diff --git a/aafwk.gni b/aafwk.gni index 53a5209d70334792238fe63ce2ebab52bd7b7ef7..0e00cbd507b9624e88f2cf225ebb52c8760d1d9e 100644 --- a/aafwk.gni +++ b/aafwk.gni @@ -19,3 +19,8 @@ services_path = "${aafwk_path}/services" kits_path = "${aafwk_path}/frameworks/kits" innerkits_path = "${aafwk_path}/interfaces/innerkits" + +dispatcher_path = "${aafwk_path}/common/task_dispatcher" + +system_test_app_path = + "${aafwk_path}/test/resource/amssystemtestability/abilitySrc" diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..5a1b8db5c815e2e1e16f670b7f5b78777a616238 --- /dev/null +++ b/bundle.json @@ -0,0 +1,211 @@ +{ + "name": "@ohos/ability_runtime", + "description": "Ability管理服务统一调度和管理应用中各Ability和应用管理服务, 用于管理应用运行关系、调度应用进程生命周期及状态", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "foundation/aafwk/standard" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "ability_runtime", + "subsystem": "aafwk", + "syscap": [], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "", + "ram": "", + "deps": { + "components": [ + "appspawn", + "bytrace_standard", + "ces_standard", + "ces_standard", + "device_manager_base", + "distributeddatamgr_appdatamgr", + "distributedschedule_dms_fwk", + "dsoftbus_standard", + "form_runtime", + "hiviewdfx_hilog_native", + "ipc", + "native_appdatamgr", + "napi", + "multimodalinput_base", + "multimedia_image_standard", + "os_account_standard", + "power_manager_native", + "safwk", + "samgr_standard", + "utils_base" + ], + "third_party": [ + "libpng", + "node", + "jsoncpp", + "json" + ] + }, + "build": { + "sub_component": [ + "//foundation/aafwk/standard/services:services_target", + "//foundation/aafwk/standard/interfaces/innerkits:innerkits_target", + "//foundation/aafwk/standard/frameworks/kits/ability/native:static_subscriber_ipc", + "//foundation/aafwk/standard/frameworks/kits/ability/native:service_extension_module", + "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", + "//foundation/aafwk/standard/interfaces/kits/napi:napi_packages", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appexec" + ], + "inner_kits": [ + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/base/include/", + "header_files": [ + "ohos/aafwk/base/array_wrapper.h", + "ohos/aafwk/base/base_def.h", + "ohos/aafwk/base/base_interfaces.h", + "ohos/aafwk/base/base_object.h", + "ohos/aafwk/base/base_types.h", + "ohos/aafwk/base/bool_wrapper.h", + "ohos/aafwk/base/byte_wrapper.h", + "ohos/aafwk/base/double_wrapper.h", + "ohos/aafwk/base/float_wrapper.h", + "ohos/aafwk/base/int_wrapper.h", + "ohos/aafwk/base/light_refbase.h", + "ohos/aafwk/base/long_wrapper.h", + "ohos/aafwk/base/short_wrapper.h", + "ohos/aafwk/base/string_wrapper.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/base:base" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/want/include/", + "header_files": [ + "ohos/aafwk/content/want.h", + "ohos/aafwk/content/skills.h", + "ohos/aafwk/content/want_params.h", + "ohos/aafwk/content/match_type.h", + "ohos/aafwk/content/operation.h", + "ohos/aafwk/content/patterns_matcher.h", + "ohos/aafwk/content/pac_map.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/want:want" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/intent/include/", + "header_files": [ + "ohos/aafwk/content/intent.h", + "ohos/aafwk/content/intent_filter.h", + "ohos/aafwk/content/intent_params.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/intent:intent" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "header_files": [ + "ability_connect_callback_interface.h", + "ability_connect_callback_stub.h", + "ability_manager_client.h", + "ability_manager_errors.h", + "ability_manager_interface.h", + "ability_scheduler_interface.h", + "stop_user_callback.h", + "stop_user_callback_stub.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/include", + "header_files": [ + "ability_context.h" + ] + }, + "name": "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/runtime/include/", + "header_files": [ + "js_runtime.h", + "runtime.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/runtime:runtime" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/napi_base_context/include", + "header_files": [ + "napi_base_context.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/napi_base_context:napi_base_context" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include", + "header_files": [ + "appmgr/app_mgr_client.h", + "appmgr/iapp_state_callback.h", + "appmgr/app_state_callback_host.h", + "appmgr/app_mgr_constants.h", + "appmgr/app_process_data.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/frameworks/kits/ability/native/include/", + "header_files": [ + "extension.h", + "extension_base.h", + "service_extension.h", + "extension_module_loader.h" + ] + }, + "name": "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/common/task_dispatcher/include", + "header_files": [ + "dispatcher/parallel_task_dispatcher.h", + "dispatcher/task_dispatcher_context", + "threading/runnable.h", + "task/task.h" + ] + }, + "name": "//foundation/aafwk/standard/common:common_target" + } + ], + "test": [ + "//foundation/aafwk/standard/frameworks/kits/content/cpp/test:unittest", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test:unittest", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test:moduletest", + "//foundation/aafwk/standard/frameworks/kits/test:moduletest", + "//foundation/aafwk/standard/services/test:moduletest", + "//foundation/aafwk/standard/services:unittest", + "//foundation/aafwk/standard/common/task_dispatcher/test:unittest", + "//foundation/aafwk/standard/common/test:moduletest", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/test:unittest", + "//foundation/aafwk/standard/frameworks/kits/appkit/test:moduletest", + "//foundation/aafwk/standard/services/appmgr/test:unittest" + ] + } + } +} \ No newline at end of file diff --git a/common/BUILD.gn b/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..682a10893206fcf67f22c99243334b3be37f69bd --- /dev/null +++ b/common/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +group("common_target") { + deps = [ "task_dispatcher:appkit_dispatcher_td" ] +} diff --git a/common/task_dispatcher/BUILD.gn b/common/task_dispatcher/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..eb88f17eef79a63ee123243f4b8d2e8328446a0b --- /dev/null +++ b/common/task_dispatcher/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +config("appkit_config") { + config("appkit_public_config") { + visibility = [ ":*" ] + include_dirs = [] + } + include_dirs = [] +} + +ohos_shared_library("appkit_dispatcher_td") { + include_dirs = [ + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + + "${aafwk_path}/common/task_dispatcher/include/dispatcher", + "${aafwk_path}/common/task_dispatcher/include/task", + "${aafwk_path}/common/task_dispatcher/include/threading", + "${aafwk_path}/frameworks/kits/appkit/native/app/include/task", + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + ] + + configs = [ ":appkit_config" ] + + public_configs = [ ":appkit_public_config" ] + + sources = [ + "${aafwk_path}/common/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp", + "${aafwk_path}/common/task_dispatcher/src/dispatcher/global_task_dispatcher.cpp", + "${aafwk_path}/common/task_dispatcher/src/dispatcher/group_impl.cpp", + "${aafwk_path}/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp", + "${aafwk_path}/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${aafwk_path}/common/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp", + "${aafwk_path}/common/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp", + "${aafwk_path}/common/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp", + "${aafwk_path}/common/task_dispatcher/src/task/barrier_handler.cpp", + "${aafwk_path}/common/task_dispatcher/src/task/sync_task.cpp", + "${aafwk_path}/common/task_dispatcher/src/task/task.cpp", + "${aafwk_path}/common/task_dispatcher/src/threading/default_thread_factory.cpp", + "${aafwk_path}/common/task_dispatcher/src/threading/default_worker_pool_config.cpp", + "${aafwk_path}/common/task_dispatcher/src/threading/task_executor.cpp", + "${aafwk_path}/common/task_dispatcher/src/threading/work_thread.cpp", + "${aafwk_path}/common/task_dispatcher/src/threading/worker_pool.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + part_name = "ability_runtime" +} diff --git a/common/task_dispatcher/include/dispatcher/base_task_dispatcher.h b/common/task_dispatcher/include/dispatcher/base_task_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..f55a2b6f081ada770d864b37bd864790dfa206f1 --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/base_task_dispatcher.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_BASE_TASK_DISPATCHER_H +#define OHOS_APP_DISPATCHER_BASE_TASK_DISPATCHER_H + +#include +#include +#include "revocable.h" +#include "runnable.h" +#include "task.h" +#include "group.h" +#include "group_impl.h" +#include "task_dispatcher.h" +#include "task_execute_interceptor.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Base implementation for interface of TaskDispatcher. + */ + +class BaseTaskDispatcher : public TaskDispatcher { +public: + BaseTaskDispatcher(const std::string &dispatcherName, const TaskPriority priority); + virtual ~BaseTaskDispatcher(){}; + + /** + * Called when post a task to the TaskDispatcher with waiting Attention: Call + * this function of Specific dispatcher on the corresponding thread will lock. + * @param runnable is the job to execute. + */ + virtual ErrCode SyncDispatch(const std::shared_ptr &runnable) override = 0; + + /** + * Called when post a task to the TaskDispatcher without waiting. + * + * @param runnable is the job to execute. + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + virtual std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable) override = 0; + + /** + * Called when post a task group to the TaskDispatcher and without waiting. + * @param runnable is the job to execute. + * @param delayMs indicate the delay time to execute. + * @return an interface for revoke the task if it hasn't been invoked. + */ + virtual std::shared_ptr DelayDispatch( + const std::shared_ptr &runnable, long delayMs) override = 0; + /** + * Set a barrier and meanwhile a sync task that execute after all tasks finished. + * @param runnable is the job to execute after barrier. + */ + ErrCode SyncDispatchBarrier(const std::shared_ptr &runnable) override; + + /** + * Set a barrier and meanwhile an async task that execute after all tasks finished. + * @param runnable is the job to execute after jobs in group. + */ + ErrCode AsyncDispatchBarrier(const std::shared_ptr &runnable) override; + /** + * Create a group. + * @return a new created group. + */ + std::shared_ptr CreateDispatchGroup() override; + + /** + * Called when post a task to the TaskDispatcher and relates it to a group + * without waiting. + * @param group related by task. + * @param runnable is the job to execute. + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + virtual std::shared_ptr AsyncGroupDispatch( + const std::shared_ptr &group, const std::shared_ptr &runnable) override; + + /** + * Synchronously waiting all tasks in the group to be done. + * @param group contains a serial of jobs. + * @param timeout is the max waiting time for jobs in group execute, in ms. + * @return true if all jobs in group has finished or false if timeout occurs. + * + */ + bool GroupDispatchWait(const std::shared_ptr &group, long timeout) override; + + /** + * Asynchronously waiting all tasks in the group to be done. |task| will be run after waiting. + * + * @param group contains a serial of jobs. + * @param runnable executes after all jobs in group finished. + * + */ + ErrCode GroupDispatchNotify( + const std::shared_ptr &group, const std::shared_ptr &runnable) override; + + /** + * Called to dispatch |task| |iterations| times and wait. + * + * @param task is the job to execute multi times. + * @param iterations indicates times the task should be executed. + * + */ + ErrCode ApplyDispatch(const std::shared_ptr> &task, long iterations) override; + + /** + * Gets the priority. + * @return The priority. + */ + TaskPriority GetPriority() const; + + /** + * Create span and set HiTraceId for task, and then tracePoint information + * @param task of which the information to tracePoint + * @param isAsyncTask whether the task is async + * @param dispatcherName the name of dispatcher which post the task + * @return valid HiTraceId if set successfully + * + */ + void TracePointBeforePost(std::shared_ptr &task, bool isAsyncTask, const std::string &dispatcherName) const; + + /** + * TracePoint information after post task + * + * @param task of which the information to tracePoint + * @param isAsyncTask whether the task is async + * @param dispatcherName the name of dispatcher which post the task + * + */ + void TracePointAfterPost(std::shared_ptr &task, bool isAsyncTask, const std::string &dispatcherName) const; + +protected: + /** + * Name of dispatcher. + * + */ + std::string dispatcherName_; + + TaskPriority taskPriority_; + +protected: + /** + * Check for the |task| argument. + * + * @param task The task to check + * + */ + ErrCode Check(const std::shared_ptr &task) const; + + /** + * Check for the |group| argument. + * + * @param group The group to check. + * @return GroupImpl + * + */ + std::shared_ptr CastToGroupImpl(const std::shared_ptr &group); + + /** + * Gets the task interceptor. + * Subclasses override this function to change the interceptor. + * + * @return The TaskExecuteInterceptor. + * + */ + std::shared_ptr GetInterceptor(); + +private: + static std::atomic SEQUENCE_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/dispatcher/blocking_queue.h b/common/task_dispatcher/include/dispatcher/blocking_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..74d6605ba8c0d23c9d08d8736445f68fde1bb937 --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/blocking_queue.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_BLOCKING_QUEUE_H +#define OHOS_APPEXECFWK_BLOCKING_QUEUE_H + +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "task.h" +#include "task_priority.h" + +namespace OHOS { +namespace AppExecFwk { +struct PriorityTaskWrapper { + PriorityTaskWrapper(const TaskPriority &priority, std::shared_ptr task) : task_(task) + { + switch (priority) { + case TaskPriority::HIGH: + priorityWeight_ = HIGH_PRIORITY_WEIGHT; + break; + case TaskPriority::DEFAULT: + priorityWeight_ = DEFAULT_PRIORITY_WEIGHT; + break; + case TaskPriority::LOW: + priorityWeight_ = LOW_PRIORITY_WEIGHT; + break; + default: + priorityWeight_ = DEFAULT_PRIORITY_WEIGHT; + break; + } + } + PriorityTaskWrapper() = delete; + ~PriorityTaskWrapper(){}; + + int priorityWeight_; + std::shared_ptr task_; + static constexpr int HIGH_PRIORITY_WEIGHT = 2; + static constexpr int DEFAULT_PRIORITY_WEIGHT = 1; + static constexpr int LOW_PRIORITY_WEIGHT = 0; +}; +struct CompareTaskPriority { + bool operator()(const std::shared_ptr &wrapper1, + const std::shared_ptr &wrapper2) const + { + return wrapper1->priorityWeight_ < wrapper2->priorityWeight_; + } +}; + +class BlockingQueue { +public: + BlockingQueue() : mutex_(), empty_(), stopFlag_(false){}; + ~BlockingQueue(){}; + + bool Offer(const std::shared_ptr &task) + { + std::unique_lock lock(mutex_); + queue_.push(task); + empty_.notify_all(); + return true; + } + + std::shared_ptr Take() + { + std::unique_lock lock(mutex_); + while (queue_.empty() && !stopFlag_) { + APP_LOGI("BlockingQueue::Take empty_wait"); + empty_.wait(lock); + } + + std::shared_ptr front = nullptr; + if (!queue_.empty()) { + front = queue_.top(); + queue_.pop(); + } + return front; + } + + std::shared_ptr Poll(long deleyedMs) + { + auto const timeout = std::chrono::steady_clock::now() + std::chrono::milliseconds(deleyedMs); + std::unique_lock lock(mutex_); + while (queue_.empty() && !stopFlag_) { + if (empty_.wait_until(lock, timeout) == std::cv_status::timeout) { + APP_LOGI("BlockingQueue::Poll timeout"); + break; + } + } + std::shared_ptr front = nullptr; + if (!queue_.empty()) { + front = queue_.top(); + queue_.pop(); + } + return front; + } + + size_t Size() + { + std::lock_guard lock(mutex_); + return queue_.size(); + } + + bool Empty() + { + std::unique_lock lock(mutex_); + return queue_.empty(); + } + + void Stop() + { + std::unique_lock lock(mutex_); + stopFlag_.store(true); + empty_.notify_all(); + } + + BlockingQueue(const BlockingQueue &) = delete; + BlockingQueue &operator=(const BlockingQueue &) = delete; + +private: + std::mutex mutex_; + std::condition_variable empty_; + std::priority_queue, std::deque>, + CompareTaskPriority> + queue_; + std::atomic stopFlag_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif diff --git a/common/task_dispatcher/include/dispatcher/global_task_dispatcher.h b/common/task_dispatcher/include/dispatcher/global_task_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..3af52cc747fc28f763c746079aec6f29bde66169 --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/global_task_dispatcher.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_GLOBAL_TASK_DISPATCHER_H +#define FOUNDATION_APPEXECFWK_OHOS_GLOBAL_TASK_DISPATCHER_H + +#include +#include "parallel_task_dispatcher_base.h" +#include "task_executor.h" +#include "task_priority.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Dispatcher for global thread model. + */ +class GlobalTaskDispatcher : public ParallelTaskDispatcherBase { +private: + static std::string DISPATCHER_NAME_; + +public: + GlobalTaskDispatcher(TaskPriority priority, std::shared_ptr &executor); + ~GlobalTaskDispatcher(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/dispatcher/group_impl.h b/common/task_dispatcher/include/dispatcher/group_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..4075ee5f59ed84456fa254f6bf83b5ad6caed312 --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/group_impl.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_GROUP_IMPL_H +#define OHOS_APP_DISPATCHER_GROUP_IMPL_H +#include +#include +#include +#include +#include "group.h" +#include "runnable.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * A group used to associated with tasks. + */ +class GroupImpl : public Group { +public: + GroupImpl(); + ~GroupImpl() = default; + /** + * Wait all tasks associated to this group to be done. + * @param timeout is the max waiting time for jobs in group execute, in ms. + * @return true if successfully wait. + */ + bool AwaitAllTasks(long timeout); + + /** + * Associates a task to this group. + */ + void Associate(); + + /** + * Notify group that a task is done or canceled. + */ + void NotifyTaskDone(); + + /** + * Adds the |notification| to notification list. + * If all tasks are already done, |notification| will immediately be called on current thread. + * Attention: If tasks are added just this time, it may not be considered. + * @param notification Called when all tasks done. + */ + bool AddNotification(const std::shared_ptr ¬ification); + +private: + const static int MAX_TASK = 1000; + std::atomic count_; + std::deque> notifications_; + std::mutex dataMutex_; + std::condition_variable condition_; + +private: + /** + * Notify all tasks and remove from queue. + * Attention: Notifications added after all tasks done is not guaranteed. + */ + void DrainNotifications(); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/dispatcher/parallel_task_dispatcher.h b/common/task_dispatcher/include/dispatcher/parallel_task_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..8c429313a59c4be1bd2051a149a6d73e489af262 --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/parallel_task_dispatcher.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_PARALLEL_TASK_DISPATCHER_H +#define FOUNDATION_APPEXECFWK_OHOS_PARALLEL_TASK_DISPATCHER_H + +#include +#include +#include +#include +#include +#include "parallel_task_dispatcher_base.h" +#include "runnable.h" +#include "sync_task.h" +#include "task_priority.h" +#include "task_execute_interceptor.h" +#include "task_executor.h" +#include "barrier_handler.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Customed parallel TaskDispatcher which means it can be created multi times. + */ +class ParallelTaskDispatcher : public ParallelTaskDispatcherBase { +public: + ParallelTaskDispatcher(const std::string &name, TaskPriority priority, std::shared_ptr &executor); + ~ParallelTaskDispatcher(){}; + + /** + * Set a barrier and meanwhile a sync task that execute after all tasks finished. + * + * @param runnable is the job to execute after barrier. + * @throws NullPointerException if |task| is null. + * + */ + ErrCode SyncDispatchBarrier(const std::shared_ptr &runnable); + + /** + * Set a barrier and meanwhile an async task that execute after all tasks finished. + * + * @param runnable is the job to execute after jobs in group. + * @throws NullPointerException if |task| is null. + * + */ + ErrCode AsyncDispatchBarrier(const std::shared_ptr &runnable); + +protected: + std::shared_ptr GetInterceptor(); + +private: + static const std::string DISPATCHER_TAG; + static const std::string ASYNC_DISPATCHER_BARRIER_TAG; + static const std::string SYNC_DISPATCHER_BARRIER_TAG; + std::shared_ptr barrierHandler_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/dispatcher/parallel_task_dispatcher_base.h b/common/task_dispatcher/include/dispatcher/parallel_task_dispatcher_base.h new file mode 100644 index 0000000000000000000000000000000000000000..22b248f0dfcaca62b97d5c5a04d449fef8b6453e --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/parallel_task_dispatcher_base.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_PARALLEL_TASK_DISPATCHER_BASE_H +#define FOUNDATION_APPEXECFWK_OHOS_PARALLEL_TASK_DISPATCHER_BASE_H + +#include +#include +#include +#include +#include + +#include "base_task_dispatcher.h" +#include "group.h" +#include "revocable.h" +#include "runnable.h" +#include "sync_task.h" +#include "task.h" +#include "task_priority.h" +#include "task_executor.h" +#include "task_execute_interceptor.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Base implementation for parallel TaskDispatcher + */ +class ParallelTaskDispatcherBase : public BaseTaskDispatcher, + public std::enable_shared_from_this { +public: + ParallelTaskDispatcherBase( + TaskPriority taskPriority, std::shared_ptr &executor, const std::string &dispatcherName); + virtual ~ParallelTaskDispatcherBase() = default; + /** + * Called when post a task to the TaskDispatcher with waiting Attention: Call + * this function of Specific dispatcher on the corresponding thread will lock. + * + * @param runnable is the job to execute + * + */ + ErrCode SyncDispatch(const std::shared_ptr &runnable) override; + + /** + * Called when post a task to the TaskDispatcher without waiting + * + * @param runnable is the job to execute + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable) override; + + /** + * Called when post a task group to the TaskDispatcher and without waiting + * + * @param runnable is the job to execute + * @param delayMs indicate the delay time to execute + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs) override; + + /** + * Called when post a task to the TaskDispatcher and relates it to a group + * without waiting. + * + * @param group related by task. + * @param runnable is the job to execute. + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + std::shared_ptr AsyncGroupDispatch( + const std::shared_ptr &group, const std::shared_ptr &runnable) override; + +protected: + virtual std::shared_ptr GetInterceptor(); + + std::shared_ptr executor_ = nullptr; + +private: + static std::string DISPATCHER_TAG; + static std::string ASYNC_DISPATCHER_TAG; + static std::string SYNC_DISPATCHER_TAG; + static std::string DELAY_DISPATCHER_TAG; + static std::string ASYNC_GROUP_DISPATCHER_TAG; + + ErrCode InterceptedExecute(std::shared_ptr &task); + + class MyTaskListener : public TaskListener { + private: + std::function callback_; + + public: + void OnChanged(const TaskStage &stage) + { + if (stage.IsDone()) { + APP_LOGI("ParallelTaskDispatcherBase task done."); + callback_(); + } + } + // set callback function + void Callback(const std::function &callbackFunction) + { + callback_ = std::move(callbackFunction); + } + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/dispatcher/serial_task_dispatcher.h b/common/task_dispatcher/include/dispatcher/serial_task_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..0777833e7aed6cc3e01bfc5bdbb781cb3bfedb48 --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/serial_task_dispatcher.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_SERIAL_TASK_DISPATCHER_H +#define OHOS_APP_DISPATCHER_SERIAL_TASK_DISPATCHER_H + +#include + +#include "base_task_dispatcher.h" +#include "task.h" +#include "sync_task.h" +#include "task_executor.h" +#include "task_priority.h" +#include "revocable.h" +#include "task_listener.h" +#include "concurrent_queue.h" +#include "runnable.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Dispatcher for serial thread model. + */ +class SerialTaskDispatcher : public BaseTaskDispatcher, public std::enable_shared_from_this { +public: + SerialTaskDispatcher( + const std::string &dispatcherName, const TaskPriority priority, const std::shared_ptr &executor); + ~SerialTaskDispatcher(){}; + + /** + * Gets waiting tasks count of SerialTaskDispatcher. + * + * @return The waiting tasks count of SerialTaskDispatcher. + * + */ + int GetWorkingTasksSize(); + + /** + * Gets name of SerialTaskDispatcher. + * + * @return The name of SerialTaskDispatcher. + * + */ + std::string GetDispatcherName(); + + /** + * Called when post a task to the TaskDispatcher with waiting Attention: Call + * this function of Specific dispatcher on the corresponding thread will lock. + * + * @param runnable is the job to execute + * + */ + ErrCode SyncDispatch(const std::shared_ptr &runnable); + + /** + * Called when post a task to the TaskDispatcher without waiting + * + * @param runnable is the job to execute + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable); + + /** + * Called when post a task group to the TaskDispatcher and without waiting + * + * @param runnable is the job to execute + * @param delayMs indicate the delay time to execute + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs); +private: + ErrCode OnNewTaskIn(std::shared_ptr &task); + + ErrCode Prepare(std::shared_ptr &task); + + /** + * Callback for task when finish. + * + */ + void OnTaskDone(); + + bool Schedule(); + + /** + * Do task in turn, until the task queue is empty. + * + * @param isExhausted is an inaccurate judge indicate that the workingTasks is empty. If true, do double-check. + * @return true if has work remain to do else false. + * + */ + bool DoNext(bool isExhausted); + + void DoWork(std::shared_ptr &task); +private: + static std::string DISPATCHER_TAG; + static std::string ASYNC_DISPATCHER_TAG; + static std::string SYNC_DISPATCHER_TAG; + static std::string DELAY_DISPATCHER_TAG; + + std::atomic running_; + ConcurrentQueue> workingTasks_; + + std::shared_ptr executor_; + std::mutex mutex_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif diff --git a/common/task_dispatcher/include/dispatcher/spec_dispatcher_config.h b/common/task_dispatcher/include/dispatcher/spec_dispatcher_config.h new file mode 100644 index 0000000000000000000000000000000000000000..64ecdb2e320afa6bcdb322e2a78fc6e800b2c5de --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/spec_dispatcher_config.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_SPEC_DISPATCHER_CONFIG_H +#define OHOS_APP_DISPATCHER_SPEC_DISPATCHER_CONFIG_H + +#include +#include "task_priority.h" + +namespace OHOS { +namespace AppExecFwk { +class SpecDispatcherConfig { +public: + static constexpr const char *MAIN = "DispatcherMain"; + static constexpr const char *UI = "DispatcherUI"; + +public: + SpecDispatcherConfig(std::string name, TaskPriority priority) + { + name_ = name; + priority_ = priority; + } + ~SpecDispatcherConfig(){}; + std::string GetName() + { + return name_; + } + + TaskPriority GetPriority() + { + return priority_; + } + +private: + std::string name_; + TaskPriority priority_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif diff --git a/common/task_dispatcher/include/dispatcher/spec_task_dispatcher.h b/common/task_dispatcher/include/dispatcher/spec_task_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..138f78aa7680721f5dfbd357cba8a816258d1cf1 --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/spec_task_dispatcher.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_SPEC_TASK_DISPATCHER_H +#define OHOS_APP_DISPATCHER_SPEC_TASK_DISPATCHER_H + +#include +#include "base_task_dispatcher.h" +#include "task.h" +#include "sync_task.h" +#include "revocable.h" +#include "runnable.h" +#include "task/task_dispatcher_handler.h" +#include "event_runner.h" +#include "spec_dispatcher_config.h" + +namespace OHOS { +namespace AppExecFwk { +class EventRunner; +class SpecTaskDispatcher : public BaseTaskDispatcher, public std::enable_shared_from_this { +public: + /** + * constructor for special task dispatchers + * + * @param config which is the config of this dispatcher + * @param runner event runner + * + */ + SpecTaskDispatcher(std::shared_ptr config, std::shared_ptr runner); + ~SpecTaskDispatcher(){}; + + /** + * Called when post a task to the TaskDispatcher with waiting Attention: Call + * this function of Specific dispatcher on the corresponding thread will lock. + * + * @param runnable is the job to execute + * + */ + ErrCode SyncDispatch(const std::shared_ptr &runnable); + + /** + * Called when post a task to the TaskDispatcher without waiting + * + * @param runnable is the job to execute + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable); + + /** + * Called when post a task group to the TaskDispatcher and without waiting + * + * @param runnable is the job to execute + * @param delayMs indicate the delay time in milliseconds to execute + * @return an interface for revoke the task if it hasn't been invoked. + * + */ + std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs); + +private: + static std::string DISPATCHER_TAG; + + static std::string ASYNC_DISPATCHER_TAG; + + static std::string SYNC_DISPATCHER_TAG; + + static std::string DELAY_DISPATCHER_TAG; + + std::shared_ptr handler_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/dispatcher/task_dispatcher_context.h b/common/task_dispatcher/include/dispatcher/task_dispatcher_context.h new file mode 100644 index 0000000000000000000000000000000000000000..f289bec7e596cb29a3b766f57234f85b56faaece --- /dev/null +++ b/common/task_dispatcher/include/dispatcher/task_dispatcher_context.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_TASK_DISPATCHER_CONTEXT_H +#define FOUNDATION_APPEXECFWK_OHOS_TASK_DISPATCHER_CONTEXT_H + +#include +#include +#include +#include +#include +#include +#include "default_worker_pool_config.h" +#include "global_task_dispatcher.h" +#include "parallel_task_dispatcher.h" +#include "serial_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_executor.h" +#include "task_priority.h" +#include "worker_pool_config.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Dispatcher management for all kinds dispatchers and executor. + */ +class TaskDispatcherContext { +public: + /** + * Constructs the object. + * + */ + TaskDispatcherContext(); + + /** + * Constructs the object with parameter executor. + * + * @param executor the TaskExecutor to set. + * + */ + TaskDispatcherContext(const std::shared_ptr &executor); + + ~TaskDispatcherContext(); + + /** + * Gets the worker pool configuration. + * + * @return The worker pool configuration. + * + */ + std::shared_ptr GetWorkerPoolConfig() const; + + /** + * Gets WorkerThread information in WorkerPool. + * + * @return The WorkerThread information in WorkerPool. + * + */ + std::map GetWorkerThreadsInfo() const; + + /** + * Gets the serialDispatchers. + * + * @return The serialDispatchers. + * + */ + std::map, std::string> GetSerialDispatchers() const; + + /** + * Gets waiting tasks count of TaskExecutor. + * + * @return The waiting tasks count of TaskExecutor. + * + */ + int GetWaitingTasksCount() const; + + /** + * Gets finished tasks count of TaskExecutor. + * + * @return The finished tasks count of TaskExecutor. + * + */ + long GetTaskCounter() const; + + /** + * Creates a serial dispatcher. + * + * @param name The dispatcher name + * @param priority The priority of tasks + * + * @return a new object of SerialTaskDispatcher + * + */ + std::shared_ptr CreateSerialDispatcher(const std::string &name, TaskPriority priority); + + /** + * Creates a parallel dispatcher. + * + * @param name The dispatcher name + * @param priority The priority of tasks + * + * @return a new object of ParallelTaskDispatcher + * + */ + std::shared_ptr CreateParallelDispatcher(const std::string &name, TaskPriority priority); + + /** + * Gets the global task dispatcher. + * + * @param priority The priority + * + * @return A global task dispatcher which cannot be null. + * + */ + std::shared_ptr GetGlobalTaskDispatcher(TaskPriority priority); + + /** + * Shutdown all about task dispatcher. + * + * @param force Indicate whether force close. + * + */ + ErrCode Shutdown(bool force); + +private: + static constexpr int HIGH_PRIORITY_INDEX = 0; + + static constexpr int DEFAULT_PRIORITY_INDEX = 1; + + static constexpr int LOW_PRIORITY_INDEX = 2; + + static constexpr int PRIORITY_COUNT = 3; + + mutable std::mutex mtx_; + + std::map, std::string> serialDispatchers_; + + std::vector> globalDispatchers_; + + std::shared_ptr config_ = nullptr; + + std::shared_ptr executor_ = nullptr; + +private: + int MapPriorityIndex(TaskPriority priority) const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/task/barrier_handler.h b/common/task_dispatcher/include/task/barrier_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..179de54592376cf672c45fb2537fca8f5b9ed1c6 --- /dev/null +++ b/common/task_dispatcher/include/task/barrier_handler.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_BARRIER_HANDLER_H +#define OHOS_APP_DISPATCHER_BARRIER_HANDLER_H + +#include +#include "appexecfwk_errors.h" +#include "task.h" +#include "task_listener.h" +#include "task_executor.h" +#include "task_execute_interceptor.h" +#include "task_stage.h" + +namespace OHOS { +namespace AppExecFwk { +class BarrierHandler : public TaskExecuteInterceptor { +public: + BarrierHandler(const std::shared_ptr &executor); + ~BarrierHandler() = default; + /** + * Intercept executing a task. + */ + ErrCode Intercept(std::shared_ptr &task) override; + + /** + * Adds a task with barrier semantics. + */ + ErrCode AddBarrier(std::shared_ptr &barrierTask); + +private: + ErrCode ListenToTask(std::shared_ptr &task); + void OnTaskDone(std::shared_ptr &task); + bool AddTaskAfterBarrier(std::shared_ptr &task); + bool HasTask(const std::set> &tasks); + std::set> CreateTaskSet(std::shared_ptr &firstTask); + +private: + class BarrierPair { + public: + std::set> tasks_; + std::shared_ptr barrier_; + + BarrierPair(const std::set> &tasks, const std::shared_ptr &barrier) + { + tasks_ = tasks; + barrier_ = barrier; + }; + ~BarrierPair() = default; + }; + + class MyTaskListener : public TaskListener { + private: + std::function callback_; + + public: + void OnChanged(const TaskStage &stage) + { + if (stage.IsDone()) { + APP_LOGI("BarrierHandler task done."); + callback_(); + } + }; + // set callback function + void Callback(const std::function &callbackFunction) + { + callback_ = std::move(callbackFunction); + }; + }; + + std::mutex barrierLock_; + std::shared_ptr executor_; + std::deque> barrierQueue_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/task/sync_task.h b/common/task_dispatcher/include/task/sync_task.h new file mode 100644 index 0000000000000000000000000000000000000000..08df7c7cf48daeaee9872fc780e33dd972d6de6d --- /dev/null +++ b/common/task_dispatcher/include/task/sync_task.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_TASK_SYNC_TASK_H +#define OHOS_APP_DISPATCHER_TASK_SYNC_TASK_H + +#include +#include + +#include "runnable.h" +#include "task_priority.h" +#include "task.h" +#include "app_log_wrapper.h" +#include "base_task_dispatcher.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * SyncTask is the synchronized task which provide synchronized method. + */ +class SyncTask final : public Task { +public: + SyncTask(const std::shared_ptr &runnable, TaskPriority priority, + const std::shared_ptr &baseTaskDispatcher); + ~SyncTask() = default; + void Run() override; + + void WaitTask(); + +private: + std::atomic executed_; + std::mutex mutex_; + std::condition_variable condition_variable_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/task/task.h b/common/task_dispatcher/include/task/task.h new file mode 100644 index 0000000000000000000000000000000000000000..b73c09578cf9ad2b11e5642c787672324814251d --- /dev/null +++ b/common/task_dispatcher/include/task/task.h @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_TASK_H +#define OHOS_APP_DISPATCHER_TASK_H + +#include +#include +#include +#include +#include "concurrent_queue.h" +#include "revocable.h" +#include "runnable.h" +#include "task_listener.h" +#include "task_priority.h" +#include "task_stage.h" + +namespace OHOS { +namespace AppExecFwk { +class BaseTaskDispatcher; +class Task : public Revocable { +public: + Task(const std::shared_ptr &runnable, const TaskPriority priority, + const std::shared_ptr &baseTaskDispatcher); + + virtual ~Task(); + + /** + * @brief invoke the function to execute the task + */ + virtual void Run(); + + /** + * @brief Gets the priority. + * @return The priority. + */ + TaskPriority GetPriority() const; + + /** + * @brief Sets the sequence. + * @param sequence The sequence + */ + void SetSequence(long sequence); + + /** + * @brief Gets the sequence. + * @return The sequence. + */ + long GetSequence() const; + + /** + * @brief Revoke this task if hasn't run. + * @return true if set revoked or already revoked. False if the task has start executing. + */ + bool Revoke() override; + + /** + * @brief Adds a task listener. + * @param listener The listener + */ + void AddTaskListener(const std::shared_ptr &listener); + + /** + * @brief Called when task is about to run. + */ + void BeforeTaskExecute(); + + /** + * @brief Called when task is done. + */ + void AfterTaskExecute(); + + /** + * @brief Called when task is canceled. + */ + void OnTaskCanceled(); + + bool operator==(std::shared_ptr &rec) const; + +protected: + std::shared_ptr runnable_; + +private: + using RevokeResult = enum { + // Maybe already run. + FAIL, + // Convert |revoked| flag from false to true. + SUCCESS, + // The |revoked| flag is already set to true. + ALREADY_REVOKED + }; + + /** + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param - + * @return bool + */ + bool EnterExecute(); + + RevokeResult SetRevoked(); + + void ConcurrentQueueStatusUpdate(const TaskStage::TASKSTAGE taskstage); + +private: + const static unsigned int EXECUTED = (1 << 0); + const static unsigned int REVOKED = (1 << 1); + long sequence_ = 0; + std::atomic state_; + TaskPriority priority_; + std::shared_ptr revocable_ = nullptr; + ConcurrentQueue> taskListeners_; + std::shared_ptr baseTaskDispatcher_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_APP_DISPATCHER_TASK_H diff --git a/common/task_dispatcher/include/task/task_handler_libevent_adapter.h b/common/task_dispatcher/include/task/task_handler_libevent_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..b5cfb0e86d9b6f5177feede85bed7130dad915dc --- /dev/null +++ b/common/task_dispatcher/include/task/task_handler_libevent_adapter.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_TASK_HANDLER_LIBEVENT_ADAPTER_H +#define OHOS_APP_DISPATCHER_TASK_HANDLER_LIBEVENT_ADAPTER_H + +#include +#include "task_dispatcher_handler.h" +#include "runnable.h" +#include "event_runner.h" +#include "event_handler.h" +#include "event_queue.h" +namespace OHOS { +namespace AppExecFwk { +class TaskHandlerLibeventAdapter final : public EventHandler, public TaskDispatcherHandler { +public: + TaskHandlerLibeventAdapter(const std::shared_ptr &eventRunner) : EventHandler(eventRunner){}; + virtual ~TaskHandlerLibeventAdapter(){}; + bool Dispatch(const std::shared_ptr &runnable) override + { + APP_LOGI("TaskHandlerLibeventAdapter::Dispatch called."); + return EventHandler::PostTask(*(runnable.get()), EventQueue::Priority::HIGH); + } + + bool Dispatch(const std::shared_ptr &runnable, long delayMs) override + { + APP_LOGI("TaskHandlerLibeventAdapter::Delay Dispatch called."); + return EventHandler::PostTask(*(runnable.get()), delayMs, EventQueue::Priority::HIGH); + } + bool DispatchSync(const std::shared_ptr &runnable) override + { + APP_LOGI("TaskHandlerLibeventAdapter::Delay Dispatch Sync called."); + return EventHandler::PostSyncTask(*(runnable.get()), EventQueue::Priority::HIGH); + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif diff --git a/common/task_dispatcher/include/task/task_listener.h b/common/task_dispatcher/include/task/task_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..b1891899515af939f9bac91e872a42700427f559 --- /dev/null +++ b/common/task_dispatcher/include/task/task_listener.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_TASK_TASK_LISTENER_H +#define OHOS_APP_DISPATCHER_TASK_TASK_LISTENER_H + +#include "task_stage.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Listen to events of task execution. + */ +class TaskListener { +public: + virtual ~TaskListener(){}; + /** + * @brief Called when task stage changed. + * @param stage The stage + * @return void + */ + virtual void OnChanged(const TaskStage &stage) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/task/task_stage.h b/common/task_dispatcher/include/task/task_stage.h new file mode 100644 index 0000000000000000000000000000000000000000..e0244d0fbeefaee18300eeb2774b8ee4e3822f52 --- /dev/null +++ b/common/task_dispatcher/include/task/task_stage.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_TASK_TASK_STAGE_H +#define OHOS_APP_DISPATCHER_TASK_TASK_STAGE_H + +namespace OHOS { +namespace AppExecFwk { +class TaskStage { +public: + TaskStage() : index_(0) + {} + TaskStage(int index) + { + index_ = index; + } + ~TaskStage() = default; + /** + * Enumeration for task execute stage. + * Attention: |REVOKED| is conflict with |AFTER_EXECUTE| and |BEFORE_EXECUTE|, which means, + * once |REVOKED|, the other stage will not be notified. So use |isDone| for judging. + */ + enum TASKSTAGE { BEFORE_EXECUTE = 0, AFTER_EXECUTE = 1, REVOKED = 2 }; + /** + * Gets the index. + * @return The index. + */ + int GetIndex() const + { + return index_; + } + + /** + * Determines if done. + * @return True if the task has been finished(maybe canceled). False if it's going to execute. + */ + bool IsDone() const + { + return ((index_ == AFTER_EXECUTE) || (index_ == REVOKED)); + } + +private: + int index_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/threading/concurrent_queue.h b/common/task_dispatcher/include/threading/concurrent_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..a5b7cc6530de33ac1611a332867c21d8feb8b51a --- /dev/null +++ b/common/task_dispatcher/include/threading/concurrent_queue.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_CONCURRENT_QUEUE_H +#define OHOS_APPEXECFWK_CONCURRENT_QUEUE_H + +#include +#include +#include +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +template +class ConcurrentQueue { +public: + ConcurrentQueue() : empty_(){}; + ~ConcurrentQueue() = default; + + /** + * get data without block + * @param task + * @return true + */ + bool Offer(const T &task) + { + std::unique_lock lock(mutex_); + queue_.push_back(task); + empty_.notify_all(); + return true; + } + + /** + * get data with block + * @param task + * @return data + */ + T Take() + { + std::unique_lock lock(mutex_); + while (queue_.empty()) { + APP_LOGI("ConcurrentQueue::Take blocked"); + empty_.wait(lock); + } + + T front(queue_.front()); + queue_.pop_front(); + return front; + } + T Poll() + { + std::unique_lock lock(mutex_); + if (queue_.empty()) { + APP_LOGI("ConcurrentQueue::Poll empty"); + return nullptr; + } + T front(queue_.front()); + queue_.pop_front(); + return front; + } + + size_t Size() + { + return queue_.size(); + } + size_t Empty() + { + return queue_.empty(); + } + auto Begin() + { + return queue_.begin(); + } + + auto End() + { + return queue_.end(); + } + void clear() + { + std::unique_lock lock(mutex_); + queue_.clear(); + } + + ConcurrentQueue(const ConcurrentQueue &) = delete; + ConcurrentQueue &operator=(const ConcurrentQueue &) = delete; + +private: + mutable std::mutex mutex_; + std::condition_variable empty_; + std::deque queue_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif diff --git a/common/task_dispatcher/include/threading/default_thread_factory.h b/common/task_dispatcher/include/threading/default_thread_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..67dc559d12ce969142d45ef00a3b54389dcdecd3 --- /dev/null +++ b/common/task_dispatcher/include/threading/default_thread_factory.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_THREADING_DEFAULT_THREAD_FACTORY_H +#define OHOS_APP_DISPATCHER_THREADING_DEFAULT_THREAD_FACTORY_H + +#include + +#include "thread_factory.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * DefaultThreadFactory is a default thread producer. + * + */ +class DefaultThreadFactory : public ThreadFactory { +public: + DefaultThreadFactory(); + virtual ~DefaultThreadFactory() + {} + virtual std::shared_ptr Create() override; + +private: + std::atomic_int index_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/threading/default_worker_pool_config.h b/common/task_dispatcher/include/threading/default_worker_pool_config.h new file mode 100644 index 0000000000000000000000000000000000000000..8ec371262e2716c89c01906aaed9699360363309 --- /dev/null +++ b/common/task_dispatcher/include/threading/default_worker_pool_config.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_DEFAULT_WORKER_POOL_CONFIG_H +#define OHOS_APPEXECFWK_DEFAULT_WORKER_POOL_CONFIG_H + +#include "worker_pool_config.h" + +namespace OHOS { +namespace AppExecFwk { +class DefaultWorkerPoolConfig final : public WorkerPoolConfig { +private: + static constexpr int DEFAULT_MAX_THREAD_COUNT = 32; + + static constexpr int DEFAULT_CORE_THREAD_COUNT = 16; + + static constexpr long DEFAULT_KEEP_ALIVE_TIME = 50; + +public: + DefaultWorkerPoolConfig() = default; + virtual ~DefaultWorkerPoolConfig() = default; + + int GetMaxThreadCount(void) const override; + + int GetCoreThreadCount(void) const override; + + long GetKeepAliveTime(void) const override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/threading/delay_execute_service.h b/common/task_dispatcher/include/threading/delay_execute_service.h new file mode 100644 index 0000000000000000000000000000000000000000..4b62e2cd3cfa52a780241af73c096b2f5bbafc8a --- /dev/null +++ b/common/task_dispatcher/include/threading/delay_execute_service.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_DELAY_EXECUTE_SERVICE_H +#define OHOS_APPEXECFWK_DELAY_EXECUTE_SERVICE_H + +#include "runnable.h" + +namespace OHOS { +namespace AppExecFwk { +class DelayExecuteService { +public: + virtual bool DelayExecute(const Runnable &runnable, long delayMs) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/threading/delay_queue.h b/common/task_dispatcher/include/threading/delay_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..49b72d4a5e98273c06b1b97379e2a5cabb00c403 --- /dev/null +++ b/common/task_dispatcher/include/threading/delay_queue.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_DELAY_QUEUE_H +#define OHOS_APPEXECFWK_DELAY_QUEUE_H + +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +struct DelayTaskWrapper { + DelayTaskWrapper(long delayMs, std::function runnable) : runnable_(std::move(runnable)) + { + auto now = std::chrono::high_resolution_clock::now(); + startTime_ = now + std::chrono::milliseconds(delayMs); + } + DelayTaskWrapper() = delete; + ~DelayTaskWrapper(){}; + + std::chrono::high_resolution_clock::time_point startTime_; + std::function runnable_; +}; + +struct CompareTaskDelayMs { + bool operator()( + const std::shared_ptr &other1, const std::shared_ptr &other2) const + { + return other1->startTime_ > other2->startTime_; + } +}; + +class DelayQueue { +public: + DelayQueue() : stopFlag_(false){}; + ~DelayQueue(){}; + + bool Offer(const std::shared_ptr &task) + { + std::unique_lock lock(mutex_); + taskQueue_.push(task); + emptyWait_.notify_all(); + return true; + } + + std::shared_ptr Take() + { + while (true) { + std::unique_lock lock(mutex_); + while (taskQueue_.empty() && !stopFlag_) { + APP_LOGI("DelayQueue::taskQueue_ is empty"); + emptyWait_.wait(lock); + } + + if (taskQueue_.empty() && stopFlag_) { + APP_LOGI("DelayQueue::taskQueue is empty and stopFlag is true"); + return nullptr; + } + + std::shared_ptr front = taskQueue_.top(); + auto now = std::chrono::high_resolution_clock::now(); + while (now < front->startTime_) { + emptyWait_.wait_until(lock, front->startTime_); + + now = std::chrono::high_resolution_clock::now(); + front = taskQueue_.top(); + } + std::shared_ptr check = taskQueue_.top(); + if (check->startTime_ == front->startTime_) { + taskQueue_.pop(); + return front; + } + } + } + + size_t Size() + { + std::unique_lock lock(mutex_); + return taskQueue_.size(); + } + + bool Empty() + { + std::unique_lock lock(mutex_); + return taskQueue_.empty(); + } + + void Stop() + { + std::unique_lock lock(mutex_); + stopFlag_.store(true); + emptyWait_.notify_all(); + } + + DelayQueue(const DelayQueue &) = delete; + DelayQueue &operator=(const DelayQueue &) = delete; + +private: + std::mutex mutex_; + std::condition_variable emptyWait_; + std::priority_queue, std::vector>, + CompareTaskDelayMs> + taskQueue_; + std::atomic stopFlag_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif diff --git a/common/task_dispatcher/include/threading/runnable.h b/common/task_dispatcher/include/threading/runnable.h new file mode 100644 index 0000000000000000000000000000000000000000..af541d17cae10e168dc11811a41711a337397213 --- /dev/null +++ b/common/task_dispatcher/include/threading/runnable.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_THREADING_RUNNABLE_H +#define OHOS_APP_DISPATCHER_THREADING_RUNNABLE_H + +#include + +namespace OHOS { +namespace AppExecFwk { +using Runnable = std::function; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/threading/task_execute_interceptor.h b/common/task_dispatcher/include/threading/task_execute_interceptor.h new file mode 100644 index 0000000000000000000000000000000000000000..51794fc34956cdcd03cfc6b1da46400344fca342 --- /dev/null +++ b/common/task_dispatcher/include/threading/task_execute_interceptor.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_TASK_TaskExecuteInterceptor_H +#define OHOS_APP_DISPATCHER_TASK_TaskExecuteInterceptor_H +#include "task.h" +#include "appexecfwk_errors.h" + +namespace OHOS { +namespace AppExecFwk { +class TaskExecuteInterceptor { +public: + virtual ~TaskExecuteInterceptor(){}; + virtual ErrCode Intercept(std::shared_ptr &task) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/threading/task_executor.h b/common/task_dispatcher/include/threading/task_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..7c6294c036ad5d360559a9c34d41e7ff502c4d16 --- /dev/null +++ b/common/task_dispatcher/include/threading/task_executor.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_TASK_EXECUTOR_H +#define OHOS_APPEXECFWK_TASK_EXECUTOR_H + +#include +#include +#include + +#include "appexecfwk_errors.h" + +#include "blocking_queue.h" +#include "delay_execute_service.h" +#include "delay_queue.h" +#include "task.h" +#include "work_thread.h" +#include "worker_pool.h" + +namespace OHOS { +namespace AppExecFwk { +class TaskExecutor : public WorkerPool, + public DelayExecuteService, + public Delegate, + public std::enable_shared_from_this { +public: + TaskExecutor(const std::shared_ptr &config); + virtual ~TaskExecutor(); + + void Execute(const std::shared_ptr &task); + + ErrCode DoWorks(const std::shared_ptr &worker) override; + + void Terminate(bool force); + + bool DelayExecute(const Runnable &runnable, long delayMs) override; + + int GetPendingTasksSize(); + + long GetTaskCounter(); + +protected: + void AfterRun(const std::shared_ptr &task) override; + void BeforeRun(const std::shared_ptr &task) override; + +private: + std::shared_ptr GetTask(const std::shared_ptr &workerThread); + + void TerminateConsumer(); + + bool EnsureConsumeStarted(); + + void Consume(); + + long GetAndIncrement(std::atomic &atomiclong); + + long IncrementAndGet(std::atomic &atomiclong); + +private: + static std::atomic sequence; + + std::shared_ptr delayTasks_; + + std::shared_ptr consumer_; + + std::shared_ptr pendingTasks_; + + std::atomic terminated_; + + std::atomic taskCounter_; + + std::mutex dataMutex_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/threading/thread_factory.h b/common/task_dispatcher/include/threading/thread_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..f1d685ed0f2680de2410170493ae8a1ccecfff79 --- /dev/null +++ b/common/task_dispatcher/include/threading/thread_factory.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_THREADING_THREAD_FACTORY_H +#define OHOS_APP_DISPATCHER_THREADING_THREAD_FACTORY_H + +#include "runnable.h" +#include +#include + +namespace OHOS { +namespace AppExecFwk { +class Thread { +public: + Thread() : thread_name_("Thread_0"), thread_(){}; + ~Thread() = default; + Thread(const Thread &) = delete; + Thread &operator=(const Thread &) = delete; + +public: + std::string thread_name_; + std::shared_ptr thread_; +}; + +/** + * ThreadFactory is an interface for producing thread. + */ +class ThreadFactory { +public: + ThreadFactory() = default; + virtual ~ThreadFactory(){}; + /** + * Create a new Thread with |task| as the body of thread. + * + * @param task The run body of the thread to create. + * + * @return a new created thread. maybe null. + * + */ + virtual std::shared_ptr Create() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/threading/work_thread.h b/common/task_dispatcher/include/threading/work_thread.h new file mode 100644 index 0000000000000000000000000000000000000000..036670bd6a03b714baf4d6bc1b021ec877a508ef --- /dev/null +++ b/common/task_dispatcher/include/threading/work_thread.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_THREADING_WORKER_THREAD_H +#define OHOS_APP_DISPATCHER_THREADING_WORKER_THREAD_H + +#include + +#include "thread_factory.h" +#include "task.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" + +namespace OHOS { +namespace AppExecFwk { +class WorkerThread; +/** + * Interface for a work delegate. + */ +class Delegate { +public: + /** + * Do works for WorkerThread. + * + * @param worker is the thread-holder. + * + */ + virtual ErrCode DoWorks(const std::shared_ptr &worker) = 0; +}; + +/** + * WorkerThread is a thread with a loop which can execute incoming tasks. + */ +class WorkerThread : public std::enable_shared_from_this { +public: + /** + * The construct function of the WorkerThread class. + * + * @param delegate delegates run works for this thread. + * @param firstTask if not null, take it as the first task in this thread. It can be null. + * @param factory can create a new thread which had some attributes set. + */ + WorkerThread(const std::shared_ptr &delegate, const std::shared_ptr &firstTask, + const std::shared_ptr &factory); + virtual ~WorkerThread(){}; + + void CreateThread(); + + /** + * Increase the task counter of self. + * + */ + void IncTaskCount(void); + + /** + * Gets the thread name. + * + * @return The thread name. + * + */ + std::string GetThreadName(void); + + /** + * Get and remove |firstTask| of self. + * + * @return the |firstTask|. + * + */ + std::shared_ptr PollFirstTask(void); + + /** + * Get count of tasks which were done. + * + * @return the count of tasks which were done. + * + */ + long GetTaskCounter(void); + + std::shared_ptr GetThread(void); + + /** + * join thread + * + */ + void Join(); + +protected: + std::shared_ptr thread_; + std::atomic_long task_counter_; + +private: + std::shared_ptr first_task_; + std::shared_ptr delegate_; + std::shared_ptr factory_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/include/threading/worker_pool.h b/common/task_dispatcher/include/threading/worker_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..eee772130055a408da163b6e7be15d4d3cb2e53f --- /dev/null +++ b/common/task_dispatcher/include/threading/worker_pool.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_WORKER_POOL_H +#define OHOS_APPEXECFWK_WORKER_POOL_H + +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "runnable.h" +#include "task.h" +#include "thread_factory.h" +#include "worker_pool_config.h" +#include "work_thread.h" + +namespace OHOS { +namespace AppExecFwk { +class WorkerPool { +public: + WorkerPool(const std::shared_ptr &config); + virtual ~WorkerPool(); + + long GetKeepAliveTime(void) const; + + int GetCoreThreadCount(void) const; + + int GetMaxThreadCount(void) const; + + int GetWorkCount(void) const; + + std::map GetWorkerThreadsInfo(void); + + bool AddWorker(const std::shared_ptr &delegate, const std::shared_ptr &task); + + void CreateGuardThread(); + +protected: + void ClosePool(bool interrupt); + + void OnWorkerExit(const std::shared_ptr &worker, bool isInterrupted); + + virtual void AfterRun(const std::shared_ptr &task); + + virtual void BeforeRun(const std::shared_ptr &task); + + void DecrementThread(void); + + bool CompareAndDecNum(int expectCount); + +private: + bool Init(const std::shared_ptr &config); + + bool CheckConfigParams(const std::shared_ptr &config); + + bool CheckThreadCount(int maxThreadCount, int coreThreadCount); + + bool CheckMaxThreadCount(int maxThreadCount); + + bool CheckCoreThreadCount(int coreThreadCount); + + void InterruptWorkers(void); + + static unsigned int GetWorkingThreadNum(unsigned int ctl); + + static bool IsRunning(int ctl); + + static int GetStateFromControl(unsigned int ctl); + + static int CombineToControl(unsigned int state, unsigned int count); + + void AdvanceStateTo(unsigned int target); + + bool CompareAndIncThreadNum(int expect); + + bool CompareAndDecThreadNum(int expect); + + bool CompareAndSet(std::atomic &atomicInt, int left, int right); + +private: + static const int THREAD_UPPER_LIMIT; + static const int MAX_THREAD_LOWER_LIMIT; + static const int CORE_THREAD_LOWER_LIMIT; + static const int COUNT_BITS; + static const unsigned int CAPACITY; + static const int RUNNING; + static const int CLOSING; + static const int INTERRUPT; + static const int CLEANED; + static const int CLOSED; + + int thread_limit_ = 0; + int core_thread_limit_ = 0; + long alive_time_Limit_ = 0; + + std::vector> pool_; + std::atomic control_; + std::mutex poolLock_; + std::shared_ptr factory_; + std::atomic initFlag_; + std::vector> exitPool_; + std::atomic stop_; + std::shared_ptr guardThread_; + std::mutex exitPoolLock_; + std::condition_variable exit_; + + std::mutex exitGuardLock_; + std::condition_variable exitGuard_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/common/task_dispatcher/include/threading/worker_pool_config.h b/common/task_dispatcher/include/threading/worker_pool_config.h new file mode 100644 index 0000000000000000000000000000000000000000..83f1fd9d94355121e03034a4bc153f7c93984f95 --- /dev/null +++ b/common/task_dispatcher/include/threading/worker_pool_config.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_WORKER_POOL_CONFIG_H +#define OHOS_APPEXECFWK_WORKER_POOL_CONFIG_H + +namespace OHOS { +namespace AppExecFwk { +class WorkerPoolConfig { +public: + virtual int GetMaxThreadCount(void) const = 0; + + virtual int GetCoreThreadCount(void) const = 0; + + virtual long GetKeepAliveTime(void) const = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/common/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp b/common/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d007d4aa03e142e74037df6adad919547d55c79d --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "base_task_dispatcher.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +std::atomic BaseTaskDispatcher::SEQUENCE_(0); +BaseTaskDispatcher::BaseTaskDispatcher(const std::string &dispatcherName, const TaskPriority priority) +{ + std::string name = dispatcherName; + if (name.size() == 0) { + name = "Dispatcher-" + std::to_string(SEQUENCE_.fetch_add(1, std::memory_order_relaxed)); + } + + dispatcherName_ = name; + taskPriority_ = priority; +} + +ErrCode BaseTaskDispatcher::SyncDispatchBarrier(const std::shared_ptr &task) +{ + APP_LOGI("BaseTaskDispatcher::SyncDispatchBarrier called"); + return SyncDispatch(task); +} +ErrCode BaseTaskDispatcher::AsyncDispatchBarrier(const std::shared_ptr &task) +{ + APP_LOGI("BaseTaskDispatcher::AsyncDispatchBarrier start"); + std::shared_ptr revocable = AsyncDispatch(task); + if (revocable != nullptr) { + APP_LOGI("BaseTaskDispatcher::AsyncDispatchBarrier end"); + return ERR_OK; + } + APP_LOGE("BaseTaskDispatcher::AsyncDispatchBarrier revocable is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; +} + +std::shared_ptr BaseTaskDispatcher::CreateDispatchGroup() +{ + APP_LOGI("BaseTaskDispatcher::CreateDispatchGroup called."); + return std::make_shared(); +} + +std::shared_ptr BaseTaskDispatcher::AsyncGroupDispatch( + const std::shared_ptr &group, const std::shared_ptr &task) +{ + APP_LOGI("BaseTaskDispatcher::AsyncGroupDispatch called."); + return AsyncDispatch(task); +} + +bool BaseTaskDispatcher::GroupDispatchWait(const std::shared_ptr &group, long timeout) +{ + APP_LOGI("BaseTaskDispatcher::GroupDispatchWait start"); + if (group == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchWait group is nullptr"); + return false; + } + std::shared_ptr groupImpl = CastToGroupImpl(group); + if (groupImpl == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchWait groupImpl is nullptr"); + return false; + } + bool result = groupImpl->AwaitAllTasks(timeout); + APP_LOGI("BaseTaskDispatcher::GroupDispatchWait start"); + return result; +} + +ErrCode BaseTaskDispatcher::GroupDispatchNotify( + const std::shared_ptr &group, const std::shared_ptr &task) +{ + APP_LOGI("BaseTaskDispatcher::GroupDispatchNotify start"); + if (group == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify group cannot be null."); + return ERR_APPEXECFWK_CHECK_FAILED; + } + if (task == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify task cannot be null"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + const std::function asyncDispatch = std::bind(&BaseTaskDispatcher::AsyncDispatch, this, task); + if (asyncDispatch == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify asyncDispatch is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + std::shared_ptr ptrCallback = std::make_shared(asyncDispatch); + if (ptrCallback == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify runnable is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + if (group == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify group is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + std::shared_ptr groupImpl = CastToGroupImpl(group); + if (groupImpl == nullptr) { + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify groupImpl is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + if (groupImpl->AddNotification(ptrCallback)) { + APP_LOGI("BaseTaskDispatcher::GroupDispatchNotify end"); + return ERR_OK; + }; + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify addNotification failed"); + return ERR_APPEXECFWK_CHECK_FAILED; +} + +ErrCode BaseTaskDispatcher::ApplyDispatch(const std::shared_ptr> &task, long iterations) +{ + APP_LOGI("BaseTaskDispatcher::ApplyDispatch start"); + if (task == nullptr) { + APP_LOGE("BaseTaskDispatcher::ApplyDispatch task object is not set"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + if (iterations <= 0) { + APP_LOGE("BaseTaskDispatcher::ApplyDispatch iterations must giant than 0"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + bool flag = true; + for (long i = 0L; i < iterations; ++i) { + std::shared_ptr ptrCallback = std::make_shared([task, i]() { (*task)(i); }); + if (ptrCallback == nullptr) { + APP_LOGE("BaseTaskDispatcher::ApplyDispatch runnable is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + std::shared_ptr revocable = AsyncDispatch(ptrCallback); + if (revocable == nullptr) { + APP_LOGE("BaseTaskDispatcher::ApplyDispatch revocable is nullptr, index:%{public}ld", i); + flag = false; + } + } + if (flag) { + APP_LOGI("BaseTaskDispatcher::ApplyDispatch end"); + return ERR_OK; + } + APP_LOGI("BaseTaskDispatcher::ApplyDispatch failed"); + return ERR_APPEXECFWK_CHECK_FAILED; +} + +ErrCode BaseTaskDispatcher::Check(const std::shared_ptr &task) const +{ + APP_LOGI("BaseTaskDispatcher::Check called"); + if (task == nullptr) { + APP_LOGE("dispatch task cannot be null."); + return ERR_APPEXECFWK_CHECK_FAILED; + } + return ERR_OK; +} + +std::shared_ptr BaseTaskDispatcher::CastToGroupImpl(const std::shared_ptr &group) +{ + APP_LOGI("BaseTaskDispatcher::CastToGroupImpl called"); + std::shared_ptr groupImpl_ptr = std::static_pointer_cast(group); + if (groupImpl_ptr != nullptr) { + return groupImpl_ptr; + } + APP_LOGE("group cannot instance of groupImpl "); + return nullptr; +} + +std::shared_ptr BaseTaskDispatcher::GetInterceptor() +{ + return nullptr; +} + +TaskPriority BaseTaskDispatcher::GetPriority() const +{ + return taskPriority_; +} + +void BaseTaskDispatcher::TracePointBeforePost( + std::shared_ptr &task, bool isAsyncTask, const std::string &dispatcherName) const +{ + APP_LOGI("BaseTaskDispatcher::TracePointBeforePost called"); + if (task == nullptr) { + APP_LOGE("BaseTaskDispatcher::TracePointBeforePost the task is nullptr"); + return; + } + std::string taskType = isAsyncTask ? "ASYNC_TASK_STRING" : "SYNC_TASK_STRING"; + long seq = task->GetSequence(); + APP_LOGI("BaseTaskDispatcher::TracePointBeforePost " + "log---TaskType:%{public}s,TaskSeq:%{public}ld,DispatcherName::%{public}s", + taskType.c_str(), + seq, + dispatcherName.c_str()); +} + +void BaseTaskDispatcher::TracePointAfterPost( + std::shared_ptr &task, bool isAsyncTask, const std::string &dispatcherName) const +{ + APP_LOGI("BaseTaskDispatcher::TracePointAfterPost called"); + if (task == nullptr) { + APP_LOGE("BaseTaskDispatcher::TracePointAfterPost the task is nullptr"); + return; + } + std::string taskType = isAsyncTask ? "ASYNC_TASK_STRING" : "SYNC_TASK_STRING"; + long seq = task->GetSequence(); + APP_LOGI("BaseTaskDispatcher::TracePointAfterPost " + "log---TaskType:%{public}s,TaskSeq:%{public}ld,DispatcherName::%{public}s", + taskType.c_str(), + seq, + dispatcherName.c_str()); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/dispatcher/global_task_dispatcher.cpp b/common/task_dispatcher/src/dispatcher/global_task_dispatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a794d8eafdd4a0d8756968d367bbe12b21daead --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/global_task_dispatcher.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "global_task_dispatcher.h" + +namespace OHOS { +namespace AppExecFwk { +std::string GlobalTaskDispatcher::DISPATCHER_NAME_ = "GlobalDispatcher"; + +GlobalTaskDispatcher::GlobalTaskDispatcher(TaskPriority priority, std::shared_ptr &executor) + : ParallelTaskDispatcherBase(priority, executor, DISPATCHER_NAME_) +{} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/dispatcher/group_impl.cpp b/common/task_dispatcher/src/dispatcher/group_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a07cffae5a35c164e20f366135bc7425eb80e152 --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/group_impl.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "group_impl.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +GroupImpl::GroupImpl() +{ + count_.store(0); +} + +/** + * Wait all tasks associated to this group to be done. + * + * @param timeout is the max waiting time for jobs in group execute, in ms. + * + * @return true if successfully wait. + */ +bool GroupImpl::AwaitAllTasks(long timeout) +{ + APP_LOGI("GroupImpl::AwaitAllTasks start"); + if (count_.load() == 0) { + APP_LOGI("GroupImpl::AwaitAllTasks number of count_ is zero"); + return true; + } + if (timeout <= 0L) { + APP_LOGW("GroupImpl::AwaitAllTasks timeout<=0"); + return false; + } + bool success = true; + std::unique_lock lock(dataMutex_); + while (count_.load() > 0) { + if (condition_.wait_for(lock, std::chrono::milliseconds(timeout)) == std::cv_status::timeout) { + success = false; + APP_LOGI("GroupImpl::awaitAllTasks timeout"); + break; + } + APP_LOGI("GroupImpl::awaitAllTasks success"); + } + APP_LOGI("GroupImpl::AwaitAllTasks end"); + return success; +} + +/** + * @brief Associates a task to this group. + * + */ +void GroupImpl::Associate() +{ + APP_LOGI("GroupImpl::Associate called add a task"); + count_.fetch_add(1); +} +/** + * @brief Notify group that a task is done or canceled. + * + */ +void GroupImpl::NotifyTaskDone() +{ + APP_LOGI("GroupImpl::NotifyTaskDone start. Called notify a task to complete"); + count_.fetch_sub(1); + int newValue = count_.load(); + if (newValue > 0) { + return; + } + std::unique_lock lock(dataMutex_); + condition_.notify_all(); + DrainNotifications(); + + APP_LOGI("GroupImpl::NotifyTaskDone end"); +} +/** + * @brief Adds the |notification| to notification list. + * If all tasks are already done, |notification| will immediately be called on current thread. + * Attention: If tasks are added just this time, it may not be considered. + * + * @param notification Called when all tasks done. + * + */ +bool GroupImpl::AddNotification(const std::shared_ptr ¬ification) +{ + APP_LOGI("GroupImpl::AddNotification start"); + if (count_.load() != 0) { + std::unique_lock lock(dataMutex_); + if (notifications_.size() == MAX_TASK) { + APP_LOGW("GroupImpl::AddNotification called maximun number of tasks exceeded"); + return false; + } + if (count_.load() != 0) { + APP_LOGI("GroupImpl::AddNotification called add task"); + notifications_.push_back(notification); + return true; + } + } + if (notification) { + APP_LOGI("GroupImpl::AddNotification notification execute"); + (*notification)(); + } + APP_LOGI("GroupImpl::AddNotification end"); + return true; +} +/** + * @brief Notify all tasks and remove from queue. + * Attention: Notifications added after all tasks done is not guaranteed. + */ +void GroupImpl::DrainNotifications() +{ + APP_LOGI("GroupImpl::DrainNotifications start"); + while (notifications_.size() > 0) { + std::shared_ptr notification = notifications_.front(); + notifications_.pop_front(); + APP_LOGI("GroupImpl::DrainNotifications execute notification"); + (*notification)(); + } + APP_LOGI("GroupImpl::DrainNotifications end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp b/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46a0d3765e12e8f0d11d2eb483a4ec920c70f069 --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "parallel_task_dispatcher.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string ParallelTaskDispatcher::DISPATCHER_TAG = "ParallelTaskDispatcher"; +const std::string ParallelTaskDispatcher::ASYNC_DISPATCHER_BARRIER_TAG = DISPATCHER_TAG + "::asyncDispatchBarrier"; +const std::string ParallelTaskDispatcher::SYNC_DISPATCHER_BARRIER_TAG = DISPATCHER_TAG + "::syncDispatchBarrier"; +ParallelTaskDispatcher::ParallelTaskDispatcher( + const std::string &name, TaskPriority priority, std::shared_ptr &executor) + : ParallelTaskDispatcherBase(priority, executor, name) +{ + barrierHandler_ = std::make_shared(executor); +} + +std::shared_ptr ParallelTaskDispatcher::GetInterceptor() +{ + return barrierHandler_; +} + +ErrCode ParallelTaskDispatcher::SyncDispatchBarrier(const std::shared_ptr &runnable) +{ + APP_LOGI("ParallelTaskDispatcher::SyncDispatchBarrier start"); + if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcher::SyncDispatchBarrier Check failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + std::shared_ptr innerSyncTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerSyncTask == nullptr) { + APP_LOGE("ParallelTaskDispatcher::SyncDispatchBarrier innerSyncTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + std::shared_ptr innerTask = std::static_pointer_cast(innerSyncTask); + if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcher::SyncDispatchBarrier innerTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + APP_LOGD("ParallelTaskDispatcher::SyncDispatchBarrier into new sync task"); + if (barrierHandler_ == nullptr) { + APP_LOGE("ParallelTaskDispatcher::SyncDispatchBarrier barrierHandler_ is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + barrierHandler_->AddBarrier(innerTask); + innerSyncTask->WaitTask(); + APP_LOGD("ParallelTaskDispatcher::SyncDispatchBarrier end"); + return ERR_OK; +} + +ErrCode ParallelTaskDispatcher::AsyncDispatchBarrier(const std::shared_ptr &runnable) +{ + APP_LOGI("ParallelTaskDispatcher::AsyncDispatchBarrier start"); + if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcher::AsyncDispatchBarrier check failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + if (barrierHandler_ == nullptr) { + APP_LOGE("ParallelTaskDispatcher::AsyncDispatchBarrier barrierHandler_ is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + APP_LOGI("ParallelTaskDispatcher::AsyncDispatchBarrier into new async task"); + if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcher::AsyncDispatchBarrier innerTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + barrierHandler_->AddBarrier(innerTask); + APP_LOGI("ParallelTaskDispatcher::AsyncDispatchBarrier end"); + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp b/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f651672d5215c80c2060539bfdab991f7cb591b --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "parallel_task_dispatcher_base.h" + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" + +namespace OHOS { +namespace AppExecFwk { +std::string ParallelTaskDispatcherBase::DISPATCHER_TAG = "ParallelTaskDispatcherBase"; +std::string ParallelTaskDispatcherBase::ASYNC_DISPATCHER_TAG = DISPATCHER_TAG + "::asyncDispatch"; +std::string ParallelTaskDispatcherBase::SYNC_DISPATCHER_TAG = DISPATCHER_TAG + "::syncDispatch"; +std::string ParallelTaskDispatcherBase::DELAY_DISPATCHER_TAG = DISPATCHER_TAG + "::delayDispatch"; +std::string ParallelTaskDispatcherBase::ASYNC_GROUP_DISPATCHER_TAG = DISPATCHER_TAG + "::asyncGroupDispatch"; +ParallelTaskDispatcherBase::ParallelTaskDispatcherBase( + TaskPriority taskPriority, std::shared_ptr &executor, const std::string &dispatcherName) + : BaseTaskDispatcher(dispatcherName, taskPriority) +{ + executor_ = executor; +} +ErrCode ParallelTaskDispatcherBase::InterceptedExecute(std::shared_ptr &task) +{ + APP_LOGI("ParallelTaskDispatcherBase::InterceptedExecute start"); + if (executor_ == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::InterceptedExecute executor_ is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + if ((GetInterceptor() != nullptr) && + GetInterceptor()->Intercept(task) == ERR_APPEXECFWK_INTERCEPT_TASK_EXECUTE_SUCCESS) { + APP_LOGE("ParallelTaskDispatcherBase::InterceptedExecute intercept task execute success"); + return ERR_APPEXECFWK_INTERCEPT_TASK_EXECUTE_SUCCESS; + } + + executor_->Execute(task); + APP_LOGI("ParallelTaskDispatcherBase::InterceptedExecute end"); + return ERR_OK; +} + +ErrCode ParallelTaskDispatcherBase::SyncDispatch(const std::shared_ptr &runnable) +{ + APP_LOGI("ParallelTaskDispatcherBase::SyncDispatch start"); + if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::SyncDispatch check failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + std::shared_ptr innerSyncTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerSyncTask == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::SyncDispatch innerSyncTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + std::shared_ptr innerTask = std::static_pointer_cast(innerSyncTask); + if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::SyncDispatch innerTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + APP_LOGI("ParallelTaskDispatcherBase::SyncDispatch into new sync task"); + ErrCode execute = InterceptedExecute(innerTask); + if (execute != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::SyncDispatch execute failed"); + return execute; + } + innerSyncTask->WaitTask(); + APP_LOGI("ParallelTaskDispatcherBase::SyncDispatch end"); + return ERR_OK; +} + +std::shared_ptr ParallelTaskDispatcherBase::AsyncDispatch(const std::shared_ptr &runnable) +{ + APP_LOGI("ParallelTaskDispatcherBase::AsyncDispatch start"); + if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncDispatch check failed."); + return nullptr; + } + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncDispatch innerTask is nullptr."); + return nullptr; + } + TracePointBeforePost(innerTask, true, ASYNC_DISPATCHER_TAG); + APP_LOGI("ParallelTaskDispatcherBase::AsyncDispatch into new async task"); + ErrCode execute = InterceptedExecute(innerTask); + if (execute != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncDispatch execute failed"); + return nullptr; + } + APP_LOGI("ParallelTaskDispatcherBase::AsyncDispatch end"); + return innerTask; +} + +std::shared_ptr ParallelTaskDispatcherBase::DelayDispatch( + const std::shared_ptr &runnable, long delayMs) +{ + APP_LOGI("ParallelTaskDispatcherBase::DelayDispatch start"); + if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch Check failed"); + return nullptr; + } + + if (executor_ == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch executor_ is nullptr"); + return nullptr; + } + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch innerTask is nullptr"); + return nullptr; + } + TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); + std::function callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), + innerTask); + bool executeFlag = executor_->DelayExecute(callback, delayMs); + if (!executeFlag) { + APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch execute failed"); + return nullptr; + } + APP_LOGI("ParallelTaskDispatcherBase::DelayDispatch end"); + return innerTask; +} + +std::shared_ptr ParallelTaskDispatcherBase::AsyncGroupDispatch( + const std::shared_ptr &group, const std::shared_ptr &runnable) +{ + APP_LOGI("ParallelTaskDispatcherBase::AsyncGroupDispatch start"); + if (group == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch group is nullptr"); + return nullptr; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch Check failed"); + return nullptr; + } + + std::shared_ptr groupImpl = CastToGroupImpl(group); + if (groupImpl == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch groupImpl is nullptr"); + return nullptr; + } + groupImpl->Associate(); + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch innerTask is nullptr"); + return nullptr; + } + TracePointBeforePost(innerTask, true, ASYNC_GROUP_DISPATCHER_TAG); + std::shared_ptr ptrlistener = std::make_shared(); + if (ptrlistener == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch ptrlistener is nullptr"); + return nullptr; + } + const std::function onTaskDone = std::bind(&GroupImpl::NotifyTaskDone, groupImpl); + ptrlistener->Callback(onTaskDone); + innerTask->AddTaskListener(ptrlistener); + ErrCode execute = InterceptedExecute(innerTask); + if (execute != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch execute failed"); + return nullptr; + } + APP_LOGI("ParallelTaskDispatcherBase::AsyncGroupDispatch end"); + return innerTask; +} + +std::shared_ptr ParallelTaskDispatcherBase::GetInterceptor() +{ + return nullptr; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp b/common/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfd27ceb9f798ee18f69d2fea0514b862a1d635f --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "serial_task_dispatcher.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +namespace OHOS { +namespace AppExecFwk { +std::string SerialTaskDispatcher::DISPATCHER_TAG = "SerialTaskDispatcher"; +std::string SerialTaskDispatcher::ASYNC_DISPATCHER_TAG = DISPATCHER_TAG + "::asyncDispatch"; +std::string SerialTaskDispatcher::SYNC_DISPATCHER_TAG = DISPATCHER_TAG + "::syncDispatch"; +std::string SerialTaskDispatcher::DELAY_DISPATCHER_TAG = DISPATCHER_TAG + "::delayDispatch"; + +SerialTaskDispatcher::SerialTaskDispatcher( + const std::string &dispatcherName, const TaskPriority priority, const std::shared_ptr &executor) + : BaseTaskDispatcher(dispatcherName, priority) +{ + running_ = false; + executor_ = executor; +} + +int SerialTaskDispatcher::GetWorkingTasksSize() +{ + return workingTasks_.Size(); +} + +std::string SerialTaskDispatcher::GetDispatcherName() +{ + return dispatcherName_; +} + +ErrCode SerialTaskDispatcher::SyncDispatch(const std::shared_ptr &runnable) +{ + APP_LOGI("SerialTaskDispatcher::SyncDispatch start"); + if (Check(runnable) != ERR_OK) { + APP_LOGE("SerialTaskDispatcher::SyncDispatch check failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + std::shared_ptr innerSyncTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerSyncTask == nullptr) { + APP_LOGE("SerialTaskDispatcher::SyncDispatch innerSyncTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + std::shared_ptr innerTask = std::static_pointer_cast(innerSyncTask); + if (innerTask == nullptr) { + APP_LOGE("SerialTaskDispatcher::SyncDispatch innerTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + TracePointBeforePost(innerTask, false, SYNC_DISPATCHER_TAG); + OnNewTaskIn(innerTask); + innerSyncTask->WaitTask(); + TracePointAfterPost(innerTask, false, DISPATCHER_TAG); + + APP_LOGI("SerialTaskDispatcher::SyncDispatch end"); + return ERR_OK; +} + +std::shared_ptr SerialTaskDispatcher::AsyncDispatch(const std::shared_ptr &runnable) +{ + APP_LOGI("SerialTaskDispatcher::AsyncDispatch start"); + if (Check(runnable) != ERR_OK) { + APP_LOGE("SerialTaskDispatcher::AsyncDispatch Check failed"); + return nullptr; + } + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("SerialTaskDispatcher::AsyncDispatch innerTask is nullptr"); + return nullptr; + } + TracePointBeforePost(innerTask, true, ASYNC_DISPATCHER_TAG); + APP_LOGI("SerialTaskDispatcher::AsyncDispatch into new async task"); + OnNewTaskIn(innerTask); + APP_LOGI("SerialTaskDispatcher::AsyncDispatch end"); + return innerTask; +} + +std::shared_ptr SerialTaskDispatcher::DelayDispatch(const std::shared_ptr &runnable, long delayMs) +{ + APP_LOGI("SerialTaskDispatcher::DelayDispatch start"); + if (executor_ == nullptr) { + APP_LOGE("SerialTaskDispatcher::DelayDispatch executor_ is nullptr"); + return nullptr; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("SerialTaskDispatcher::DelayDispatch Check failed"); + return nullptr; + } + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("SerialTaskDispatcher::DelayDispatch innerTask is nullptr"); + return nullptr; + } + TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); + // bind parameter to avoid deconstruct. + std::function callback = std::bind(&SerialTaskDispatcher::OnNewTaskIn, this, innerTask); + bool executeFlag = executor_->DelayExecute(callback, delayMs); + if (!executeFlag) { + APP_LOGE("SerialTaskDispatcher::DelayDispatch execute failed"); + return nullptr; + } + APP_LOGI("SerialTaskDispatcher::DelayDispatch end"); + return innerTask; +} + +ErrCode SerialTaskDispatcher::OnNewTaskIn(std::shared_ptr &task) +{ + APP_LOGI("SerialTaskDispatcher::OnNewTaskIn start"); + ErrCode code = Prepare(task); + if (code != ERR_OK) { + APP_LOGE("SerialTaskDispatcher::OnNewTaskIn Prepare failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + { + std::unique_lock lock(mutex_); + if (workingTasks_.Offer(task) == false) { + APP_LOGW("SerialTaskDispatcher.onNewTaskIn exceed the maximum capacity of Queue"); + } + } + + Schedule(); + APP_LOGI("SerialTaskDispatcher::OnNewTaskIn end"); + return ERR_OK; +} + +ErrCode SerialTaskDispatcher::Prepare(std::shared_ptr &task) +{ + APP_LOGI("SerialTaskDispatcher::Prepare start"); + if (task == nullptr) { + APP_LOGE("SerialTaskDispatcher::Prepare task is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + // inline class + class MyTaskListener : public TaskListener { + private: + std::function callback_; + + public: + void OnChanged(const TaskStage &stage) + { + if (stage.IsDone()) { + callback_(); + } + } + // set callback function + void Callback(const std::function &callbackFunction) + { + callback_ = std::move(callbackFunction); + } + }; + + // set inline listener + std::shared_ptr ptrlistener = std::make_shared(); + if (ptrlistener == nullptr) { + APP_LOGE("SerialTaskDispatcher::Prepare MyTaskListener is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + const std::function onTaskDone = [&]() { OnTaskDone(); }; + ptrlistener->Callback(onTaskDone); + task->AddTaskListener(ptrlistener); + APP_LOGI("SerialTaskDispatcher::Prepare end"); + return ERR_OK; +} + +void SerialTaskDispatcher::OnTaskDone() +{ + APP_LOGI("SerialTaskDispatcher::OnTaskDone start"); + bool isExhausted = workingTasks_.Empty(); + DoNext(isExhausted); + APP_LOGI("SerialTaskDispatcher::OnTaskDone end"); +} + +bool SerialTaskDispatcher::Schedule() +{ + bool init = false; + if (!running_.compare_exchange_strong(init, true)) { + APP_LOGW("SerialTaskDispatcher::schedule already running"); + return false; + } + APP_LOGI("SerialTaskDispatcher::Schedule do next"); + return DoNext(false); +} + +bool SerialTaskDispatcher::DoNext(bool isExhausted) +{ + APP_LOGI("SerialTaskDispatcher::DoNext start"); + std::shared_ptr nextptr = nullptr; + { + std::unique_lock lock(mutex_); + nextptr = workingTasks_.Poll(); + if (nextptr == nullptr) { + running_.store(false); + APP_LOGW("SerialTaskDispatcher::DoNext no more task"); + return false; + } + } + + DoWork(nextptr); + APP_LOGI("SerialTaskDispatcher::DoNext end"); + return true; +} + +void SerialTaskDispatcher::DoWork(std::shared_ptr &task) +{ + APP_LOGI("SerialTaskDispatcher::DoWork called."); + // |task| mustn't be null + executor_->Execute(task); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp b/common/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6e176164b19d04fbb185d7e894f764ac19ce3b4 --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "spec_task_dispatcher.h" +#include "task_handler_libevent_adapter.h" + +namespace OHOS { +namespace AppExecFwk { +std::string SpecTaskDispatcher::DISPATCHER_TAG = "SpecTaskDispatcher"; +std::string SpecTaskDispatcher::ASYNC_DISPATCHER_TAG = DISPATCHER_TAG + "::asyncDispatch"; +std::string SpecTaskDispatcher::SYNC_DISPATCHER_TAG = DISPATCHER_TAG + "::syncDispatch"; +std::string SpecTaskDispatcher::DELAY_DISPATCHER_TAG = DISPATCHER_TAG + "::delayDispatch"; +SpecTaskDispatcher::SpecTaskDispatcher( + std::shared_ptr config, std::shared_ptr runner) + : BaseTaskDispatcher(config->GetName(), config->GetPriority()) +{ + handler_ = std::make_shared(runner); +} + +ErrCode SpecTaskDispatcher::SyncDispatch(const std::shared_ptr &runnable) +{ + APP_LOGI("SpecTaskDispatcher::SyncDispatch start"); + if (handler_ == nullptr) { + APP_LOGE("SpecTaskDispatcher::SyncDispatch handler is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("SpecTaskDispatcher::SyncDispatch check failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("SpecTaskDispatcher::SyncDispatch innerTask is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + TracePointBeforePost(innerTask, false, SYNC_DISPATCHER_TAG); + APP_LOGI("SpecTaskDispatcher::SyncDispatch into new sync task"); + handler_->DispatchSync(runnable); + TracePointAfterPost(innerTask, false, DISPATCHER_TAG); + + APP_LOGI("SpecTaskDispatcher::SyncDispatch end"); + return ERR_OK; +} + +std::shared_ptr SpecTaskDispatcher::AsyncDispatch(const std::shared_ptr &runnable) +{ + APP_LOGI("SpecTaskDispatcher::AsyncDispatch start"); + if (handler_ == nullptr) { + APP_LOGE("SpecTaskDispatcher::AsyncDispatch handler is nullptr"); + return nullptr; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("SpecTaskDispatcher::AsyncDispatch check failed"); + return nullptr; + } + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("SpecTaskDispatcher::AsyncDispatch innerTask is nullptr"); + return nullptr; + } + TracePointBeforePost(innerTask, true, ASYNC_DISPATCHER_TAG); + APP_LOGI("SpecTaskDispatcher::AsyncDispatch into new async task"); + handler_->Dispatch(runnable); + APP_LOGI("SpecTaskDispatcher::AsyncDispatch end"); + return innerTask; +} + +std::shared_ptr SpecTaskDispatcher::DelayDispatch(const std::shared_ptr &runnable, long delayMs) +{ + APP_LOGI("SpecTaskDispatcher::DelayDispatch start"); + if (handler_ == nullptr) { + APP_LOGE("SpecTaskDispatcher::DelayDispatch handler is nullptr"); + return nullptr; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("SpecTaskDispatcher::DelayDispatch check failed"); + return nullptr; + } + + std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); + if (innerTask == nullptr) { + APP_LOGE("SpecTaskDispatcher::DelayDispatch innerTask is nullptr"); + return nullptr; + } + TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); + handler_->Dispatch(runnable, delayMs); + APP_LOGI("SpecTaskDispatcher::DelayDispatch end"); + return innerTask; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp b/common/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b72fe3bd27a949f6b99af5e9220040a2951d3241 --- /dev/null +++ b/common/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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_dispatcher_context.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +TaskDispatcherContext::TaskDispatcherContext() +{ + globalDispatchers_.resize(PRIORITY_COUNT); + config_ = std::make_shared(); + if (config_ == nullptr) { + APP_LOGE("TaskDispatcherContext::TaskDispatcherContext config is nullptr"); + executor_ = nullptr; + } else { + executor_ = std::make_shared(config_); + if (executor_ != nullptr) { + executor_->CreateGuardThread(); + } + } +} +TaskDispatcherContext::TaskDispatcherContext(const std::shared_ptr &executor) +{ + globalDispatchers_.resize(PRIORITY_COUNT); + config_ = std::make_shared(); + executor_ = executor; +} + +TaskDispatcherContext::~TaskDispatcherContext() +{ + if (executor_) { + APP_LOGI("TaskDispatcherContext::~TaskDispatcherContext() terminate"); + executor_->Terminate(false); + } + APP_LOGI("TaskDispatcherContext::~TaskDispatcherContext end"); +} + +std::shared_ptr TaskDispatcherContext::GetWorkerPoolConfig() const +{ + return config_; +} + +std::map TaskDispatcherContext::GetWorkerThreadsInfo() const +{ + APP_LOGI("TaskDispatcherContext::GetWorkerThreadsInfo called"); + if (executor_ != nullptr) { + return executor_->GetWorkerThreadsInfo(); + } + std::map map; + APP_LOGE("TaskDispatcherContext::GetWorkerThreadsInfo executor is nullptr"); + return map; +} + +std::map, std::string> TaskDispatcherContext::GetSerialDispatchers() const +{ + APP_LOGI("TaskDispatcherContext::GetSerialDispatchers called"); + return serialDispatchers_; +} + +int TaskDispatcherContext::GetWaitingTasksCount() const +{ + APP_LOGI("TaskDispatcherContext::GetWaitingTasksCount called"); + if (executor_ != nullptr) { + return executor_->GetPendingTasksSize(); + } + APP_LOGE("TaskDispatcherContext::GetWaitingTasksCount executor is nullptr"); + return 0; +} + +long TaskDispatcherContext::GetTaskCounter() const +{ + APP_LOGI("TaskDispatcherContext::GetTaskCounter called"); + if (executor_ != nullptr) { + return executor_->GetTaskCounter(); + } + APP_LOGE("TaskDispatcherContext::GetTaskCounter executor is nullptr"); + return 0; +} + +std::shared_ptr TaskDispatcherContext::CreateSerialDispatcher( + const std::string &name, TaskPriority priority) +{ + APP_LOGI("TaskDispatcherContext::CreateSerialDispatcher start"); + if (executor_ == nullptr) { + APP_LOGE("TaskDispatcherContext::CreateSerialDispatcher executor is nullptr"); + return nullptr; + } + std::shared_ptr serialDispatcher = + std::make_shared(name, priority, executor_); + serialDispatchers_.insert(std::pair, std::string>(serialDispatcher, name)); + APP_LOGI("TaskDispatcherContext::CreateSerialDispatcher end"); + return serialDispatcher; +} + +std::shared_ptr TaskDispatcherContext::CreateParallelDispatcher( + const std::string &name, TaskPriority priority) +{ + APP_LOGI("TaskDispatcherContext::CreateParallelDispatcher start"); + if (executor_ == nullptr) { + APP_LOGE("TaskDispatcherContext::CreateParallelDispatcher executor is nullptr"); + return nullptr; + } + std::shared_ptr parallelTaskDispatcher = + std::make_shared(name, priority, executor_); + APP_LOGI("TaskDispatcherContext::CreateParallelDispatcher end"); + return parallelTaskDispatcher; +} + +int TaskDispatcherContext::MapPriorityIndex(TaskPriority priority) const +{ + switch (priority) { + case TaskPriority::HIGH: + return HIGH_PRIORITY_INDEX; + case TaskPriority::DEFAULT: + return DEFAULT_PRIORITY_INDEX; + case TaskPriority::LOW: + return LOW_PRIORITY_INDEX; + default: + return DEFAULT_PRIORITY_INDEX; + } + APP_LOGE("TaskDispatcherContext.mapPriorityIndex unhandled priority=%{public}d", priority); + + return DEFAULT_PRIORITY_INDEX; +} + +std::shared_ptr TaskDispatcherContext::GetGlobalTaskDispatcher(TaskPriority priority) +{ + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher start"); + std::unique_lock lock(mtx_); + int index = MapPriorityIndex(priority); + std::shared_ptr dispatcher = globalDispatchers_[index]; + if (dispatcher == nullptr) { + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher dispatcher is nullptr "); + if (executor_ == nullptr) { + APP_LOGE("TaskDispatcherContext::GetGlobalTaskDispatcher executor_ is nullptr "); + return nullptr; + } + dispatcher = std::make_shared(priority, executor_); + if (globalDispatchers_[index] == nullptr) { + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher dispatcher compareAndSet "); + globalDispatchers_.insert((globalDispatchers_.begin() + index), dispatcher); + } + } + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher end"); + return dispatcher; +} + +ErrCode TaskDispatcherContext::Shutdown(bool force) +{ + APP_LOGI("TaskDispatcherContext::Shutdown start"); + if (executor_ == nullptr) { + APP_LOGE("TaskDispatcherContext::Shutdown executor_ is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + executor_->Terminate(force); + APP_LOGI("TaskDispatcherContext::Shutdown end"); + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/task/barrier_handler.cpp b/common/task_dispatcher/src/task/barrier_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c773dafadf6491c23cd0ae868f40600d1ad00dc --- /dev/null +++ b/common/task_dispatcher/src/task/barrier_handler.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "barrier_handler.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +BarrierHandler::BarrierHandler(const std::shared_ptr &executor) +{ + executor_ = executor; +}; + +ErrCode BarrierHandler::AddBarrier(std::shared_ptr &barrierTask) +{ + APP_LOGI("BarrierHandler::AddBarrier start"); + if (ListenToTask(barrierTask) != ERR_OK) { + APP_LOGE("BarrierHandler::AddBarrier listenToTask failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + }; + + bool execNow = false; + { + std::unique_lock lock(barrierLock_); + std::shared_ptr pair = barrierQueue_.size() == 0 ? nullptr : barrierQueue_.back(); + if ((pair == nullptr) || ((!HasTask(pair->tasks_)) && (pair->barrier_ == nullptr))) { + execNow = true; + APP_LOGI("BarrierHandler::AddBarrier need execute now"); + } + if ((pair == nullptr) || (pair->barrier_ != nullptr)) { + std::set> tmp; + std::shared_ptr barrierPair = std::make_shared(tmp, barrierTask); + if (barrierPair == nullptr) { + APP_LOGE("BarrierHandler::AddBarrier barrierPair is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + barrierQueue_.push_back(barrierPair); + APP_LOGI("BarrierHandler::AddBarrier barrierQueue push barrierPair"); + } else { + pair->barrier_ = barrierTask; + } + } + + if (execNow) { + APP_LOGI("BarrierHandler::AddBarrier execute task"); + executor_->Execute(barrierTask); + } + APP_LOGI("BarrierHandler::AddBarrier end"); + return ERR_OK; +} + +ErrCode BarrierHandler::Intercept(std::shared_ptr &task) +{ + APP_LOGI("BarrierHandler::Intercept start"); + if (ListenToTask(task) != ERR_OK) { + APP_LOGE("BarrierHandler::Intercept listenToTask failed"); + return ERR_APPEXECFWK_CHECK_FAILED; + }; + + // afterBarrier means is intercepted. + bool intercepted = AddTaskAfterBarrier(task); + if (intercepted) { + APP_LOGI("BarrierHandler::Intercept intercepted a task."); + } + ErrCode result = intercepted ? ERR_APPEXECFWK_INTERCEPT_TASK_EXECUTE_SUCCESS : ERR_APPEXECFWK_CHECK_FAILED; + APP_LOGI("BarrierHandler::Intercept end, result:%{public}d", result); + return result; +} + +ErrCode BarrierHandler::ListenToTask(std::shared_ptr &task) +{ + APP_LOGI("BarrierHandler::ListenToTask start"); + std::shared_ptr ptrlistener = std::make_shared(); + if (ptrlistener == nullptr) { + APP_LOGE("BarrierHandler::listenToTask make shared MyTaskListener is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + const std::function onTaskDone = std::bind(&BarrierHandler::OnTaskDone, this, task); + ptrlistener->Callback(onTaskDone); + task->AddTaskListener(ptrlistener); + APP_LOGI("BarrierHandler::ListenToTask end"); + return ERR_OK; +} + +void BarrierHandler::OnTaskDone(std::shared_ptr &task) +{ + APP_LOGI("BarrierHandler::OnTaskDone start"); + // remove from head of queue. + // Under the premise that task cannot be reused. + bool removed = false; + { + std::unique_lock lock(barrierLock_); + std::shared_ptr barrierPair = barrierQueue_.size() == 0 ? nullptr : barrierQueue_.front(); + if (barrierPair != nullptr) { + if (HasTask(barrierPair->tasks_)) { + removed = barrierPair->tasks_.erase(task) == 0 ? false : true; + if (barrierPair->tasks_.empty() && (barrierPair->barrier_ != nullptr)) { + APP_LOGI("Barrier.onTaskDone execute barrier task after task done."); + executor_->Execute(barrierPair->barrier_); + } + } else if (task == (barrierPair->barrier_)) { + APP_LOGI("Barrier.onTaskDone remove a barrier."); + barrierPair->barrier_ = nullptr; + removed = true; + // Driven to next barrier. + // In one case (barrierQueue.size() == 1): call barrier, and no more task incoming. + if (barrierQueue_.size() > 1) { + barrierQueue_.pop_front(); + std::shared_ptr nextPair = barrierQueue_.front(); + if (HasTask(nextPair->tasks_)) { + for (std::set>::iterator it = nextPair->tasks_.begin(); + it != nextPair->tasks_.end(); + it++) { + executor_->Execute(*it); + } + } else if (nextPair->barrier_ != nullptr) { + APP_LOGI("Barrier.onTaskDone execute barrier task after barrier done."); + executor_->Execute(nextPair->barrier_); + } else { + APP_LOGW("Barrier.onTaskDone: Detected an empty node."); + } + } + } + } + } + + if (!removed) { + APP_LOGI("Barrier.onTaskDone: Task remove failed."); + } + APP_LOGI("BarrierHandler::OnTaskDone end"); +} + +bool BarrierHandler::AddTaskAfterBarrier(std::shared_ptr &task) +{ + APP_LOGI("BarrierHandler::AddTaskAfterBarrier start"); + std::unique_lock lock(barrierLock_); + std::shared_ptr pair = barrierQueue_.size() == 0 ? nullptr : barrierQueue_.back(); + if ((pair == nullptr) || (pair->barrier_ != nullptr)) { + std::shared_ptr tmp = std::make_shared(CreateTaskSet(task), nullptr); + if (tmp == nullptr) { + APP_LOGE("BarrierHandler::addTaskAfterBarrier make shared BarrierPair is nullptr"); + return false; + } + + barrierQueue_.push_back(tmp); + } else if (pair->tasks_.empty()) { + pair->tasks_ = CreateTaskSet(task); + } else { + pair->tasks_.insert(task); + } + APP_LOGI("BarrierHandler::AddTaskAfterBarrier end"); + return (barrierQueue_.size() > 1); +} + +bool BarrierHandler::HasTask(const std::set> &tasks) +{ + return ((tasks.size() != 0) && !tasks.empty()); +} + +std::set> BarrierHandler::CreateTaskSet(std::shared_ptr &firstTask) +{ + std::set> taskSet; + taskSet.insert(firstTask); + return taskSet; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/src/task/sync_task.cpp b/common/task_dispatcher/src/task/sync_task.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a551df0e437bdff4a158d18f0d049b6a8296b461 --- /dev/null +++ b/common/task_dispatcher/src/task/sync_task.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "sync_task.h" +#include + +namespace OHOS { +namespace AppExecFwk { +// Help to calculate hash code of object. +template +inline size_t CalculateHashCode(const T &obj) +{ + std::hash calculateHashCode; + return calculateHashCode(obj); +} + +SyncTask::SyncTask(const std::shared_ptr &runnable, TaskPriority priority, + const std::shared_ptr &baseTaskDispatcher) + : Task(runnable, priority, baseTaskDispatcher) +{ + executed_.store(false); +} + +void SyncTask::Run() +{ + std::unique_lock lock(mutex_); + auto threadId = std::this_thread::get_id(); + APP_LOGI("SyncTask::Run begin thread=%{public}zu", CalculateHashCode(threadId)); + Task::Run(); + executed_.store(true); + + // |waitTask| may have been multi invoked. + condition_variable_.notify_all(); + APP_LOGI("SyncTask::Run end thread=%{public}zu", CalculateHashCode(threadId)); +} + +void SyncTask::WaitTask() +{ + auto threadId = std::this_thread::get_id(); + APP_LOGI("SyncTask::WaitTask begin thread=%{public}zu", CalculateHashCode(threadId)); + + std::unique_lock lock(mutex_); + while (executed_ == false) { + condition_variable_.wait(lock); + } + + APP_LOGI("SyncTask::WaitTask end thread=%{public}zu", CalculateHashCode(threadId)); +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/task/task.cpp b/common/task_dispatcher/src/task/task.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e283f535a83c59b3ab0bab8095adb058b3bdac7d --- /dev/null +++ b/common/task_dispatcher/src/task/task.cpp @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Constructs the object. + * @param runnable The user task wrapped in. + * @param priority The priority + * @return None + */ +Task::Task(const std::shared_ptr &runnable, const TaskPriority priority, + const std::shared_ptr &baseTaskDispatcher) + : taskListeners_() +{ + runnable_ = runnable; + priority_ = priority; + baseTaskDispatcher_ = baseTaskDispatcher; + std::atomic_init(&state_, 0U); + APP_LOGI("Task::Task init listener count=%{public}zu", taskListeners_.Size()); +} +Task::~Task() +{} + +/** + * @brief invoke the function to execute the task + * @param None + * @return None + */ +void Task::Run() +{ + APP_LOGI("Task::Run task run called start"); + if (runnable_ == nullptr) { + APP_LOGI("Task::Run called runnable_ is null"); + return; + } + // Task cannot be reused. + if (EnterExecute()) { + APP_LOGI("Task::Run runnable_ Run called start"); + (*runnable_.get())(); + } + APP_LOGI("Task::Run runnable_ Run called end"); +} + +/** + * @brief Gets the priority. + * @param None + * @return The priority. + */ +TaskPriority Task::GetPriority() const +{ + return priority_; +} + +/** + * @brief Sets the sequence. + * @param None + * @param sequence The sequence + * @return None + */ +void Task::SetSequence(long sequence) +{ + sequence_ = sequence; +} + +/** + * @brief Gets the sequence. + * @param None + * @return The sequence. + */ +long Task::GetSequence() const +{ + return sequence_; +} + +/** + * @brief Revoke this task if hasn't run. + * @param None + * @return true if set revoked or already revoked. False if the task has start executing. + */ +bool Task::Revoke() +{ + if (runnable_ == nullptr) { + APP_LOGE("Task.Revoke called runnable_ is null"); + return false; + } + RevokeResult result = SetRevoked(); + APP_LOGI("Task.Revoke result: %{public}u", result); + if (result == SUCCESS) { + OnTaskCanceled(); + } + return (result == SUCCESS) || (result == ALREADY_REVOKED); +} + +/** + * @brief Adds a task listener. + * @param listener The listener + * @return None + */ +void Task::AddTaskListener(const std::shared_ptr &listener) +{ + APP_LOGI("Task.AddTaskListener listener called start"); + taskListeners_.Offer(listener); +} + +/** + * @brief Called when task is about to run. + * @param None + * @return None + */ +void Task::BeforeTaskExecute() +{ + if ((state_ & REVOKED) != REVOKED) { + ConcurrentQueueStatusUpdate(TaskStage::BEFORE_EXECUTE); + } +} + +/** + * @brief Called when task is done. + * @param None + * @return None + */ +void Task::AfterTaskExecute() +{ + if ((state_ & EXECUTED) == EXECUTED) { + APP_LOGI("Task.AfterTaskExecute taskStage called AFTER_EXECUTE"); + ConcurrentQueueStatusUpdate(TaskStage::AFTER_EXECUTE); + } +} + +/** + * @brief Called when task is canceled. + * @param None + * @return None + */ +void Task::OnTaskCanceled() +{ + APP_LOGI("Task.OnTaskCanceled taskStage called REVOKED"); + ConcurrentQueueStatusUpdate(TaskStage::REVOKED); +} + +/** + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param None + * @return bool + */ +bool Task::EnterExecute() +{ + unsigned int stateNotIn = EXECUTED | REVOKED; + while (true) { + unsigned int value = state_.load(); + if ((state_ & stateNotIn) == 0) { + // Not executed or revoked + if (state_.compare_exchange_strong(value, EXECUTED)) { + APP_LOGI("Task.EnterExecute return success"); + return true; + } + } else { + APP_LOGE("Task.EnterExecute return fail, state=%{public}d, stateNotIn=%{public}d", value, stateNotIn); + return false; + } + } +} + +Task::RevokeResult Task::SetRevoked() +{ + while (true) { + unsigned int value = state_.load(); + if ((value & REVOKED) == REVOKED) { + APP_LOGW("Task.SetRevoked return ALREADY_REVOKED"); + return ALREADY_REVOKED; + } + if ((value & EXECUTED) == 0) { + if (state_.compare_exchange_strong(value, REVOKED)) { + APP_LOGI("Task.SetRevoked return SUCCESS"); + return SUCCESS; + } + } else { + APP_LOGE("Task.SetRevoked return FAIL"); + return FAIL; + } + } +} + +void Task::ConcurrentQueueStatusUpdate(const TaskStage::TASKSTAGE taskstage) +{ + APP_LOGI("Task.ConcurrentQueueStatusUpdate taskListeners_ called start"); + for (auto iter = taskListeners_.Begin(); iter != taskListeners_.End(); iter++) { + (*iter)->OnChanged(taskstage); + } + if (taskstage == TaskStage::TASKSTAGE::AFTER_EXECUTE) { + taskListeners_.clear(); + } +} + +bool Task::operator==(std::shared_ptr &rec) const +{ + return this->sequence_ == rec->sequence_ && this->state_ == rec->state_ && this->priority_ == rec->priority_ && + this->revocable_ == rec->revocable_ && this->runnable_ == rec->runnable_ && + this->baseTaskDispatcher_ == rec->baseTaskDispatcher_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/threading/default_thread_factory.cpp b/common/task_dispatcher/src/threading/default_thread_factory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aeee13514b9a3d9c643fd5a4fca874890ca5f767 --- /dev/null +++ b/common/task_dispatcher/src/threading/default_thread_factory.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "default_thread_factory.h" + +namespace OHOS { +namespace AppExecFwk { +DefaultThreadFactory::DefaultThreadFactory() : index_(1) +{} + +std::shared_ptr DefaultThreadFactory::Create() +{ + std::shared_ptr pThread = std::make_shared(); + if (pThread != nullptr) { + int value = std::atomic_fetch_add(&index_, 1); + std::string name = std::string("PoolThread-") + std::to_string(value); + pThread->thread_name_ = name; + APP_LOGI("DefaultThreadFactory::Create thread name is %{public}s", name.c_str()); + } else { + APP_LOGE("DefaultThreadFactory::Create error, thread is nullptr"); + } + + return pThread; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/threading/default_worker_pool_config.cpp b/common/task_dispatcher/src/threading/default_worker_pool_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a42d13a2d5bb558d17675343652aef58028d151c --- /dev/null +++ b/common/task_dispatcher/src/threading/default_worker_pool_config.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "default_worker_pool_config.h" + +namespace OHOS { +namespace AppExecFwk { +int DefaultWorkerPoolConfig::GetMaxThreadCount(void) const +{ + return DEFAULT_MAX_THREAD_COUNT; +} + +int DefaultWorkerPoolConfig::GetCoreThreadCount(void) const +{ + return DEFAULT_CORE_THREAD_COUNT; +} + +long DefaultWorkerPoolConfig::GetKeepAliveTime(void) const +{ + return DEFAULT_KEEP_ALIVE_TIME; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/threading/task_executor.cpp b/common/task_dispatcher/src/threading/task_executor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4a6b100a13da4342cbd68a90d666fded3eee881 --- /dev/null +++ b/common/task_dispatcher/src/threading/task_executor.cpp @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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_executor.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +std::atomic TaskExecutor::sequence(0); + +TaskExecutor::TaskExecutor(const std::shared_ptr &config) : WorkerPool(config) +{ + terminated_ = false; + taskCounter_ = 0; + delayTasks_ = std::make_shared(); + pendingTasks_ = std::make_shared(); +} +TaskExecutor::~TaskExecutor() +{ + if ((consumer_) && consumer_->joinable()) { + APP_LOGI("TaskExecutor::~TaskExecutor consumer is running"); + consumer_->join(); + } + APP_LOGI("TaskExecutor::~TaskExecutor"); +} + +void TaskExecutor::Execute(const std::shared_ptr &task) +{ + APP_LOGI("TaskExecutor::Execute begin"); + task->SetSequence(GetAndIncrement(sequence)); + + std::shared_ptr executor = shared_from_this(); + + if (AddWorker(executor, task) == false) { + std::shared_ptr priorityTaskWrapper = + std::make_shared(task->GetPriority(), task); + if (pendingTasks_->Offer(priorityTaskWrapper) == false) { + APP_LOGW("TaskExecutor::Execute rejected a task"); + } + } + APP_LOGI("TaskExecutor::Execute end"); +} + +ErrCode TaskExecutor::DoWorks(const std::shared_ptr &worker) +{ + APP_LOGI("TaskExecutor::DoWorks begin"); + if (worker == nullptr) { + APP_LOGE("TaskExecutor::DoWorks worker is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + if (worker->GetThread() == nullptr) { + APP_LOGE("TaskExecutor::DoWorks worker GetThread is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + + std::shared_ptr task = worker->PollFirstTask(); + + bool isInterrupted = false; + bool done = false; + while (((task != nullptr && done == false) || ((task = GetTask(worker)) != nullptr))) { + APP_LOGI("TaskExecutor::DoWorks loop tasks."); + + BeforeRun(task); + + task->Run(); + + AfterRun(task); + + worker->IncTaskCount(); + IncrementAndGet(taskCounter_); + + // loop condition + done = true; + } + OnWorkerExit(worker, isInterrupted); + APP_LOGI("TaskExecutor::DoWorks end"); + return ERR_OK; +} +std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr &workerThread) +{ + bool isTimeout = false; + std::shared_ptr nullRunnable = nullptr; + std::shared_ptr next = nullptr; + + for (;;) { + if (terminated_.load() && pendingTasks_->Empty()) { + APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is terminated", + workerThread->GetThreadName().c_str()); + DecrementThread(); + return nullRunnable; + } + + int workerCount = GetWorkCount(); + APP_LOGI("TaskExecutor::GetTask workerCount:%{public}d, GetCoreThreadCount: %{public}d", + workerCount, + GetCoreThreadCount()); + bool needCheckTimeout = (workerCount > GetCoreThreadCount()); + if (isTimeout && needCheckTimeout && pendingTasks_->Empty()) { + APP_LOGI("TaskExecutor::GetTask isTimeout is true"); + if (CompareAndDecNum(workerCount)) { + APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is timeout", + workerThread->GetThreadName().c_str()); + return nullRunnable; + } + continue; + } + + APP_LOGI("TaskExecutor::GetTask need timeout=%{public}d", needCheckTimeout); + std::shared_ptr next = + needCheckTimeout ? pendingTasks_->Poll(GetKeepAliveTime()) : pendingTasks_->Take(); + + if (next != nullptr && next->task_ != nullptr) { + APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s get next task", + workerThread->GetThreadName().c_str()); + return next->task_; + } + isTimeout = true; + } +} + +void TaskExecutor::Terminate(bool force) +{ + APP_LOGI("TaskExecutor::Terminate begin"); + TerminateConsumer(); + ClosePool(force); + APP_LOGI("TaskExecutor::Terminate end"); +} + +void TaskExecutor::AfterRun(const std::shared_ptr &task) +{ + task->AfterTaskExecute(); +} + +void TaskExecutor::BeforeRun(const std::shared_ptr &task) +{ + task->BeforeTaskExecute(); +} + +bool TaskExecutor::DelayExecute(const Runnable &task, long delayMs) +{ + if (delayMs <= 0) { + task(); + APP_LOGI("TaskExecutor::DelayExecute end and delayMs less than 0"); + return true; + } + if (terminated_.load()) { + APP_LOGI("TaskExecutor::DelayExecute end and terminate"); + return false; + } + std::shared_ptr delayTaskWrapper = std::make_shared(delayMs, task); + if (delayTaskWrapper == nullptr) { + APP_LOGI("TaskExecutor::DelayExecute end and delayTaskWrapper is nullptr"); + return false; + } + delayTasks_->Offer(delayTaskWrapper); + return EnsureConsumeStarted(); +} + +void TaskExecutor::TerminateConsumer() +{ + std::unique_lock lock(dataMutex_); + terminated_.store(true); + pendingTasks_->Stop(); + delayTasks_->Stop(); + + if (consumer_ != nullptr) { + if (consumer_->joinable()) { + consumer_->join(); + } + consumer_ = nullptr; + } +} + +bool TaskExecutor::EnsureConsumeStarted() +{ + if (consumer_ == nullptr) { + { + std::unique_lock lock(dataMutex_); + if (consumer_ == nullptr) { + consumer_ = std::make_shared(&TaskExecutor::Consume, this); + if (consumer_ == nullptr) { + APP_LOGE("TaskExecutor::EnsureConsumeStarted consumer_ is nullptr"); + return false; + } + APP_LOGI("TaskExecutor::EnsureConsumeStarted start a delay task consumer"); + } + } + } + return true; +} + +void TaskExecutor::Consume() +{ + for (;;) { + if (terminated_.load() && delayTasks_->Empty()) { + APP_LOGI("TaskExecutor::Consume delay task is empty"); + break; + } + std::shared_ptr delayTaskWrapper = delayTasks_->Take(); + if (delayTaskWrapper == nullptr || delayTaskWrapper->runnable_ == nullptr) { + APP_LOGE("TaskExecutor::Consume delayTaskWrapper is nullptr"); + return; + }; + (delayTaskWrapper->runnable_)(); + APP_LOGI("TaskExecutor::Consume after run"); + } +} + +int TaskExecutor::GetPendingTasksSize() +{ + return pendingTasks_->Size(); +} + +long TaskExecutor::GetTaskCounter() +{ + return taskCounter_.load(); +} + +long TaskExecutor::GetAndIncrement(std::atomic &atomiclong) +{ + long ret = atomiclong.load(); + atomiclong.fetch_add(1, std::memory_order_relaxed); + + return ret; +} + +long TaskExecutor::IncrementAndGet(std::atomic &atomiclong) +{ + atomiclong.fetch_add(1, std::memory_order_relaxed); + + return atomiclong; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/src/threading/work_thread.cpp b/common/task_dispatcher/src/threading/work_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8efbd1fa574fc5e7c310fd013f0991816dee531c --- /dev/null +++ b/common/task_dispatcher/src/threading/work_thread.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "work_thread.h" + +namespace OHOS { +namespace AppExecFwk { +WorkerThread::WorkerThread(const std::shared_ptr &delegate, const std::shared_ptr &firstTask, + const std::shared_ptr &factory) +{ + task_counter_.store(0); + + first_task_ = firstTask; + delegate_ = delegate; + factory_ = factory; +} + +void WorkerThread::Join() +{ + if ((thread_) && (thread_->thread_) && thread_->thread_->joinable()) { + APP_LOGI("WorkerThread::Join joinable thread"); + thread_->thread_->join(); + } + APP_LOGI("WorkerThread::Join end"); +} + +void WorkerThread::CreateThread() +{ + thread_ = factory_->Create(); + auto task = [&]() { + if (delegate_ != nullptr) { + auto ptr = shared_from_this(); + delegate_->DoWorks(ptr); + }; + }; + + // start a thread to run task function. + thread_->thread_ = std::make_shared(task); + APP_LOGI("WorkerThread::CreateThread start thread. "); +} + +void WorkerThread::IncTaskCount() +{ + task_counter_.fetch_add(1, std::memory_order_relaxed); +} + +std::string WorkerThread::GetThreadName() +{ + if (thread_ != nullptr) { + return thread_->thread_name_; + } else { + return std::string(""); + } +} + +std::shared_ptr WorkerThread::PollFirstTask(void) +{ + std::shared_ptr ret(nullptr); + if (first_task_ != nullptr) { + ret.swap(first_task_); + } + return ret; +} + +long WorkerThread::GetTaskCounter(void) +{ + long value = task_counter_; + return value; +} + +std::shared_ptr WorkerThread::GetThread(void) +{ + return thread_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/common/task_dispatcher/src/threading/worker_pool.cpp b/common/task_dispatcher/src/threading/worker_pool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1ae3c5a56866ea2ee22a443f3772e558faed36e --- /dev/null +++ b/common/task_dispatcher/src/threading/worker_pool.cpp @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "worker_pool.h" + +#include +#include "default_thread_factory.h" + +namespace OHOS { +namespace AppExecFwk { +const int WorkerPool::THREAD_UPPER_LIMIT = 256; +const int WorkerPool::MAX_THREAD_LOWER_LIMIT = 1; +const int WorkerPool::CORE_THREAD_LOWER_LIMIT = 0; +const int WorkerPool::COUNT_BITS = sizeof(int) * __CHAR_BIT__ - 3; +const unsigned int WorkerPool::CAPACITY = (1 << COUNT_BITS) - 1; +const int WorkerPool::RUNNING = (-(1 << COUNT_BITS)); +const int WorkerPool::CLOSING = (0 << COUNT_BITS); +const int WorkerPool::INTERRUPT = (1 << COUNT_BITS); +const int WorkerPool::CLEANED = (2 << COUNT_BITS); +const int WorkerPool::CLOSED = (3 << COUNT_BITS); + +WorkerPool::WorkerPool(const std::shared_ptr &config) +{ + control_ = CombineToControl(RUNNING, 0); + pool_.clear(); + exitPool_.clear(); + WorkerPool::factory_ = std::make_shared(); + initFlag_.store(Init(config)); + stop_.store(false); +} + +WorkerPool::~WorkerPool() +{ + control_ = 0; + + APP_LOGI("WorkerPool::~WorkerPool"); +} + +bool WorkerPool::Init(const std::shared_ptr &config) +{ + if (CheckConfigParams(config) == false) { + APP_LOGE("WorkerPool::checkConfigParams parameters are illegal"); + return false; + } + + thread_limit_ = config->GetMaxThreadCount(); + core_thread_limit_ = config->GetCoreThreadCount(); + long keepAliveTime = config->GetKeepAliveTime(); + alive_time_Limit_ = keepAliveTime > 0 ? keepAliveTime : 0; + + return true; +} + +bool WorkerPool::CheckConfigParams(const std::shared_ptr &config) +{ + if (config == nullptr) { + APP_LOGE("WorkerPool::CheckConfigParams config is nullptr"); + return false; + } + + int maxThreadCount = config->GetMaxThreadCount(); + int coreThreadCount = config->GetCoreThreadCount(); + + if (!CheckThreadCount(maxThreadCount, coreThreadCount)) { + APP_LOGE("WorkerPool::CheckConfigParams parameters are illegal, maxThreadCount %{public}d is less than " + "coreThreadCount %{public}d", + maxThreadCount, + coreThreadCount); + return false; + } + if (!CheckMaxThreadCount(maxThreadCount)) { + APP_LOGE("WorkerPool::CheckConfigParams maxThreadCount %{public}d is illegal", maxThreadCount); + return false; + } + if (!CheckCoreThreadCount(coreThreadCount)) { + APP_LOGE("WorkerPool::CheckConfigParams coreThreadCount %{public}d is illegal", coreThreadCount); + return false; + } + return true; +} + +bool WorkerPool::CheckThreadCount(int maxThreadCount, int coreThreadCount) +{ + return maxThreadCount >= coreThreadCount; +} + +bool WorkerPool::CheckMaxThreadCount(int maxThreadCount) +{ + if ((maxThreadCount > THREAD_UPPER_LIMIT) || (maxThreadCount < MAX_THREAD_LOWER_LIMIT)) { + return false; + } + return true; +} + +bool WorkerPool::CheckCoreThreadCount(int coreThreadCount) +{ + if ((coreThreadCount > THREAD_UPPER_LIMIT) || (coreThreadCount < CORE_THREAD_LOWER_LIMIT)) { + return false; + } + return true; +} + +long WorkerPool::GetKeepAliveTime(void) const +{ + return alive_time_Limit_; +} + +int WorkerPool::GetCoreThreadCount(void) const +{ + return core_thread_limit_; +} + +int WorkerPool::GetMaxThreadCount(void) const +{ + return thread_limit_; +} + +int WorkerPool::GetWorkCount(void) const +{ + unsigned int value = control_.load(); + return GetWorkingThreadNum(value); +} + +std::map WorkerPool::GetWorkerThreadsInfo(void) +{ + std::unique_lock mLock(poolLock_); + std::map workerThreadsInfo; + + for (auto it = pool_.begin(); it != pool_.end(); it++) { + if ((*it) != nullptr) { + workerThreadsInfo.emplace((*it)->GetThreadName(), (*it)->GetTaskCounter()); + } + } + return workerThreadsInfo; +} + +void WorkerPool::ClosePool(bool interrupt) +{ + APP_LOGI("WorkerPool::ClosePool begin interrupt=%{public}d", interrupt); + std::unique_lock mLock(poolLock_); + + AdvanceStateTo(CLOSING); + InterruptWorkers(); + + APP_LOGI("WorkerPool::ClosePool end"); +} + +void WorkerPool::InterruptWorkers(void) +{ + APP_LOGI("WorkerPool::InterruptWorkers begin"); + if (guardThread_ == nullptr) { + APP_LOGE("WorkerPool::InterruptWorkers guardThread is nullptr"); + return; + } + poolLock_.unlock(); + + { + std::unique_lock lock(exitPoolLock_); + stop_.store(true); + exit_.notify_all(); + } + + { + std::unique_lock lock(exitPoolLock_); + exitGuard_.wait(lock); + if (guardThread_->joinable()) { + APP_LOGI("WorkerPool::InterruptWorkers guardThread_ joinable"); + guardThread_->join(); + // Prevent manual call again + guardThread_ = nullptr; + } + } + + APP_LOGI("WorkerPool::InterruptWorkers end"); +} + +void WorkerPool::CreateGuardThread() +{ + APP_LOGI("WorkerPool::CreateGuardThread START"); + if (guardThread_ != nullptr) { + APP_LOGW("WorkerPool::CreateGuardThread guardThread_ is not nullptr"); + return; + } + auto guardTask = [&]() { + while (true) { + { + std::unique_lock lock(exitPoolLock_); + if (!exitPool_.empty()) { + exitPool_.front()->Join(); + exitPool_.erase(exitPool_.begin()); + } else { + exit_.wait(lock, [this] { + return this->stop_.load() || !this->exitPool_.empty(); + }); // return 防止先notify 后wait + } + } + if (stop_.load() && exitPool_.empty() && pool_.empty()) { + exitGuard_.notify_all(); + APP_LOGI("WorkerPool::CreateGuardThread break while"); + break; + } + } + APP_LOGI("WorkerPool::CreateGuardThread STOP"); + }; + + guardThread_ = std::make_shared(guardTask); +} + +bool WorkerPool::AddWorker(const std::shared_ptr &delegate, const std::shared_ptr &task) +{ + bool added = false; + if (!initFlag_.load()) { + APP_LOGE("WorkerPool::AddWorker workPool init failed"); + return added; + } + if (factory_ == nullptr) { + APP_LOGE("WorkerPool::AddWorker factory_ is nullptr"); + return added; + } + if (task == nullptr) { + APP_LOGE("WorkerPool::AddWorker task is nullptr"); + return added; + } + if (delegate == nullptr) { + APP_LOGE("WorkerPool::AddWorker delegate is nullptr"); + return added; + } + std::unique_lock mLock(poolLock_); + std::shared_ptr newThread = nullptr; + + for (;;) { + unsigned int value = control_.load(); + int num = GetWorkingThreadNum(value); + if (num >= thread_limit_) { + APP_LOGI("WorkerPool::AddWorker thread count exceed limits, num=%{public}d, limits=%{public}d", + num, + thread_limit_); + break; + } + if (!IsRunning(value)) { + APP_LOGI("WorkerPool::AddWorker thread pool is not running. value=%{public}d, closing=%{public}d, " + "count_bits=%{public}d", + value, + CLOSING, + COUNT_BITS); + break; + } + + if (CompareAndIncThreadNum(num)) { + newThread = std::make_shared(delegate, task, factory_); + if (newThread == nullptr) { + APP_LOGE("WorkerPool::AddWorker create thread fail"); + break; + } + + newThread->CreateThread(); + + APP_LOGI("WorkerPool::AddWorker create new thread"); + + pool_.emplace_back(newThread); + APP_LOGI("WorkerPool::AddWorker pool_ add thread ,POOL SIZE: %{public}zu", pool_.size()); + + added = true; + break; + } + + APP_LOGW("WorkerPool::AddWorker set thread state error. retry. "); + } + return added; +} + +void WorkerPool::OnWorkerExit(const std::shared_ptr &worker, bool isInterrupted) +{ + std::unique_lock mLock(poolLock_); + APP_LOGI("WorkerPool::OnWorkerExit start, pool size: %{public}zu", pool_.size()); + for (auto it = pool_.begin(); it != pool_.end(); it++) { + if ((*it).get() == worker.get()) { + APP_LOGI("WorkerPool::OnWorkerExit erase current, size=%{public}zu, threads=%{public}d", + pool_.size(), + GetWorkingThreadNum(control_.load())); + { + std::unique_lock lock(exitPoolLock_); + exitPool_.emplace_back(worker); + APP_LOGI("WorkerPool::OnWorkerExit exit notify all"); + exit_.notify_all(); + } + pool_.erase(it); + + break; + } + } + APP_LOGI("WorkerPool::OnWorkerExit end"); +} + +void WorkerPool::AfterRun(const std::shared_ptr &task) +{} + +void WorkerPool::BeforeRun(const std::shared_ptr &task) +{} + +unsigned int WorkerPool::GetWorkingThreadNum(unsigned int ctl) +{ + return ctl & CAPACITY; +} + +bool WorkerPool::IsRunning(int ctl) +{ + return ctl < CLOSING; +} + +int WorkerPool::GetStateFromControl(unsigned int ctl) +{ + return ctl & ~CAPACITY; +} + +void WorkerPool::AdvanceStateTo(unsigned int target) +{ + APP_LOGI("WorkerPool::AdvanceStateTo begin"); + for (;;) { + unsigned int current = control_.load(); + if ((current >= target) || + CompareAndSet(control_, current, CombineToControl(target, GetWorkingThreadNum(current)))) { + APP_LOGI("WorkerPool::AdvanceStateTo break"); + break; + } + } + APP_LOGI("WorkerPool::AdvanceStateTo end"); +} + +int WorkerPool::CombineToControl(unsigned int state, unsigned int count) +{ + return state | count; +} + +bool WorkerPool::CompareAndIncThreadNum(int expect) +{ + unsigned int ctl = control_.load(); + int state = GetStateFromControl(ctl); + return CompareAndSet(control_, ctl, CombineToControl(state, expect + 1)); +} + +void WorkerPool::DecrementThread(void) +{ + APP_LOGI("WorkerPool::DecrementThread begin"); + int curr = control_.load(); + while (!CompareAndDecThreadNum(curr)) { + curr = control_.load(); + } + APP_LOGI("WorkerPool::DecrementThread end"); +} + +bool WorkerPool::CompareAndDecThreadNum(int expect) +{ + return CompareAndSet(control_, expect, expect - 1); +} + +bool WorkerPool::CompareAndDecNum(int expectCount) +{ + unsigned int curr = control_.load(); + int state = GetStateFromControl(curr); + int expectControl = CombineToControl(state, expectCount); + return CompareAndDecThreadNum(expectControl); +} + +bool WorkerPool::CompareAndSet(std::atomic &atomicInt, int expect, int desire) +{ + return atomicInt.compare_exchange_strong(expect, desire); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/test/BUILD.gn b/common/task_dispatcher/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d867ca4185a867fd485cbf74f4d2229b852acacc --- /dev/null +++ b/common/task_dispatcher/test/BUILD.gn @@ -0,0 +1,80 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +group("unittest") { + testonly = true + + deps = [ + "unittest/barrier_handler_test:unittest", + "unittest/base_task_dispatcher_test:unittest", + "unittest/global_task_dispatcher_test:unittest", + "unittest/groupImpl_test:unittest", + "unittest/parallel_task_dispatcher_base_test:unittest", + "unittest/parallel_task_dispatcher_test:unittest", + "unittest/serial_task_dispatcher_test:unittest", + "unittest/spec_dispatcher_config_test:unittest", + "unittest/spec_task_dispatcher_test:unittest", + "unittest/sync_task_test:unittest", + "unittest/task_dispatcher_context_test:unittest", + "unittest/task_executor_test:unittest", + "unittest/task_handler_libevent_adapter_test:unittest", + "unittest/task_test:unittest", + "unittest/work_thread_test:unittest", + "unittest/worker_pool_test:unittest", + ] +} + +config("dispatcher_test_config") { + configs = [] + + defines = [] + + include_dirs = [ + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + + "${dispatcher_path}/include/dispatcher", + "${dispatcher_path}/include/threading", + "${dispatcher_path}/include/task", + + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + "${aafwk_path}/frameworks/kits/appkit/native/app/include/task", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/include", + ] +} + +ohos_source_set("dispatcher_test_source") { + testonly = true + + sources = [] + + include_dirs = [ "//third_party/json/include" ] + + public_configs = [ + "//utils/native/base:utils_config", + ":dispatcher_test_config", + ] + + public_deps = [ + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + deps = [ "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler" ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} diff --git a/common/task_dispatcher/test/unittest/barrier_handler_test/BUILD.gn b/common/task_dispatcher/test/unittest/barrier_handler_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f4d1aeae48baa320867a26e17490f640001c55c3 --- /dev/null +++ b/common/task_dispatcher/test/unittest/barrier_handler_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("BarrierHandlerTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "barrier_handler_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":BarrierHandlerTest" ] +} diff --git a/common/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp b/common/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..57eedb0cf9657977627c8e13fc5f1893f1f6e89a --- /dev/null +++ b/common/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "barrier_handler.h" +#undef private +#include "appexecfwk_errors.h" +#include "default_worker_pool_config.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; + +class BarrierHandlerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void BarrierHandlerTest::SetUpTestCase() +{} + +void BarrierHandlerTest::TearDownTestCase() +{} + +void BarrierHandlerTest::SetUp() +{} + +void BarrierHandlerTest::TearDown() +{} + +std::shared_ptr CreateBarrierHandler() +{ + std::shared_ptr config_ = std::make_shared(); + std::shared_ptr executor = std::make_shared(config_); + std::shared_ptr barrierHandler = std::make_shared(executor); + return barrierHandler; +} +/** + * @tc.number: BarrierHandler_ConstructorTest_001 + * @tc.name: Constructor + * @tc.desc: Test BarrierHandlerTest Constructor. + */ +HWTEST(BarrierHandlerTest, BarrierHandler_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("BarrierHandler_ConstructorTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr barrierHandler = CreateBarrierHandler(); + EXPECT_NE(barrierHandler, nullptr); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: BarrierHandler_interceptTest_001 + * @tc.name: intercept + * @tc.desc: Test BarrierHandler intercept. + */ +HWTEST(BarrierHandlerTest, BarrierHandler_interceptTest_001, TestSize.Level0) +{ + auto name = std::string("BarrierHandler_interceptTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr barrierHandler = CreateBarrierHandler(); + std::shared_ptr runnable = std::make_shared([&]() { GTEST_LOG_(INFO) << name << " Runnable"; }); + std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, nullptr); + ErrCode result = barrierHandler->Intercept(task); + task->Run(); + task->AfterTaskExecute(); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: BarrierHandler_interceptTest_002 + * @tc.name: intercept + * @tc.desc: Test BarrierHandler intercept. + */ +HWTEST(BarrierHandlerTest, BarrierHandler_interceptTest_002, TestSize.Level0) +{ + auto name = std::string("BarrierHandler_interceptTest_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr barrierHandler = CreateBarrierHandler(); + // add task + std::shared_ptr runnable = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + GTEST_LOG_(INFO) << name << " Runnable"; + }); + std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, nullptr); + barrierHandler->Intercept(task); + // add barrier + std::shared_ptr barrierRunnable = + std::make_shared([&]() { GTEST_LOG_(INFO) << name << " barrierTask "; }); + std::shared_ptr barrierTask = std::make_shared(barrierRunnable, TaskPriority::DEFAULT, nullptr); + barrierHandler->AddBarrier(barrierTask); + // add interceptTask + std::shared_ptr interceptRunnable = + std::make_shared([&]() { GTEST_LOG_(INFO) << name << " interceptRunnable"; }); + std::shared_ptr interceptTask = std::make_shared(interceptRunnable, TaskPriority::DEFAULT, nullptr); + // intercept result + bool result = barrierHandler->Intercept(interceptTask); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: BarrierHandler_addBarrierTest_001 + * @tc.name: addBarrier + * @tc.desc: Test BarrierHandler addBarrier. + */ +HWTEST(BarrierHandlerTest, BarrierHandler_addBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("BarrierHandler_interceptTest_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr barrierHandler = CreateBarrierHandler(); + + std::atomic count(0); + + std::shared_ptr barrierRunnable = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " add barrier Task "; + }); + std::shared_ptr barrierTask = std::make_shared(barrierRunnable, TaskPriority::DEFAULT, nullptr); + barrierHandler->AddBarrier(barrierTask); + EXPECT_EQ(count.load(), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(600)); + EXPECT_EQ(count.load(), 1); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: BarrierHandler_addBarrierTest_002 + * @tc.name: addBarrier + * @tc.desc: Test BarrierHandler barrier not execute now. + */ +HWTEST(BarrierHandlerTest, BarrierHandler_addBarrierTest_002, TestSize.Level0) +{ + auto name = std::string("BarrierHandler_addBarrierTest_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr barrierHandler = CreateBarrierHandler(); + + std::atomic count(0); + + std::shared_ptr taskRun1 = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " add barrier Task "; + }); + std::shared_ptr task1 = std::make_shared(taskRun1, TaskPriority::DEFAULT, nullptr); + barrierHandler->Intercept(task1); + std::shared_ptr taskRun2 = std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " add barrier Task "; + }); + std::shared_ptr task2 = std::make_shared(taskRun2, TaskPriority::DEFAULT, nullptr); + barrierHandler->Intercept(task2); + + std::shared_ptr barrierRunnable = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + EXPECT_EQ(count.load(), 2); + GTEST_LOG_(INFO) << name << " add barrier Task "; + }); + std::shared_ptr barrierTask = std::make_shared(barrierRunnable, TaskPriority::DEFAULT, nullptr); + barrierHandler->AddBarrier(barrierTask); + GTEST_LOG_(INFO) << name << " end"; +} \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/base_task_dispatcher_test/BUILD.gn b/common/task_dispatcher/test/unittest/base_task_dispatcher_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..125246d8aefb68438bcc6984f9db6a2056244867 --- /dev/null +++ b/common/task_dispatcher/test/unittest/base_task_dispatcher_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("BaseTaskDispatcherTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "base_task_dispatcher_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":BaseTaskDispatcherTest" ] +} diff --git a/common/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp b/common/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b86f345d621ddbbe902b6dfac0f6f5116c0d1fa1 --- /dev/null +++ b/common/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp @@ -0,0 +1,405 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#undef private +#include "base_task_dispatcher.h" +#include "runnable.h" +#include "serial_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_dispatcher_context.h" + +#include +#include +#include +#include + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +using OHOS::AppExecFwk ::BaseTaskDispatcher; +using OHOS::AppExecFwk::DefaultWorkerPoolConfig; +using OHOS::AppExecFwk::Group; +using OHOS::AppExecFwk::GroupImpl; +using OHOS::AppExecFwk::IteratableTask; +using OHOS::AppExecFwk::Revocable; +using OHOS::AppExecFwk::Runnable; +using OHOS::AppExecFwk ::SerialTaskDispatcher; +using OHOS::AppExecFwk::TaskDispatcher; +using OHOS::AppExecFwk::TaskDispatcherContext; +using OHOS::AppExecFwk::TaskExecutor; +using OHOS::AppExecFwk::TaskPriority; +using OHOS::AppExecFwk::WorkerPoolConfig; + +class BaseTaskDispatcherTest : public testing::Test { +public: + void SetUp(); + void TearDown(); + std::shared_ptr CreateSerialTaskDispatcher(); + std::shared_ptr context; + std::shared_ptr ptrSerialTaskDispatcher; + static void SetUpTestCase(); + static void TearDownTestCase(); +}; + +void BaseTaskDispatcherTest::SetUpTestCase() +{} + +void BaseTaskDispatcherTest::TearDownTestCase() +{} + +void BaseTaskDispatcherTest::SetUp() +{ + context = std::make_shared(); + std::string dispatcherName = "test-serial-dispatcher"; + TaskPriority taskPriority = TaskPriority::DEFAULT; + ptrSerialTaskDispatcher = context->CreateSerialDispatcher(dispatcherName, taskPriority); +} + +void BaseTaskDispatcherTest::TearDown() +{ + context = nullptr; + ptrSerialTaskDispatcher = nullptr; +} + +const std::string Prefix(const std::string &name) +{ + return std::string(">>> prefix :") + std::string(" ") + name + std::string(": "); +} + +/** + * @tc.number: CreateBaseTaskDispatcherTest_0100 + * @tc.name: test create BaseTaskDispatcher + * @tc.desc: 1.create BaseTaskDispatcher + * 2.get TaskPriority successfully + */ +HWTEST_F(BaseTaskDispatcherTest, CreateBaseTaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CreateBaseTaskDispatcher_0100 start"; + int priority = ptrSerialTaskDispatcher->GetPriority(); + EXPECT_EQ(priority, TaskPriority::DEFAULT); + GTEST_LOG_(INFO) << "CreateBaseTaskDispatcher_0100 end"; +} + +/** + * @tc.number: SyncDispatchBarrier_0100 + * @tc.name: test SyncDispatchBarrier + * @tc.desc: 1.create SerialTaskDispatcher + * 2.SyncDispatchBarrier successfully + */ +HWTEST_F(BaseTaskDispatcherTest, SyncDispatchBarrier_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "SyncDispatchBarrier_0100 start"; + const std::string name("SyncDispatchBarrier_0100"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + // init + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + long sleep1 = 200; + ptrSerialTaskDispatcher->SyncDispatchBarrier(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_EQ(index, 0); + GTEST_LOG_(INFO) << Prefix(name) << "SyncDispatchBarrier-" << 1 << " thread " << std::this_thread::get_id() + << ", sleep for " << sleep1 << " ms"; + })); + + // serial execute + EXPECT_EQ(count.load(), 1); + + long sleep2 = 100; + ptrSerialTaskDispatcher->SyncDispatchBarrier(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_EQ(index, 1); + GTEST_LOG_(INFO) << Prefix(name) << "SyncDispatchBarrier-" << 2 << " thread " << std::this_thread::get_id() + << ", sleep for " << sleep2 << " ms"; + })); + + // serial execute + EXPECT_EQ(count.load(), 2); + long wait = sleep1 + sleep2 + 100; + GTEST_LOG_(INFO) << Prefix(name) << "wait for " << (wait); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_EQ(count.load(), 2); + GTEST_LOG_(INFO) << "sync thread end " << std::this_thread::get_id(); + GTEST_LOG_(INFO) << Prefix(name) << "end "; + GTEST_LOG_(INFO) << "SyncDispatchBarrier_0100 end"; +} +/** + * @tc.number: AsyncDispatchBarrier_0100 + * @tc.name: test AsyncDispatchBarrier + * @tc.desc: 1.create SerialTaskDispatcher + * 2.AsyncDispatchBarrier successfully + */ +HWTEST_F(BaseTaskDispatcherTest, AsyncDispatchBarrier_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AsyncDispatchBarrier_0100 start"; + const std::string name("AsyncDispatchBarrier_0100"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + std::atomic count(0); + long sleep1 = 200; + ptrSerialTaskDispatcher->AsyncDispatchBarrier(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_EQ(index, 0); + GTEST_LOG_(INFO) << Prefix(name) << "AsyncDispatchBarrier-" << index << " thread " << std::this_thread::get_id() + << ", sleep for " << sleep1 << " ms"; + })); + + // async execute + EXPECT_LT(count.load(), 1); + + long sleep2 = 100; + ptrSerialTaskDispatcher->AsyncDispatchBarrier(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_EQ(index, 1); + GTEST_LOG_(INFO) << Prefix(name) << "AsyncDispatchBarrier-" << index << " thread " << std::this_thread::get_id() + << ", sleep for " << sleep2 << " ms"; + })); + EXPECT_LT(count.load(), 2); + long wait = sleep1 + sleep2 + 100; + GTEST_LOG_(INFO) << Prefix(name) << "wait for " << (wait); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_EQ(count.load(), 2); + GTEST_LOG_(INFO) << Prefix(name) << "end "; + GTEST_LOG_(INFO) << "AsyncDispatchBarrier_0100 end"; +} + +/** + * @tc.number: CreateDispatchGroup_0100 + * @tc.name: test CreateDispatchGroup + * @tc.desc: 1.create SerialTaskDispatcher + * 2.CreateDispatchGroup successfully + */ +HWTEST_F(BaseTaskDispatcherTest, CreateDispatchGroup_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CreateDispatchGroup_0100 start"; + std::shared_ptr gptr = ptrSerialTaskDispatcher->CreateDispatchGroup(); + EXPECT_TRUE(ptrSerialTaskDispatcher->GroupDispatchWait(gptr, 10)); + GTEST_LOG_(INFO) << "CreateDispatchGroup_0100 end"; +} + +/** + * @tc.number: AsyncGroupDispatch_0100 + * @tc.name: test AsyncGroupDispatch + * @tc.desc: 1.create SerialTaskDispatcher + * 2.AsyncGroupDispatch successfully + */ +HWTEST_F(BaseTaskDispatcherTest, AsyncGroupDispatch_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AsyncGroupDispatch_0100 start"; + const std::string name("AsyncGroupDispatch_0100"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + std::shared_ptr gptr = ptrSerialTaskDispatcher->CreateDispatchGroup(); + std::atomic count(0); + long sleep1 = 200; + ptrSerialTaskDispatcher->AsyncGroupDispatch(gptr, std::make_shared([&count, &sleep1, &name]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_EQ(index, 0); + GTEST_LOG_(INFO) << Prefix(name) << "AsyncGroupDispatch-" << index << " thread " << std::this_thread::get_id() + << ", sleep for " << sleep1 << " ms"; + })); + + // async execute + EXPECT_LT(count.load(), 1); + + long sleep2 = 100; + ptrSerialTaskDispatcher->AsyncGroupDispatch(gptr, std::make_shared([&count, &sleep2, &name]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_EQ(index, 1); + GTEST_LOG_(INFO) << Prefix(name) << "AsyncGroupDispatch-" << index << " thread " << std::this_thread::get_id() + << ", sleep for " << sleep2 << " ms"; + })); + EXPECT_LT(count.load(), 2); + long wait = sleep1 + sleep2 + 100; + GTEST_LOG_(INFO) << Prefix(name) << "wait for " << (wait); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_EQ(count.load(), 2); + GTEST_LOG_(INFO) << Prefix(name) << "end "; + GTEST_LOG_(INFO) << "AsyncGroupDispatch_0100 end"; +} + +/** + * @tc.number: ApplyDispatch_0100 + * @tc.name: test ApplyDispatch + * @tc.desc: 1.create SerialTaskDispatcher + * 2.ApplyDispatch successfully + */ +HWTEST_F(BaseTaskDispatcherTest, ApplyDispatch_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ApplyDispatch_0100 start"; + + const std::string name("ApplyDispatch_0100"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + + std::atomic count(0); + long sleep1 = 101; + auto repeats1 = std::make_shared>([&](long index) { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + count.fetch_add(1); + GTEST_LOG_(INFO) << Prefix(name) << "repeat1-" << index << ", thread " << std::this_thread::get_id() + << ", sleep for " << sleep1 << " ms"; + }); + ptrSerialTaskDispatcher->ApplyDispatch(repeats1, 10); + + long sleep2 = 100; + auto repeats2 = std::make_shared>([&](long index) { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + count.fetch_add(1); + GTEST_LOG_(INFO) << Prefix(name) << "repeat2-" << index << ", thread " << std::this_thread::get_id() + << ", sleep for " << sleep2 << " ms"; + }); + ptrSerialTaskDispatcher->ApplyDispatch(repeats2, 10); + // async execute + EXPECT_LT(count.load(), 20); + long wait = sleep1 * 10 + sleep2 * 10 + 100 + 100; + GTEST_LOG_(INFO) << Prefix(name) << "wait for " << (wait); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_EQ(count.load(), 20); + GTEST_LOG_(INFO) << Prefix(name) << "end "; + GTEST_LOG_(INFO) << "ApplyDispatch_0100 end"; +} + +/** + * @tc.number: ApplyDispatch_0200 + * @tc.name: test ApplyDispatch + * @tc.desc: 1.create SerialTaskDispatcher + * 2.ApplyDispatch iterations <0 + */ +HWTEST_F(BaseTaskDispatcherTest, ApplyDispatch_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ApplyDispatch_0200 start"; + + const std::string name("ApplyDispatch_0200"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + ptrSerialTaskDispatcher->ApplyDispatch(nullptr, 10); + GTEST_LOG_(INFO) << Prefix(name) << "end "; + GTEST_LOG_(INFO) << "ApplyDispatch_0200 end"; +} +/** + * @tc.number: ApplyDispatch_0300 + * @tc.name: test ApplyDispatch + * @tc.desc: 1.create SerialTaskDispatcher + * 2.ApplyDispatch task is nullptr + */ +HWTEST_F(BaseTaskDispatcherTest, ApplyDispatch_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ApplyDispatch_0300 start"; + + const std::string name("ApplyDispatch_0300"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + auto repeats1 = std::make_shared>( + [&](long index) { GTEST_LOG_(INFO) << "Error:ApplyDispatch_0300 is run "; }); + ptrSerialTaskDispatcher->ApplyDispatch(repeats1, -1); + GTEST_LOG_(INFO) << Prefix(name) << "end "; + GTEST_LOG_(INFO) << "ApplyDispatch_0300 end"; +} +/** + * @tc.number:GroupDispatchWait_0100 + * @tc.name: test GroupDispatchWait + * @tc.desc: 1.create SerialTaskDispatcher + * 2.GroupDispatchWait successfully + */ +HWTEST_F(BaseTaskDispatcherTest, GroupDispatchWait_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GroupDispatchWait_0100 start"; + std::shared_ptr gptr = ptrSerialTaskDispatcher->CreateDispatchGroup(); + EXPECT_TRUE(ptrSerialTaskDispatcher->GroupDispatchWait(gptr, 0)); + GTEST_LOG_(INFO) << "GroupDispatchWait_0100 end"; +} + +/** + * @tc.number:GroupDispatchNotify_0100 + * @tc.name: test GroupDispatchNotify + * @tc.desc: 1.create SerialTaskDispatcher + * 2.GroupDispatchNotify successfully + */ +HWTEST_F(BaseTaskDispatcherTest, GroupDispatchNotify_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GroupDispatchNotify_0100 start"; + std::atomic count(0); + std::shared_ptr gptr = ptrSerialTaskDispatcher->CreateDispatchGroup(); + count.fetch_add(1); + std::function task = [&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << "GroupDispatchNotify_0100 :notify task is run"; + }; + std::shared_ptr rptr = std::make_shared(task); + EXPECT_EQ(count.load(), 1); + GTEST_LOG_(INFO) << "GroupDispatchNotify_0100 end"; +} + +/** + * @tc.number:GetPriority_0100 + * @tc.name: test GetPriority + * @tc.desc: 1.create SerialTaskDispatcher + * 2.GetPriority successfully + */ +HWTEST_F(BaseTaskDispatcherTest, GetPriority_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetPriority_0100 start"; + EXPECT_EQ(ptrSerialTaskDispatcher->GetPriority(), TaskPriority::DEFAULT); + GTEST_LOG_(INFO) << "GetPriority_0100 end"; +} +/** + * @tc.number:TracePointBeforePost_0100 + * @tc.name: TracePointBeforePost + * @tc.desc: 1.create SerialTaskDispatcher + * 2.TracePointBeforePost successfully + */ +HWTEST_F(BaseTaskDispatcherTest, TracePointBeforePost_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "TracePointBeforePost_0100 start"; + Runnable TestTask([]() { GTEST_LOG_(INFO) << "TracePointBeforePost_0100 task"; }); + std::shared_ptr runnable = std::make_shared(TestTask); + std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, ptrSerialTaskDispatcher); + std::string dispatcherName = "TracePointBeforePost_0100 "; + ptrSerialTaskDispatcher->TracePointBeforePost(task, true, dispatcherName); + GTEST_LOG_(INFO) << "TracePointBeforePost_0100 end"; +} + +/** + * @tc.number:TracePointAfterPost_0100 + * @tc.name: TracePointAfterPost + * @tc.desc: 1.create SerialTaskDispatcher + * 2.TracePointAfterPost successfully + */ +HWTEST_F(BaseTaskDispatcherTest, TracePointAfterPost_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "TracePointAfterPost_0100 start"; + Runnable TestTask([]() { GTEST_LOG_(INFO) << "TracePointBeforePost_0100 task"; }); + std::shared_ptr runnable = std::make_shared(TestTask); + std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, ptrSerialTaskDispatcher); + std::string dispatcherName = "TracePointAfterPost_0100 "; + ptrSerialTaskDispatcher->TracePointAfterPost(task, false, dispatcherName); + GTEST_LOG_(INFO) << "TracePointAfterPost_0100 end"; +} diff --git a/common/task_dispatcher/test/unittest/global_task_dispatcher_test/BUILD.gn b/common/task_dispatcher/test/unittest/global_task_dispatcher_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fb64f1340f3978ebdff7630268ebddf6ef754b52 --- /dev/null +++ b/common/task_dispatcher/test/unittest/global_task_dispatcher_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("GlobalTaskDispatcherTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "global_task_dispatcher_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":GlobalTaskDispatcherTest" ] +} diff --git a/common/task_dispatcher/test/unittest/global_task_dispatcher_test/global_task_dispatcher_test.cpp b/common/task_dispatcher/test/unittest/global_task_dispatcher_test/global_task_dispatcher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..636b8e1059e5a303d612faef7b3e18f698a3d7a0 --- /dev/null +++ b/common/task_dispatcher/test/unittest/global_task_dispatcher_test/global_task_dispatcher_test.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "global_task_dispatcher.h" +#undef private +#include "default_worker_pool_config.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class GlobalTaskDispatcherTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void GlobalTaskDispatcherTest::SetUpTestCase() +{} + +void GlobalTaskDispatcherTest::TearDownTestCase() +{} + +void GlobalTaskDispatcherTest::SetUp() +{} + +void GlobalTaskDispatcherTest::TearDown() +{} + +/** + * @tc.number: GlobalTaskDispatcher_ConstructorTest_001 + * @tc.name: Constructor + * @tc.desc: Test GlobalTaskDispatcherTest Constructor. + */ +HWTEST(GlobalTaskDispatcherTest, GlobalTaskDispatcher_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("GlobalTaskDispatcher_ConstructorTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr config_ = std::make_shared(); + std::shared_ptr executor = std::make_shared(config_); + std::shared_ptr globalTaskDispatcher = + std::make_shared(TaskPriority::DEFAULT, executor); + EXPECT_NE(globalTaskDispatcher, nullptr); + GTEST_LOG_(INFO) << name << " end"; +} \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/groupImpl_test/BUILD.gn b/common/task_dispatcher/test/unittest/groupImpl_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3ce7d0beb41366ae443683d853380cde5efbd08a --- /dev/null +++ b/common/task_dispatcher/test/unittest/groupImpl_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("GroupImplTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "groupImpl_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":GroupImplTest" ] +} diff --git a/common/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp b/common/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..344cfbc9267b59027074726f859114dc7fb5d6b7 --- /dev/null +++ b/common/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include "group_impl.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class GroupImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void GroupImplTest::SetUpTestCase(void) +{} + +void GroupImplTest::TearDownTestCase(void) +{} + +void GroupImplTest::SetUp(void) +{} + +void GroupImplTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_GroupImpl_ConstructorTest_001 + * @tc.name: GroupImplConstructor + * @tc.desc: Test GroupImpl Constructor. + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_GroupImpl_ConstructorTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + EXPECT_TRUE((groupPtr != nullptr)); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_GroupImpl_AwaitAllTasks_001 + * @tc.name: AwaitAllTasks + * @tc.desc: Test GroupImpl await all tasks done + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AwaitAllTasks_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_GroupImpl_AwaitAllTasks_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + // add task + groupPtr->Associate(); + groupPtr->Associate(); + // add notification + std::shared_ptr notification1 = + std::make_shared([]() { GTEST_LOG_(INFO) << "GroupImpl notification1"; }); + std::shared_ptr notification2 = + std::make_shared([]() { GTEST_LOG_(INFO) << "GroupImpl notification2"; }); + groupPtr->AddNotification(notification1); + groupPtr->AddNotification(notification2); + // excute task + std::thread excuteTask1([&]() { groupPtr->NotifyTaskDone(); }); + std::thread excuteTask2([&]() { groupPtr->NotifyTaskDone(); }); + excuteTask1.detach(); + excuteTask2.detach(); + groupPtr->AwaitAllTasks(1000); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_Run_002 + * @tc.name: AwaitAllTasks + * @tc.desc: Test GroupImpl await all tasks done + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AwaitAllTasks_002, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_Run_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + // add task + groupPtr->Associate(); + // add notification + std::shared_ptr notification = + std::make_shared([]() { GTEST_LOG_(INFO) << "GroupImpl notification1"; }); + groupPtr->AddNotification(notification); + bool result = groupPtr->AwaitAllTasks(1000); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_GroupImpl_Associate_001 + * @tc.name: Associate + * @tc.desc: Test GroupImpl add task + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_Associate_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_GroupImpl_Associate_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + // add task + groupPtr->Associate(); + bool result = groupPtr->AwaitAllTasks(1000); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_GroupImpl_NotifyTaskDone_001 + * @tc.name: NotifyTaskDone + * @tc.desc: Test GroupImpl notify task done + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_NotifyTaskDone_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_GroupImpl_NotifyTaskDone_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + groupPtr->Associate(); + groupPtr->NotifyTaskDone(); + bool result = groupPtr->AwaitAllTasks(1000); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_GroupImpl_AddNotification_001 + * @tc.name: AddNotification + * @tc.desc: Test GroupImpl add a notification + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_GroupImpl_AddNotification_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + std::shared_ptr notification = + std::make_shared([]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); + bool result = groupPtr->AddNotification(notification); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_GroupImpl_AddNotification_002 + * @tc.name: AddNotification + * @tc.desc: Test GroupImpl max number of notifications + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_002, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_GroupImpl_AddNotification_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + for (int i = 0; i < 1000; i++) { + std::shared_ptr notification = + std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); + groupPtr->AddNotification(notification); + } + std::shared_ptr notificationTask = + std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); + bool result = groupPtr->AddNotification(notificationTask); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_GroupImpl_AddNotification_003 + * @tc.name: AddNotification + * @tc.desc: Test GroupImpl max number of notifications + */ +HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_003, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_GroupImpl_AddNotification_003"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr groupPtr = std::make_shared(); + groupPtr->Associate(); + for (int i = 0; i < 1000; i++) { + std::shared_ptr notification = + std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); + groupPtr->AddNotification(notification); + } + std::shared_ptr notificationTask = + std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); + bool result = groupPtr->AddNotification(notificationTask); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << name << " end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/BUILD.gn b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..034e2735ffe4a1e606d29ecedac43e342ab954f2 --- /dev/null +++ b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("ParallelTaskDispatcherBaseTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "parallel_task_dispatcher_base_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":ParallelTaskDispatcherBaseTest" ] +} diff --git a/common/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7e924cf0234769f389676492b8b6b03d87e4b14 --- /dev/null +++ b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "parallel_task_dispatcher_base.h" +#undef private +#include "appexecfwk_errors.h" +#include "task_priority.h" +#include "task_executor.h" +#include "task.h" +#include "default_worker_pool_config.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; + +class ParallelTaskDispatcherBaseTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr CreateParallelTaskDispatcherBase( + std::string name, TaskPriority priority); +}; + +void ParallelTaskDispatcherBaseTest::SetUpTestCase() +{} + +void ParallelTaskDispatcherBaseTest::TearDownTestCase() +{} + +void ParallelTaskDispatcherBaseTest::SetUp() +{} + +void ParallelTaskDispatcherBaseTest::TearDown() +{} + +std::shared_ptr CreateParallelTaskDispatcherBase(std::string name, TaskPriority priority) +{ + std::shared_ptr config_ = std::make_shared(); + std::shared_ptr executor = std::make_shared(config_); + std::shared_ptr parallelTaskDispatcherBaseBase = + std::make_shared(priority, executor, name); + + return parallelTaskDispatcherBaseBase; +} + +/** + * @tc.number: ParallelTaskDispatcherBase_ConstructorTest_001 + * @tc.name: Constructor + * @tc.desc: Test ParallelTaskDispatcherBase Constructor. + */ +HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcherBase_ConstructorTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcherBase = + CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); + EXPECT_EQ(parallelTaskDispatcherBase->GetPriority(), TaskPriority::DEFAULT); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcherBase_SyncDispatchTest_001 + * @tc.name: SyncDispatch + * @tc.desc: Test ParallelTaskDispatcherBase sync dispatcher task. + */ +HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_SyncDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcherBase_SyncDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcherBase = + CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); + ErrCode errCode = parallelTaskDispatcherBase->SyncDispatch(nullptr); + EXPECT_TRUE(errCode == ERR_APPEXECFWK_CHECK_FAILED); + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + std::shared_ptr rptr = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Runnable1"; + }); + parallelTaskDispatcherBase->SyncDispatch(rptr); + EXPECT_EQ(count.load(), 1); + + std::shared_ptr rptr2 = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Runnable2"; + }); + parallelTaskDispatcherBase->SyncDispatch(rptr2); + EXPECT_EQ(count.load(), 2); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcherBase_AsyncDispatchTest_001 + * @tc.name: AsyncDispatch + * @tc.desc: Test ParallelTaskDispatcherBase async dispatcher task. + */ +HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcherBase_AsyncDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcherBase = + CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); + std::shared_ptr revocable = parallelTaskDispatcherBase->AsyncDispatch(nullptr); + EXPECT_TRUE(revocable == nullptr); + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + std::shared_ptr rptr = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Runnable1"; + }); + parallelTaskDispatcherBase->AsyncDispatch(rptr); + EXPECT_LT(count.load(), 1); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + EXPECT_EQ(count.load(), 1); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcherBase_DelayDispatchTest_001 + * @tc.name: DelayDispatch + * @tc.desc: Test ParallelTaskDispatcherBase delay dispatch tasks. + */ +HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_DelayDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcherBase_DelayDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcherBase = + CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + std::shared_ptr rptr = std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Runnable"; + }); + parallelTaskDispatcherBase->DelayDispatch(rptr, 1000); + EXPECT_LT(count.load(), 1); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + EXPECT_EQ(count.load(), 1); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcherBase_DelayDispatchTest_002 + * @tc.name: DelayDispatch + * @tc.desc: Test ParallelTaskDispatcherBase delay dispatch tasks. + */ +HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_DelayDispatchTest_002, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcherBase_DelayDispatchTest_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcherBase = + CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + std::shared_ptr rptr = std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Runnable"; + }); + std::shared_ptr revocable = parallelTaskDispatcherBase->DelayDispatch(nullptr, 1000); + EXPECT_TRUE(revocable == nullptr); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcherBase_AsyncGroupDispatchTest_001 + * @tc.name: AsyncGroupDispatch + * @tc.desc: Test ParallelTaskDispatcherBase add group. + */ +HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcherBase_AsyncGroupDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcherBase = + CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + std::shared_ptr group1 = parallelTaskDispatcherBase->CreateDispatchGroup(); + std::shared_ptr group1Run1 = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(800)); + count.fetch_add(1); + int index = count.load(); + EXPECT_EQ(index, 3); + GTEST_LOG_(INFO) << name << " Group1 : Runnable1"; + }); + parallelTaskDispatcherBase->AsyncGroupDispatch(group1, group1Run1); + std::shared_ptr group1Run2 = std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Group1 : Runnable2"; + }); + parallelTaskDispatcherBase->AsyncGroupDispatch(group1, group1Run2); + std::shared_ptr group2 = parallelTaskDispatcherBase->CreateDispatchGroup(); + std::shared_ptr group2Run = std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Group2 : Runnable"; + }); + parallelTaskDispatcherBase->AsyncGroupDispatch(group2, group2Run); + EXPECT_LT(count.load(), 3); + std::this_thread::sleep_for(std::chrono::milliseconds(1200)); + EXPECT_EQ(count.load(), 3); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcherBase_AsyncGroupDispatchTest_002 + * @tc.name: AsyncGroupDispatch + * @tc.desc: Test ParallelTaskDispatcherBase add group. + */ +HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDispatchTest_002, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcherBase_AsyncGroupDispatchTest_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcherBase = + CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); + + std::shared_ptr revocable = parallelTaskDispatcherBase->AsyncGroupDispatch(nullptr, nullptr); + EXPECT_TRUE(revocable == nullptr); + GTEST_LOG_(INFO) << name << " end"; +} \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/parallel_task_dispatcher_test/BUILD.gn b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2d806681b24fb5e7391d621b5182d7a40f04d270 --- /dev/null +++ b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("ParallelTaskDispatcherTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "parallel_task_dispatcher_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":ParallelTaskDispatcherTest" ] +} diff --git a/common/task_dispatcher/test/unittest/parallel_task_dispatcher_test/parallel_task_dispatcher_test.cpp b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_test/parallel_task_dispatcher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fa744cf871a81d49a2ca88f1c12933c3d90cb52 --- /dev/null +++ b/common/task_dispatcher/test/unittest/parallel_task_dispatcher_test/parallel_task_dispatcher_test.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "parallel_task_dispatcher.h" +#undef private +#include "task_priority.h" +#include "task_executor.h" +#include "task.h" +#include "default_worker_pool_config.h" +#include "appexecfwk_errors.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; + +class ParallelTaskDispatcherTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr CreateParallelTaskDispatcher(std::string name, TaskPriority priority); +}; + +void ParallelTaskDispatcherTest::SetUpTestCase() +{} + +void ParallelTaskDispatcherTest::TearDownTestCase() +{} + +void ParallelTaskDispatcherTest::SetUp() +{} + +void ParallelTaskDispatcherTest::TearDown() +{} + +std::shared_ptr CreateParallelTaskDispatcher(std::string name, TaskPriority priority) +{ + std::shared_ptr config_ = std::make_shared(); + std::shared_ptr executor = std::make_shared(config_); + std::shared_ptr parallelTaskDispatcher = + std::make_shared(name, priority, executor); + return parallelTaskDispatcher; +} + +/** + * @tc.number: ParallelTaskDispatcher_ConstructorTest_001 + * @tc.name: Constructor + * @tc.desc: Test ParallelTaskDispatcher Constructor. + */ +HWTEST(ParallelTaskDispatcherTest, ParallelTaskDispatcher_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("Parallel_Task_Dispatcher_Test_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcher = + CreateParallelTaskDispatcher(name, TaskPriority::DEFAULT); + { + EXPECT_EQ(parallelTaskDispatcher->GetPriority(), TaskPriority::DEFAULT); + } + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_SyncDispatchBarrierTest_001 + * @tc.name: SyncDispatchBarrier + * @tc.desc: Test ParallelTaskDispatcher SyncDispatchBarrier. + */ +HWTEST(ParallelTaskDispatcherTest, ParallelTaskDispatcher_SyncDispatchBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_SyncDispatchBarrierTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcher = + CreateParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::shared_ptr rptr = std::make_shared([&]() { GTEST_LOG_(INFO) << name << " Runnable"; }); + if (parallelTaskDispatcher->barrierHandler_ != nullptr) { + int before = parallelTaskDispatcher->barrierHandler_->barrierQueue_.size(); + parallelTaskDispatcher->SyncDispatchBarrier(rptr); + int after = parallelTaskDispatcher->barrierHandler_->barrierQueue_.size(); + EXPECT_LT(before, after); + } else { + GTEST_LOG_(INFO) << "parallelTaskDispatcher barrierHandler_ is null"; + } + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_SyncDispatchBarrierTest_002 + * @tc.name: SyncDispatchBarrier + * @tc.desc: Test ParallelTaskDispatcher SyncDispatchBarrier. + */ +HWTEST(ParallelTaskDispatcherTest, ParallelTaskDispatcher_SyncDispatchBarrierTest_002, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_SyncDispatchBarrierTest_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcher = + CreateParallelTaskDispatcher(name, TaskPriority::DEFAULT); + ErrCode result = parallelTaskDispatcher->SyncDispatchBarrier(nullptr); + EXPECT_TRUE(result == ERR_APPEXECFWK_CHECK_FAILED); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_AsyncDispatchBarrierTest_001 + * @tc.name: AsyncDispatchBarrier + * @tc.desc: Test ParallelTaskDispatcher AsyncDispatchBarrier. + */ +HWTEST(ParallelTaskDispatcherTest, ParallelTaskDispatcher_AsyncDispatchBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_AsyncDispatchBarrierTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcher = + CreateParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::shared_ptr rptr = std::make_shared([&]() { GTEST_LOG_(INFO) << name << " Runnable"; }); + if (parallelTaskDispatcher->barrierHandler_ != nullptr) { + int before = parallelTaskDispatcher->barrierHandler_->barrierQueue_.size(); + parallelTaskDispatcher->AsyncDispatchBarrier(rptr); + int after = parallelTaskDispatcher->barrierHandler_->barrierQueue_.size(); + EXPECT_LT(before, after); + } else { + GTEST_LOG_(INFO) << "parallelTaskDispatcher barrierHandler_ is null"; + } + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_AsyncDispatchBarrierTest_002 + * @tc.name: AsyncDispatchBarrier + * @tc.desc: Test ParallelTaskDispatcher AsyncDispatchBarrier. + */ +HWTEST(ParallelTaskDispatcherTest, ParallelTaskDispatcher_AsyncDispatchBarrierTest_002, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_AsyncDispatchBarrierTest_002"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr parallelTaskDispatcher = + CreateParallelTaskDispatcher(name, TaskPriority::DEFAULT); + ErrCode result = parallelTaskDispatcher->AsyncDispatchBarrier(nullptr); + EXPECT_TRUE(result == ERR_APPEXECFWK_CHECK_FAILED); + GTEST_LOG_(INFO) << name << " end"; +} diff --git a/common/task_dispatcher/test/unittest/serial_task_dispatcher_test/BUILD.gn b/common/task_dispatcher/test/unittest/serial_task_dispatcher_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0c5f1598c3eb5df89f69e892c5da40de3fe8122b --- /dev/null +++ b/common/task_dispatcher/test/unittest/serial_task_dispatcher_test/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("SerialTaskDispatcherTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "serial_task_dispatcher_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + deps = [ ":SerialTaskDispatcherTest" ] +} diff --git a/common/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp b/common/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f85ceb402a0c010665e725a5a084822b9ea4fa7f --- /dev/null +++ b/common/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp @@ -0,0 +1,595 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "serial_task_dispatcher.h" +#undef private +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "default_worker_pool_config.h" +#include "task.h" +#include "task_executor.h" +#include "task_priority.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; + +class SerialTaskDispatcherTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + void SetUp() + {} + void TearDown() + {} +}; + +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_SyncDispatchTest_1000, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_SyncDispatchTest_1000"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared(name, priority, executor); + + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + dispatcher->SyncDispatch(std::make_shared([&count, &name]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name + " task " + std::to_string(index) + " end"; + })); + + EXPECT_TRUE(count.load() == 1); + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: SerialTaskDispatch + * Function: SerialTaskDispatch + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: Verify if new SerialTaskDispatch with the valid params will return default value. + */ +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_ConstructorTest_001"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::DEFAULT; + + { + std::shared_ptr dispatcher = + std::make_shared(name, priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), name); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_ConstructorTest_002, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_ConstructorTest_002"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::LOW; + + { + std::shared_ptr dispatcher = + std::make_shared(name, priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), name); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_ConstructorTest_003, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_ConstructorTest_003"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + + { + std::shared_ptr dispatcher = + std::make_shared(name, priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), name); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_ConstructorTest_004, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_ConstructorTest_004"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + + { + std::shared_ptr dispatcher = + std::make_shared("", priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), "Dispatcher-0"); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + + { + std::shared_ptr dispatcher = + std::make_shared("", priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), "Dispatcher-1"); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_ConstructorTest_005, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_ConstructorTest_005"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + + { + std::shared_ptr dispatcher = + std::make_shared("", priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), "Dispatcher-2"); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + { + std::shared_ptr dispatcher = + std::make_shared("", priority, executor); + EXPECT_EQ(dispatcher->GetDispatcherName(), "Dispatcher-3"); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: SerialTaskDispatch + * Function: GetWorkingTasksSize + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify working task size changes + */ +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_GetWorkingTasksSizeTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_GetWorkingTasksSizeTest_001"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), std::string("Dispatcher-4")); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + + dispatcher->AsyncDispatch(std::make_shared([]() { + long wait = 2000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_GetWorkingTasksSizeTest_001 task0 end "; + })); + dispatcher->AsyncDispatch(std::make_shared([]() { + long wait = 4000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_GetWorkingTasksSizeTest_001 task1 end "; + })); + { + long wait = 500; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 2 - 1); + } + { + long wait = 2000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 1 - 1); + } + { + long wait = 2000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + long wait = 5000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_GetWorkingTasksSizeTest_002, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_GetWorkingTasksSizeTest_002"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + EXPECT_EQ(dispatcher->GetDispatcherName(), std::string("Dispatcher-5")); + EXPECT_EQ(dispatcher->GetPriority(), priority); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + + int times = 100; + for (int i = 0; i < times; i++) { + dispatcher->AsyncDispatch(std::make_shared([i]() { + long wait = 200 + i / 2; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_GetWorkingTasksSizeTest_002 task" + std::to_string(i) + "end"; + })); + } + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), times - 1); + } + { + long wait = 300 * (long)times; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: SerialTaskDispatch + * Function: SyncDispatch + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify synchronized task‘s executing sequence: serial. do wait task. + */ +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_SyncDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_SyncDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + int sleep1 = 2000; + dispatcher->SyncDispatch(std::make_shared([&count, sleep = sleep1]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_SyncDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + })); + EXPECT_TRUE(count.load() == 1); + + int sleep2 = 100; + dispatcher->SyncDispatch(std::make_shared([&count, sleep = sleep2]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_SyncDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + })); + EXPECT_TRUE(count.load() == 2); + + int sleep3 = 1000; + dispatcher->SyncDispatch(std::make_shared([&count, sleep = sleep3]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_SyncDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + })); + EXPECT_TRUE(count.load() == 3); + + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for " + std::to_string(wait)); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_SyncDispatchTest_002, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_SyncDispatchTest_002"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + ErrCode errCode = dispatcher->SyncDispatch(nullptr); + EXPECT_TRUE(errCode == ERR_APPEXECFWK_CHECK_FAILED); + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: SerialTaskDispatch + * Function: AsyncDispatch + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify asynchronized task‘s executing sequence: serial. donot wait task. + */ +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_AsyncDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_AsyncDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + int sleep1 = 2000; + dispatcher->AsyncDispatch(std::make_shared([&count, sleep = sleep1]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + })); + EXPECT_TRUE(count.load() == 0); + + int sleep2 = 1000; + dispatcher->AsyncDispatch(std::make_shared([&count, sleep = sleep2]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + })); + EXPECT_TRUE(count.load() == 0); + + int sleep3 = 1000; + dispatcher->AsyncDispatch(std::make_shared([&count, sleep = sleep3]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + })); + EXPECT_TRUE(count.load() == 0); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 0); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 1); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_AsyncDispatchTest_002, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_AsyncDispatchTest_002"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + std::shared_ptr revocable = dispatcher->AsyncDispatch(nullptr); + EXPECT_TRUE(revocable == nullptr); + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: SerialTaskDispatch + * Function: DelayDispatch + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify asynchronized task‘s executing sequence: delay, serial. donot wait task. + */ +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_DelayDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + std::atomic count(0); + int sleep1 = 2000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + }), + sleep1); + EXPECT_TRUE(count.load() == 0); + + int sleep2 = 1000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + }), + sleep2); + EXPECT_TRUE(count.load() == 0); + + int sleep3 = 1000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep3]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + }), + sleep3); + EXPECT_TRUE(count.load() == 0); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << ("wait for task, load= " + std::to_string(count.load())); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_002, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_DelayDispatchTest_002"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + int sleep1 = 2000; + dispatcher->DelayDispatch(nullptr, sleep1); + + GTEST_LOG_(INFO) << name + " end"; +} + +HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_003, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_DelayDispatchTest_003"); + GTEST_LOG_(INFO) << name + " start"; + auto config = std::make_shared(); + auto executor = std::make_shared(config); + auto priority = TaskPriority::HIGH; + std::shared_ptr dispatcher = std::make_shared("", priority, executor); + + std::atomic count(0); + int sleep1 = -2000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1 || index == 0); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_003 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + }), + sleep1); + + int sleep2 = -1000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_003 task" + std::to_string(index) + + " end, elapsed " + std::to_string(sleep); + }), + sleep2); + + { + long wait = 100; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + + GTEST_LOG_(INFO) << name + " end"; +} diff --git a/common/task_dispatcher/test/unittest/spec_dispatcher_config_test/BUILD.gn b/common/task_dispatcher/test/unittest/spec_dispatcher_config_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..44da57920080b6c72297ad21531b30d4bb4573c6 --- /dev/null +++ b/common/task_dispatcher/test/unittest/spec_dispatcher_config_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("SpecDispatcherConfigTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "spec_dispatcher_config_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":SpecDispatcherConfigTest" ] +} diff --git a/common/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test.cpp b/common/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0292695e797e092dd96a3aafdcf64ebaff7589b9 --- /dev/null +++ b/common/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#undef private +#include "spec_dispatcher_config.h" +#include +#include +#include +#include +#include "runnable.h" +#include "event_runner.h" +#include "default_worker_pool_config.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +using OHOS::AppExecFwk::DefaultWorkerPoolConfig; +using OHOS::AppExecFwk::TaskPriority; +using OHOS::AppExecFwk::WorkerPoolConfig; + +class SpecDispatcherConfigTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void SpecDispatcherConfigTest::SetUpTestCase() +{} + +void SpecDispatcherConfigTest::TearDownTestCase() +{} + +void SpecDispatcherConfigTest::SetUp() +{} + +void SpecDispatcherConfigTest::TearDown() +{} + +/** + * @tc.number:SpecDispatcherConfig_0100 + * @tc.name: SpecDispatcherConfig + * @tc.desc: 1.create SpecDispatcherConfig + * 2.GetName successfully + * * 3.GetPriority successfully + */ +HWTEST(SpecDispatcherConfigTest, SpecDispatcherConfig_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "SpecDispatcherConfig_0100 start"; + std::string dispatcherName = "SpecDispatcherConfig_0100"; + TaskPriority taskPriority = TaskPriority::DEFAULT; + std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); + EXPECT_EQ(config->GetName(), dispatcherName); + EXPECT_EQ(config->GetPriority(), TaskPriority::DEFAULT); + GTEST_LOG_(INFO) << "SpecDispatcherConfig_0100 end"; +} +/** + * @tc.number:GetPriority_0100 + * @tc.name: GetPriority + * @tc.desc: 1.create SpecDispatcherConfig + * * 2.GetPriority successfully + */ +HWTEST(SpecDispatcherConfigTest, GetPriority_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "SpecTaskDispatcher_0100 start"; + std::string dispatcherName = "GetPriority_0100"; + TaskPriority taskPriority = TaskPriority::DEFAULT; + std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); + EXPECT_EQ(config->GetPriority(), TaskPriority::DEFAULT); + GTEST_LOG_(INFO) << "GetPriority_0100 end"; +} +/** + * @tc.number:GetName_0100 + * @tc.name: GetName + * @tc.desc: 1.create SpecDispatcherConfig + * 2.GetName successfully + */ +HWTEST(SpecDispatcherConfigTest, GetName_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetName_0100 start"; + std::string dispatcherName = "GetName_0100"; + TaskPriority taskPriority = TaskPriority::DEFAULT; + std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); + EXPECT_EQ(config->GetName(), dispatcherName); + GTEST_LOG_(INFO) << "GetName_0100 end"; +} diff --git a/common/task_dispatcher/test/unittest/spec_task_dispatcher_test/BUILD.gn b/common/task_dispatcher/test/unittest/spec_task_dispatcher_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7928056c7702d4283759a14eb1dedc2186f70d4f --- /dev/null +++ b/common/task_dispatcher/test/unittest/spec_task_dispatcher_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("SpecTaskDispatcherTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "spec_task_dispatcher_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":SpecTaskDispatcherTest" ] +} diff --git a/common/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp b/common/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f55d58413f5d1b79e7ac96b533bbff668fc367a4 --- /dev/null +++ b/common/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp @@ -0,0 +1,349 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#undef private +#include "spec_task_dispatcher.h" + +#include "event_runner.h" +#include "runnable.h" +#include "serial_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_dispatcher_context.h" + +#include +#include +#include +#include + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +using OHOS::AppExecFwk::DefaultWorkerPoolConfig; +using OHOS::AppExecFwk::IteratableTask; +using OHOS::AppExecFwk::Revocable; +using OHOS::AppExecFwk::Runnable; +using OHOS::AppExecFwk ::SpecTaskDispatcher; +using OHOS::AppExecFwk::TaskDispatcherContext; +using OHOS::AppExecFwk::TaskExecutor; +using OHOS::AppExecFwk::TaskPriority; +using OHOS::AppExecFwk::WorkerPoolConfig; + +class SpecTaskDispatcherTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void SpecTaskDispatcherTest::SetUpTestCase() +{} + +void SpecTaskDispatcherTest::TearDownTestCase() +{} + +void SpecTaskDispatcherTest::SetUp() +{} + +void SpecTaskDispatcherTest::TearDown() +{} + +const std::string Prefix(const std::string &name) +{ + return std::string(">>> prefix :") + std::string(" ") + name + std::string(": "); +} + +std::shared_ptr CreateSpecTaskDispatcher() +{ + std::string dispatcherName = SpecDispatcherConfig::MAIN; + TaskPriority taskPriority = TaskPriority::HIGH; + std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); + std::shared_ptr runner = EventRunner::Create(true); + std::shared_ptr specTaskDispatcher = std::make_shared(config, runner); + GTEST_LOG_(INFO) << Prefix(dispatcherName) << " created"; + return specTaskDispatcher; +} + +/** + * @tc.number:SpecTaskDispatcher_0100 + * @tc.name: test SpecTaskDispatcher + * @tc.desc: 1.create SpecTaskDispatcher + * 2.GetPriority successfully + */ +HWTEST(SpecTaskDispatcherTest, SpecTaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "SpecTaskDispatcher_0100 start"; + std::shared_ptr ptr = CreateSpecTaskDispatcher(); + // same to func CreateSpecTaskDispatcher TaskPriority + EXPECT_EQ(ptr->GetPriority(), TaskPriority::HIGH); + GTEST_LOG_(INFO) << "SpecTaskDispatcher_0100 end"; +} + +/** + * @tc.number:SyncDispatch_0100 + * @tc.name: test SyncDispatch + * @tc.desc: 1.create SpecTaskDispatcher + * 2.SyncDispatch successfully + */ +HWTEST(SpecTaskDispatcherTest, SyncDispatch_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "SyncDispatch_0100 start"; + const std::string name("SyncDispatch_0100"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + std::shared_ptr ptr = CreateSpecTaskDispatcher(); + + // task runs synchronized + // use elapsed time to identify a task. + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + int sleep1 = 2000; + ptr->SyncDispatch(std::make_shared([&count, sleep = sleep1]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + })); + EXPECT_TRUE(count.load() == 1); + + int sleep2 = 100; + ptr->SyncDispatch(std::make_shared([&count, sleep = sleep2]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + })); + EXPECT_TRUE(count.load() == 2); + + int sleep3 = 1000; + ptr->SyncDispatch(std::make_shared([&count, sleep = sleep3]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + })); + EXPECT_TRUE(count.load() == 3); + + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for " + std::to_string(wait)); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + + GTEST_LOG_(INFO) << "SyncDispatch_0100 end"; +} +/** + * @tc.number:SyncDispatch_0200 + * @tc.name: test SyncDispatch + * @tc.desc: 1.create SpecTaskDispatcher + * 2.SyncDispatch Runnable is nullptr + */ +HWTEST(SpecTaskDispatcherTest, SyncDispatch_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "SyncDispatch_0200 start"; + const std::string name("SyncDispatch_0200"); + std::shared_ptr ptr = CreateSpecTaskDispatcher(); + ptr->SyncDispatch(nullptr); + GTEST_LOG_(INFO) << "SyncDispatch_0200 end"; +} +/** + * @tc.number:AsyncDispatch_0100 + * @tc.name: test AsyncDispatch + * @tc.desc: 1.create SpecTaskDispatcher + * 2.AsyncDispatch successfully + */ +HWTEST(SpecTaskDispatcherTest, AsyncDispatch_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AsyncDispatch_0100 start"; + const std::string name("AsyncDispatch_0100"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + std::shared_ptr ptr = CreateSpecTaskDispatcher(); + // init + // task runs synchronized + // use elapsed time to identify a task. + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + int sleep1 = 2000; + ptr->AsyncDispatch(std::make_shared([&count, sleep = sleep1]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + })); + EXPECT_TRUE(count.load() == 0); + + int sleep2 = 1000; + ptr->AsyncDispatch(std::make_shared([&count, sleep = sleep2]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + })); + EXPECT_TRUE(count.load() == 0); + + int sleep3 = 1000; + ptr->AsyncDispatch(std::make_shared([&count, sleep = sleep3]() { + auto time = std::chrono::milliseconds(sleep); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + })); + EXPECT_TRUE(count.load() == 0); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 0); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 1); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } + + GTEST_LOG_(INFO) << "AsyncDispatch_0100 end"; +} +/** + * @tc.number:AsyncDispatch_0200 + * @tc.name: test AsyncDispatch + * @tc.desc: 1.create SpecTaskDispatcher + * 2.AsyncDispatch Runnable is nullptr + */ +HWTEST(SpecTaskDispatcherTest, AsyncDispatch_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AsyncDispatch_0200 start"; + const std::string name("AsyncDispatch_0200"); + std::shared_ptr ptr = CreateSpecTaskDispatcher(); + ptr->AsyncDispatch(nullptr); + GTEST_LOG_(INFO) << "AsyncDispatch_0200 end"; +} +/** + * @tc.number:DelayDispatch_0100 + * @tc.name: test DelayDispatch + * @tc.desc: 1.create SpecTaskDispatcher + * 2.DelayDispatch successfully + */ +HWTEST(SpecTaskDispatcherTest, DelayDispatch_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "DelayDispatch_0100 start"; + const std::string name("DelayDispatch"); + GTEST_LOG_(INFO) << Prefix(name) << "begin thread " << std::this_thread::get_id(); + std::shared_ptr ptr = CreateSpecTaskDispatcher(); + + // task runs delayed + // use elapsed time to identify a task. + std::atomic count(0); + int sleep1 = 2000; + ptr->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { + // execute second + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + }), + sleep1); + EXPECT_TRUE(count.load() == 0); + + int sleep2 = 1000; + ptr->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { + // execute first + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + }), + sleep2); + EXPECT_TRUE(count.load() == 0); + + int sleep3 = 1000; + ptr->DelayDispatch(std::make_shared([&count, sleep = sleep3]() { + // execute first + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); + }), + sleep3); + EXPECT_TRUE(count.load() == 0); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } + GTEST_LOG_(INFO) << "DelayDispatch_0100 end"; +} + +/** + * @tc.number:DelayDispatch_0200 + * @tc.name: test DelayDispatch + * @tc.desc: 1.create SpecTaskDispatcher + * 2.DelayDispatch Runnable is nullptr + */ +HWTEST(SpecTaskDispatcherTest, DelayDispatch_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "DelayDispatch_0200 start"; + const std::string name("DelayDispatch_0200"); + std::shared_ptr ptr = CreateSpecTaskDispatcher(); + ptr->DelayDispatch(nullptr, 200); + GTEST_LOG_(INFO) << "DelayDispatch_0200 end"; +} \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/sync_task_test/BUILD.gn b/common/task_dispatcher/test/unittest/sync_task_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c72beab2a9ee1fb7dc9d32fdabc397bc44399686 --- /dev/null +++ b/common/task_dispatcher/test/unittest/sync_task_test/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("SyncTaskTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "sync_task_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + deps = [ ":SyncTaskTest" ] +} diff --git a/common/task_dispatcher/test/unittest/sync_task_test/sync_task_test.cpp b/common/task_dispatcher/test/unittest/sync_task_test/sync_task_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..655dfe37f5912ced64b676249bc8e29cf68e4842 --- /dev/null +++ b/common/task_dispatcher/test/unittest/sync_task_test/sync_task_test.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "sync_task.h" +#undef private +#include "app_log_wrapper.h" +#include "default_worker_pool_config.h" +#include "task.h" +#include "task_priority.h" +#include "task_executor.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class SyncTaskTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + void SetUp() + {} + void TearDown() + {} +}; + +/* + * Feature: SyncTask + * Function: SyncTask + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: Verify if new SyncTask with the valid params will return default value. + */ +HWTEST(SyncTaskTest, SyncTask_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("SyncTask_ConstructorTest_001"); + GTEST_LOG_(INFO) << name + " start"; + auto runnable = std::make_shared([]() { + long wait = 200; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + APP_LOGD("task %{public}d end", 0); + }); + auto priorityLow = TaskPriority::LOW; + auto priorityHigh = TaskPriority::HIGH; + + { + SyncTask task(runnable, priorityLow, nullptr); + EXPECT_EQ(task.GetPriority(), priorityLow); + } + { + SyncTask task(runnable, priorityHigh, nullptr); + EXPECT_EQ(task.GetPriority(), priorityHigh); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: SyncTask + * Function: Run + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify Run + */ +HWTEST(SyncTaskTest, SyncTask_RunTest_001, TestSize.Level0) +{ + auto name = std::string("SyncTask_RunTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto runnable = std::make_shared([&count]() { + long wait = 200; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + count++; + APP_LOGD("task %{public}d end", count.load()); + }); + auto priority = TaskPriority::DEFAULT; + { + SyncTask task(runnable, priority, nullptr); + // run task + Runnable taskRunner = std::bind(&SyncTask::Run, &task); + std::thread taskThread = std::thread(taskRunner); + + EXPECT_EQ(count.load(), 0); + taskThread.join(); + EXPECT_EQ(count.load(), 1); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: SyncTask + * Function: WaitTask + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify wait task complete + */ +HWTEST(SyncTaskTest, SyncTask_WaitTest_001, TestSize.Level0) +{ + auto name = std::string("SyncTask_WaitTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto runnable = std::make_shared([&count]() { + long wait = 1000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + count++; + APP_LOGD("task %{public}d end", count.load()); + }); + auto priority = TaskPriority::LOW; + { + SyncTask task(runnable, priority, nullptr); + // run task + std::thread taskThread = std::thread(std::bind(&SyncTask::Run, &task)); + std::thread taskWaitThread = std::thread(std::bind(&SyncTask::WaitTask, &task)); + + EXPECT_EQ(count.load(), 0); + taskThread.join(); + taskWaitThread.join(); + EXPECT_EQ(count.load(), 1); + } + + GTEST_LOG_(INFO) << name + " end"; +} diff --git a/common/task_dispatcher/test/unittest/task_dispatcher_context_test/BUILD.gn b/common/task_dispatcher/test/unittest/task_dispatcher_context_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9118bf33c6433e11f75d27810a9f7b18a921662f --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_dispatcher_context_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("TaskDispatcherContextTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "task_dispatcher_context_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":TaskDispatcherContextTest" ] +} diff --git a/common/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp b/common/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae5fd1d92be8fd4bfb13152584e2349d5d432130 --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "task_dispatcher_context.h" +#undef private +#include "default_worker_pool_config.h" +#include "task.h" +#include "task_priority.h" +#include "task_executor.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class TaskDispatcherContextTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void TaskDispatcherContextTest::SetUpTestCase() +{} + +void TaskDispatcherContextTest::TearDownTestCase() +{} + +void TaskDispatcherContextTest::SetUp() +{} + +void TaskDispatcherContextTest::TearDown() +{} + +/** + * @tc.number:TaskDispatcherContext_0100 + * @tc.name: createTaskDispatcherContext + * @tc.desc: 1.create default TaskDispatcherContext + * 2.GetWorkerPoolConfig successfully + */ +HWTEST(TaskDispatcherContextTest, TaskDispatcherContext_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "TaskDispatcherContext_0100 start"; + std::shared_ptr taskDispatcherContext = std::make_shared(); + std::shared_ptr config = taskDispatcherContext->GetWorkerPoolConfig(); + EXPECT_EQ(config.get()->GetMaxThreadCount(), 32); + GTEST_LOG_(INFO) << "TaskDispatcherContext_0100 end"; +} + +/** + * @tc.number:TaskDispatcherContext_0200 + * @tc.name: createTaskDispatcherContext + * @tc.desc: 1.create TaskDispatcherContext by TaskExecutor + * 2.GetWorkerThreadsInfo successfully + */ +HWTEST(TaskDispatcherContextTest, TaskDispatcherContext_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "TaskDispatcherContext_0200 start"; + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr testTaskExecutor = std::make_shared(config); + std::shared_ptr taskDispatcherContext = + std::make_shared(testTaskExecutor); + std::map workerThreadsInfo = taskDispatcherContext->GetWorkerThreadsInfo(); + bool flag = (workerThreadsInfo.size() == 0); + EXPECT_TRUE(flag); + GTEST_LOG_(INFO) << "TaskDispatcherContext_0200 end"; +} + +/** + * @tc.number:GetWorkerPoolConfig_0100 + * @tc.name: createTaskDispatcherContext + * @tc.desc: 1.create default TaskDispatcherContext + * 2.GetWorkerPoolConfig successfully + */ +HWTEST(TaskDispatcherContextTest, GetWorkerPoolConfig_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetWorkerPoolConfig_0100 start"; + std::shared_ptr taskDispatcherContext = std::make_shared(); + std::shared_ptr config = taskDispatcherContext->GetWorkerPoolConfig(); + EXPECT_EQ(config.get()->GetMaxThreadCount(), 32); + GTEST_LOG_(INFO) << "GetWorkerPoolConfig_0100 end"; +} +/** + * @tc.number:GetWorkerThreadsInfo_0100 + * @tc.name: GetWorkerThreadsInfo + * @tc.desc: 1.create TaskDispatcherContext by TaskExecutor,TaskExecutor is nullptr + * 2.GetWorkerThreadsInfo successfully + */ +HWTEST(TaskDispatcherContextTest, GetWorkerThreadsInfo_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetWorkerThreadsInfo_0100 start"; + const std::shared_ptr config = std::make_shared(); + std::shared_ptr taskDispatcherContext = std::make_shared(nullptr); + std::map workerThreadsInfo = taskDispatcherContext->GetWorkerThreadsInfo(); + bool flag = (workerThreadsInfo.size() == 0); + EXPECT_TRUE(flag); + GTEST_LOG_(INFO) << "GetWorkerThreadsInfo_0100 end"; +} +/** + * @tc.number:GetWorkerThreadsInfo_0200 + * @tc.name: GetWorkerThreadsInfo + * @tc.desc: 1.create TaskDispatcherContext by TaskExecutor + * 2.GetWorkerThreadsInfo successfully + */ +HWTEST(TaskDispatcherContextTest, GetWorkerThreadsInfo_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "TaskDispatcherContext_0200 start"; + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr testTaskExecutor = std::make_shared(config); + std::shared_ptr taskDispatcherContext = + std::make_shared(testTaskExecutor); + std::map workerThreadsInfo = taskDispatcherContext->GetWorkerThreadsInfo(); + bool flag = (workerThreadsInfo.size() == 0); + EXPECT_TRUE(flag); + GTEST_LOG_(INFO) << "TaskDispatcherContext_0200 end"; +} +/** + * @tc.number:CreateSerialDispatcher_0100 + * @tc.name: CreateSerialDispatcher + * @tc.desc: 1.CreateSerialDispatcher + * 2.GetSerialDispatchers successfully + */ +HWTEST(TaskDispatcherContextTest, CreateSerialDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CreateSerialDispatcher_0100 start"; + + std::shared_ptr taskDispatcherContext = std::make_shared(); + std::string dispatcherName = "test-serial-dispatcher"; + TaskPriority taskPriority = TaskPriority::DEFAULT; + std::shared_ptr ptrSerialTaskDispatcher = + taskDispatcherContext->CreateSerialDispatcher(dispatcherName, taskPriority); + EXPECT_EQ(ptrSerialTaskDispatcher->GetDispatcherName(), dispatcherName); + GTEST_LOG_(INFO) << "CreateSerialDispatcher_0100 end"; +} +/** + * @tc.number:GetSerialDispatchers_0100 + * @tc.name: GetSerialDispatchers + * @tc.desc: 1.CreateSerialDispatcher + * 2.GetSerialDispatchers successfully + */ +HWTEST(TaskDispatcherContextTest, GetSerialDispatchers_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetSerialDispatchers_0100 start"; + + std::shared_ptr taskDispatcherContext = std::make_shared(); + std::string dispatcherName = "test-serial-dispatcher"; + TaskPriority taskPriority = TaskPriority::DEFAULT; + std::shared_ptr ptrSerialTaskDispatcher = + taskDispatcherContext->CreateSerialDispatcher(dispatcherName, taskPriority); + + std::shared_ptr ptrSerialTaskDispatcherNew = + taskDispatcherContext->CreateSerialDispatcher(dispatcherName, taskPriority); + + std::map, std::string> serialDispatchers = + taskDispatcherContext->GetSerialDispatchers(); + bool flag = (serialDispatchers.size() == 2); + EXPECT_TRUE(flag); + std::map, std::string>::iterator iter; + for (iter = serialDispatchers.begin(); iter != serialDispatchers.end(); iter++) { + EXPECT_EQ(iter->second, dispatcherName); + } + GTEST_LOG_(INFO) << "GetSerialDispatchers_0100 end"; +} +/** + * @tc.number:CreateParallelDispatcher_0100 + * @tc.name: CreateParallelDispatcher + * @tc.desc: 1.CreateParallelDispatcher + * 2.GetPriority successfully + */ +HWTEST(TaskDispatcherContextTest, CreateParallelDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CreateParallelDispatcher_0100 start"; + std::shared_ptr taskDispatcherContext = std::make_shared(); + std::string dispatcherName = "test-parallel-dispatcher"; + TaskPriority taskPriority = TaskPriority::HIGH; + std::shared_ptr ptrSerialTaskDispatcher = + taskDispatcherContext->CreateParallelDispatcher(dispatcherName, taskPriority); + EXPECT_EQ(ptrSerialTaskDispatcher->GetPriority(), taskPriority); + GTEST_LOG_(INFO) << "CreateParallelDispatcher_0100 end"; +} + +/** + * @tc.number:GetGlobalTaskDispatcher_0100 + * @tc.name: GetGlobalTaskDispatcher + * @tc.desc: 1.GetGlobalTaskDispatcher + */ +HWTEST(TaskDispatcherContextTest, GetGlobalTaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetGlobalTaskDispatcher_0100 start"; + std::shared_ptr taskDispatcherContext = std::make_shared(); + TaskPriority taskPriority = TaskPriority::HIGH; + // case 1:GetGlobalTaskDispatcher dispatcher is null + std::shared_ptr ptr = taskDispatcherContext->GetGlobalTaskDispatcher(taskPriority); + GTEST_LOG_(INFO) << "GetGlobalTaskDispatcher_0100 end"; +} +/** + * @tc.number:GetGlobalTaskDispatcher_0200 + * @tc.name: GetGlobalTaskDispatcher + * @tc.desc: 1.GetGlobalTaskDispatcher + */ +HWTEST(TaskDispatcherContextTest, GetGlobalTaskDispatcher_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetGlobalTaskDispatcher_0200 start"; + std::shared_ptr taskDispatcherContext = std::make_shared(); + TaskPriority taskPriority = TaskPriority::HIGH; + // case 1:GetGlobalTaskDispatcher dispatcher is null + std::shared_ptr ptr = taskDispatcherContext->GetGlobalTaskDispatcher(taskPriority); + // case 2:GetGlobalTaskDispatcher dispatcher is not null + std::shared_ptr ptr1 = taskDispatcherContext->GetGlobalTaskDispatcher(taskPriority); + GTEST_LOG_(INFO) << "GetGlobalTaskDispatcher_0200 end"; +} +/** + * @tc.number:Shutdown_0100 + * @tc.name: Shutdown + * @tc.desc: 1.Shutdown + */ +HWTEST(TaskDispatcherContextTest, Shutdown_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Shutdown_0100 start"; + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr testTaskExecutor = std::make_shared(config); + testTaskExecutor->DelayExecute([]() { GTEST_LOG_(INFO) << "Shutdown_0100 delay execute task"; }, 10); + std::shared_ptr taskDispatcherContext = + std::make_shared(testTaskExecutor); + taskDispatcherContext->Shutdown(true); + GTEST_LOG_(INFO) << "Shutdown_0100 end"; +} + +/** + * @tc.number:GetWaitingTasksCount_0100 + * @tc.name: GetWaitingTasksCount + * @tc.desc: 1.create TaskDispatcherContext by TaskExecutor,TaskExecutor is nullptr + * 2.GetWaitingTasksCount eq 0 + */ +HWTEST(TaskDispatcherContextTest, GetWaitingTasksCount_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetWaitingTasksCount_0100 start"; + const std::shared_ptr testTaskExecutor = nullptr; + std::shared_ptr taskDispatcherContext = + std::make_shared(testTaskExecutor); + EXPECT_EQ(taskDispatcherContext->GetWaitingTasksCount(), 0); + GTEST_LOG_(INFO) << "GetWaitingTasksCount_0100 end"; +} + +/** + * @tc.number:GetWaitingTasksCount_0200 + * @tc.name: GetWaitingTasksCount + * @tc.desc: 1.create TaskDispatcherContext by TaskExecutor,TaskExecutor is not nullptr + * 2.GetWaitingTasksCount eq 0 + */ +HWTEST(TaskDispatcherContextTest, GetWaitingTasksCount_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetWaitingTasksCount_0200 start"; + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr testTaskExecutor = std::make_shared(config); + std::shared_ptr taskDispatcherContext = + std::make_shared(testTaskExecutor); + EXPECT_EQ(taskDispatcherContext->GetWaitingTasksCount(), 0); + GTEST_LOG_(INFO) << "GetWaitingTasksCount_0200 end"; +} +/** + * @tc.number:GetTaskCounter_0100 + * @tc.name: GetTaskCounter + * @tc.desc: 1.create TaskDispatcherContext by TaskExecutor + * 2.GetWaitingTasksCount eq 0 + */ +HWTEST(TaskDispatcherContextTest, GetTaskCounter_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetTaskCounter_0100 start"; + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr testTaskExecutor = std::make_shared(config); + std::shared_ptr taskDispatcherContext = + std::make_shared(testTaskExecutor); + EXPECT_EQ(taskDispatcherContext->GetTaskCounter(), 0); + GTEST_LOG_(INFO) << "GetTaskCounter_0100 end"; +} \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/task_executor_test/BUILD.gn b/common/task_dispatcher/test/unittest/task_executor_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..273b89ce87938e4de336ea787f662c84f1880d20 --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_executor_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("TaskExecutorTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "task_executor_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":TaskExecutorTest" ] +} diff --git a/common/task_dispatcher/test/unittest/task_executor_test/task_executor_test.cpp b/common/task_dispatcher/test/unittest/task_executor_test/task_executor_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47f70eb1da15cb8ee64e902efe525b2270147d5a --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_executor_test/task_executor_test.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "task_executor.h" +#include "default_worker_pool_config.h" +#include "worker_pool_config.h" +#include "default_thread_factory.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class TaskExecutorTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr CreateTaskExecutor(); +}; + +void TaskExecutorTest::SetUpTestCase(void) +{} + +void TaskExecutorTest::TearDownTestCase(void) +{} + +void TaskExecutorTest::SetUp(void) +{} + +void TaskExecutorTest::TearDown(void) +{} + +std::shared_ptr CreateTaskExecutor() +{ + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr testTaskExecutor = std::make_shared(config); + return testTaskExecutor; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_Constructor_0100 + * @tc.name: Constructor + * @tc.desc: Test whether constructor are called normally + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_Constructor_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Constructor_0100 start"; + const std::shared_ptr config = std::make_shared(); + std::make_shared(config); + + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Constructor_0100 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_Execute_0100 + * @tc.name: Execute + * @tc.desc: Test whether taskExecute are called normally, + * and verify whether the return value of getTaskCounter equal to 1 + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_Execute_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Execute_0100 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + Runnable TestTask([]() { GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Execute_0100 task"; }); + std::shared_ptr runnable = std::make_shared(TestTask); + std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, nullptr); + testTaskExecutor->Execute(task); + sleep(1); + long count = testTaskExecutor->GetTaskCounter(); + EXPECT_EQ(1, count); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Execute_0100 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_Execute_0200 + * @tc.name: Execute + * @tc.desc: Test whether taskExecute are called normally + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_Execute_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Execute_0200 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + std::atomic count(0); + Runnable TestTask([&count]() { + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Execute_0200 task "; + count++; + }); + std::shared_ptr runnable = std::make_shared(TestTask); + std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, nullptr); + for (int i = 0; i < 33; i++) { + testTaskExecutor->Execute(task); + } + sleep(1); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Execute_0200 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_DelayExecute_0100 + * @tc.name: DelayExecute + * @tc.desc: Test whether delayExecute and terminate are called normally + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_DelayExecute_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0100 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + testTaskExecutor->DelayExecute( + []() { GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0100 delay execute task001"; }, 3000); + testTaskExecutor->DelayExecute( + []() { GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0100 delay execute task002"; }, 1000); + sleep(1); + testTaskExecutor->Terminate(true); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0100 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_DelayExecute_0200 + * @tc.name: DelayExecute + * @tc.desc: Test whether delayExecute are called normally + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_DelayExecute_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0200 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + testTaskExecutor->DelayExecute( + []() { GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0200 delay execute task001"; }, 0); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0200 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_DelayExecute_0300 + * @tc.name: DelayExecute + * @tc.desc: Test whether delayExecute are called normally + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_DelayExecute_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0300 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + testTaskExecutor->Terminate(true); + sleep(1); + testTaskExecutor->DelayExecute( + []() { GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0300 delay execute task"; }, 1000); + + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DelayExecute_0300 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_Terminate_0100 + * @tc.name: Terminate + * @tc.desc: Test whether terminate are called normally + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_Terminate_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Terminate_0100 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + testTaskExecutor->Terminate(true); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_Terminate_0100 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_DoWorks_0100 + * @tc.name: DoWorks + * @tc.desc: Test the abnormal state of doWorks + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_DoWorks_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0100 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + Runnable TestTask([]() { GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0100 test task"; }); + std::shared_ptr runnable = std::make_shared(TestTask); + TaskPriority priority = TaskPriority::DEFAULT; + std::shared_ptr firstTask = std::make_shared(runnable, priority, nullptr); + const std::shared_ptr factory = std::make_shared(); + + std::shared_ptr worker = std::make_shared(testTaskExecutor, firstTask, factory); + testTaskExecutor->DoWorks(worker); + sleep(1); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0100 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_DoWorks_0200 + * @tc.name: DoWorks + * @tc.desc: Test the abnormal state of doWorks + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_DoWorks_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0200 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + testTaskExecutor->DoWorks(nullptr); + + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0200 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_DoWorks_0300 + * @tc.name: DoWorks + * @tc.desc: Test whether doWorks are called normally + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_DoWorks_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0300 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + + Runnable TestTask([]() { GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0300 test task"; }); + std::shared_ptr runnable = std::make_shared(TestTask); + TaskPriority priority = TaskPriority::DEFAULT; + std::shared_ptr firstTask = std::make_shared(runnable, priority, nullptr); + const std::shared_ptr factory = std::make_shared(); + std::shared_ptr worker = std::make_shared(testTaskExecutor, firstTask, factory); + std::thread doWorksThread([&]() { + worker->CreateThread(); // doWorks + }); + + doWorksThread.join(); + sleep(1); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_DoWorks_0300 end"; +} + +/** + * @tc.number: AppExecFwk_TaskExecutor_GetPendingTasksSize_0100 + * @tc.name: GetPendingTasksSize + * @tc.desc: Test whether the getPendingTasksSize return value equal to 0. + * + */ +HWTEST(TaskExecutorTest, AppExecFwk_TaskExecutor_GetPendingTasksSize_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_GetPendingTasksSize_0100 start"; + + const std::shared_ptr testTaskExecutor = CreateTaskExecutor(); + int size = testTaskExecutor->GetPendingTasksSize(); + EXPECT_EQ(0, size); + GTEST_LOG_(INFO) << "AppExecFwk_TaskExecutor_GetPendingTasksSize_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/task_handler_libevent_adapter_test/BUILD.gn b/common/task_dispatcher/test/unittest/task_handler_libevent_adapter_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..87822b593595622e395bd249aef824191a0ddf15 --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_handler_libevent_adapter_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("TaskHandlerLibeventAdapterTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "task_handler_libevent_adapter_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":TaskHandlerLibeventAdapterTest" ] +} diff --git a/common/task_dispatcher/test/unittest/task_handler_libevent_adapter_test/task_handler_libevent_adapter_test.cpp b/common/task_dispatcher/test/unittest/task_handler_libevent_adapter_test/task_handler_libevent_adapter_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5146ec09942eb1856e8231af5ecca4b6e3e5e922 --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_handler_libevent_adapter_test/task_handler_libevent_adapter_test.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#undef private +#include "task_handler_libevent_adapter.h" +#include +#include +#include +#include "runnable.h" +#include "event_runner.h" +#include "default_worker_pool_config.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +using OHOS::AppExecFwk::DefaultWorkerPoolConfig; +using OHOS::AppExecFwk::Revocable; +using OHOS::AppExecFwk::Runnable; +using OHOS::AppExecFwk::TaskPriority; +using OHOS::AppExecFwk::WorkerPoolConfig; + +class TaskHandlerLibeventAdapterTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void TaskHandlerLibeventAdapterTest::SetUpTestCase() +{} + +void TaskHandlerLibeventAdapterTest::TearDownTestCase() +{} + +void TaskHandlerLibeventAdapterTest::SetUp() +{} + +void TaskHandlerLibeventAdapterTest::TearDown() +{} +/** + * @tc.number:TaskHandlerLibeventAdapter_0100 + * @tc.name: TaskHandlerLibeventAdapter + * @tc.desc: 1.create TaskHandlerLibeventAdapter + * 2.Dispatch successfully + */ +HWTEST(TaskHandlerLibeventAdapterTest, TaskHandlerLibeventAdapter_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "TaskHandlerLibeventAdapter_0100 start"; + std::shared_ptr runner = EventRunner::Create(true); + std::shared_ptr handler = std::make_shared(runner); + handler->Dispatch( + std::make_shared([&]() { GTEST_LOG_(INFO) << "TaskHandlerLibeventAdapter_0100 is run"; })); + GTEST_LOG_(INFO) << "TaskHandlerLibeventAdapter_0100 end"; +} +/** + * @tc.number:Dispatch_0100 + * @tc.name: Dispatch + * @tc.desc: 1.create TaskHandlerLibeventAdapter + * 2.Dispatch successfully + */ +HWTEST(TaskHandlerLibeventAdapterTest, Dispatch_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Dispatch_0100 start"; + std::shared_ptr runner = EventRunner::Create(true); + std::shared_ptr handler = std::make_shared(runner); + handler->Dispatch(std::make_shared([&]() { GTEST_LOG_(INFO) << "Dispatch_0100 is run"; })); + GTEST_LOG_(INFO) << "Dispatch_0100 end"; +} +/** + * @tc.number:Dispatch_0200 + * @tc.name: Dispatch + * @tc.desc: 1.create TaskHandlerLibeventAdapter + * 2.Dispatch have delay successfully + */ +HWTEST(TaskHandlerLibeventAdapterTest, Dispatch_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Dispatch_0200 start"; + std::shared_ptr runner = EventRunner::Create(true); + std::shared_ptr handler = std::make_shared(runner); + handler->Dispatch(std::make_shared([&]() { GTEST_LOG_(INFO) << "Dispatch_0200 is run"; }), 300); + GTEST_LOG_(INFO) << "Dispatch_0200 end"; +} \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/task_test/BUILD.gn b/common/task_dispatcher/test/unittest/task_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3cc8ee274b335b1aba9ee801c728ac725331e9fb --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("TaskTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "task_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":TaskTest" ] +} diff --git a/common/task_dispatcher/test/unittest/task_test/task_test.cpp b/common/task_dispatcher/test/unittest/task_test/task_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fa06c0642c2614a5f29d6594d726a39f8c05474 --- /dev/null +++ b/common/task_dispatcher/test/unittest/task_test/task_test.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "task.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class MyTaskListener : public TaskListener { +public: + void OnChanged(const TaskStage &stage) + { + stage_ = stage.GetIndex(); + } + int stage_; +}; + +class TaskTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr CreateTask(std::string &runStr, TaskPriority priority); +}; + +void TaskTest::SetUpTestCase(void) +{} + +void TaskTest::TearDownTestCase(void) +{} + +void TaskTest::SetUp(void) +{} + +void TaskTest::TearDown(void) +{} + +std::shared_ptr CreateTask(std::string &runStr, TaskPriority priority) +{ + std::shared_ptr runnable = std::make_shared([&]() { GTEST_LOG_(INFO) << runStr; }); + std::shared_ptr task = std::make_shared(runnable, priority, nullptr); + return task; +}; + +/** + * @tc.number: AppExecFwk_Task_ConstructorTest_001 + * @tc.name: TaskConstructor + * @tc.desc: Test Task Constructor. + */ +HWTEST(TaskTest, AppExecFwk_Task_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_ConstructorTest_001"); + GTEST_LOG_(INFO) << name << " start"; + + std::string highTaskRun = "Task_Run: HIGH Task"; + TaskPriority highPriority = TaskPriority::HIGH; + std::shared_ptr highTask = CreateTask(highTaskRun, highPriority); + EXPECT_TRUE((highTask != nullptr)); + EXPECT_EQ(highPriority, highTask->GetPriority()); + highTask->Run(); + + std::string defaultTaskRun = "Task_Run: DEFAULT Task"; + TaskPriority defaultPriority = TaskPriority::DEFAULT; + std::shared_ptr defaultTask = CreateTask(defaultTaskRun, defaultPriority); + EXPECT_TRUE((defaultTask != nullptr)); + EXPECT_EQ(defaultPriority, defaultTask->GetPriority()); + defaultTask->Run(); + + std::string lowTaskRun = "Task_Run: DEFAULT Task"; + TaskPriority lowPriority = TaskPriority::LOW; + std::shared_ptr lowTask = CreateTask(lowTaskRun, lowPriority); + EXPECT_TRUE((lowTask != nullptr)); + EXPECT_EQ(lowPriority, lowTask->GetPriority()); + lowTask->Run(); + + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_Run_001 + * @tc.name: Run + * @tc.desc: Test task executor Runnable + */ +HWTEST(TaskTest, AppExecFwk_Task_Run_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_Run_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: task run"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + task->Run(); + EXPECT_FALSE(task->Revoke()); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_Sequence_001 + * @tc.name: GetSequence,SetSequence + * @tc.desc: Test get sequence and set sequence + */ +HWTEST(TaskTest, AppExecFwk_Task_Sequence_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_Sequence_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: Task_Sequence"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + long sequence = 10; + task->SetSequence(sequence); + EXPECT_EQ(10, task->GetSequence()); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_GetPriority_001 + * @tc.name: GetPriority + * @tc.desc: Test get priority + */ +HWTEST(TaskTest, AppExecFwk_Task_GetPriority_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_GetPriority_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: GetPriority DEFAULT Task"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::LOW); + EXPECT_EQ(TaskPriority::LOW, task->GetPriority()); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_Revoke_001 + * @tc.name: Revoke + * @tc.desc: Test task revoke true + */ +HWTEST(TaskTest, AppExecFwk_Task_Revoke_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_Revoke_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: Revoke Task"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + EXPECT_TRUE(task->Revoke()); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_Revoke_002 + * @tc.name: Revoke + * @tc.desc: Test task revoke false + */ +HWTEST(TaskTest, AppExecFwk_Task_Revoke_002, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_Revoke_002"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: Revoke Task"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + task->Run(); + EXPECT_FALSE(task->Revoke()); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_AddTaskListener_001 + * @tc.name: AddTaskListener + * @tc.desc: Test task add task listener + */ +HWTEST(TaskTest, AppExecFwk_Task_AddTaskListener_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_AddTaskListener_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: AddTaskListener"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + std::shared_ptr taskListener1 = std::make_shared(); + task->AddTaskListener(taskListener1); + std::shared_ptr taskListener2 = std::make_shared(); + task->AddTaskListener(taskListener2); + task->AfterTaskExecute(); + EXPECT_EQ(taskListener1->stage_, 0); + EXPECT_EQ(taskListener2->stage_, 0); + task->Run(); + task->AfterTaskExecute(); + EXPECT_EQ(taskListener1->stage_, 1); + EXPECT_EQ(taskListener2->stage_, 1); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_BeforeTaskExecute_001 + * @tc.name: BeforeTaskExecute + * @tc.desc: Test task before task execute + */ +HWTEST(TaskTest, AppExecFwk_Task_BeforeTaskExecute_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_BeforeTaskExecute_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: BeforeTaskExecute"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + std::shared_ptr taskListener = std::make_shared(); + task->AddTaskListener(taskListener); + task->BeforeTaskExecute(); + EXPECT_EQ(taskListener->stage_, TaskStage::BEFORE_EXECUTE); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_AfterTaskExecute_001 + * @tc.name: AfterTaskExecute + * @tc.desc: Test after task execute + */ +HWTEST(TaskTest, AppExecFwk_Task_AfterTaskExecute_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_AfterTaskExecute_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: AfterTaskExecute"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + std::shared_ptr taskListener = std::make_shared(); + task->AddTaskListener(taskListener); + task->AfterTaskExecute(); + EXPECT_EQ(taskListener->stage_, 0); + task->Run(); + task->AfterTaskExecute(); + EXPECT_EQ(taskListener->stage_, 1); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: AppExecFwk_Task_OnTaskCanceled_001 + * @tc.name: OnTaskCanceled + * @tc.desc: Test task canceled + */ +HWTEST(TaskTest, AppExecFwk_Task_OnTaskCanceled_001, TestSize.Level0) +{ + auto name = std::string("AppExecFwk_Task_OnTaskCanceled_001"); + GTEST_LOG_(INFO) << name << " start"; + std::string taskRun = "Task_Run: OnTaskCanceled"; + std::shared_ptr task = CreateTask(taskRun, TaskPriority::DEFAULT); + std::shared_ptr taskListener = std::make_shared(); + task->AddTaskListener(taskListener); + task->OnTaskCanceled(); + EXPECT_EQ(taskListener->stage_, 2); + GTEST_LOG_(INFO) << name << " end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/task_dispatcher/test/unittest/work_thread_test/BUILD.gn b/common/task_dispatcher/test/unittest/work_thread_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e6b418d78012cccb4ede624d434d9df5c7fac9c5 --- /dev/null +++ b/common/task_dispatcher/test/unittest/work_thread_test/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("WorkerThreadTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "work_thread_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + deps = [ ":WorkerThreadTest" ] +} diff --git a/common/task_dispatcher/test/unittest/work_thread_test/work_thread_test.cpp b/common/task_dispatcher/test/unittest/work_thread_test/work_thread_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7450520a33e5caec5c1a271519e8e00d883bca6 --- /dev/null +++ b/common/task_dispatcher/test/unittest/work_thread_test/work_thread_test.cpp @@ -0,0 +1,366 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 +#define private public +#include "work_thread.h" +#undef private +#include "app_log_wrapper.h" +#include "default_thread_factory.h" +#include "default_worker_pool_config.h" +#include "task_priority.h" +#include "task_executor.h" +#include "task.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class WorkerThreadTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + void SetUp() + {} + void TearDown() + {} +}; + +/* + * Feature: WorkerThread + * Function: SyncTask + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: Verify if new SyncTask with the valid params will return default value. + */ +HWTEST(WorkerThreadTest, WorkerThread_ConstructorTest_001, TestSize.Level0) +{ + auto name = std::string("WorkerThread_ConstructorTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto factory = std::make_shared(); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + EXPECT_EQ(thread->GetTaskCounter(), 0); + EXPECT_EQ(thread->GetThreadName(), ""); + } + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + EXPECT_EQ(thread->GetTaskCounter(), 0); + EXPECT_EQ(thread->GetThreadName(), ""); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: WorkerThread + * Function: CreateThread + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify create thread object + */ +HWTEST(WorkerThreadTest, WorkerThread_CreateThreadTest_001, TestSize.Level0) +{ + auto name = std::string("WorkerThread_CreateThreadTest_001"); + GTEST_LOG_(INFO) << name + " start"; + auto factory = std::make_shared(); + std::atomic count(0); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_EQ(thread->GetTaskCounter(), 1); + EXPECT_EQ(thread->GetThreadName(), std::string("PoolThread-1")); + EXPECT_TRUE(thread->GetThread() != nullptr); + } + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_EQ(thread->GetTaskCounter(), 1); + EXPECT_EQ(thread->GetThreadName(), std::string("PoolThread-2")); + EXPECT_TRUE(thread->GetThread() != nullptr); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: WorkerThread + * Function: IncTaskCount + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify task count increcement + */ +HWTEST(WorkerThreadTest, WorkerThread_IncTaskCountTest_001, TestSize.Level0) +{ + auto name = std::string("WorkerThread_IncTaskCountTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto factory = std::make_shared(); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + EXPECT_EQ(thread->GetTaskCounter(), 0); + thread->IncTaskCount(); + EXPECT_EQ(thread->GetTaskCounter(), 1); + thread->IncTaskCount(); + EXPECT_EQ(thread->GetTaskCounter(), 2); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: WorkerThread + * Function: GetTaskCounter + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify task count + */ +HWTEST(WorkerThreadTest, WorkerThread_GetTaskCounterTest_001, TestSize.Level0) +{ + auto name = std::string("WorkerThread_GetTaskCounterTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto factory = std::make_shared(); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + EXPECT_EQ(thread->GetTaskCounter(), 0); + thread->IncTaskCount(); + EXPECT_EQ(thread->GetTaskCounter(), 1); + thread->IncTaskCount(); + EXPECT_EQ(thread->GetTaskCounter(), 2); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: WorkerThread + * Function: GetThreadName + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify thread name + */ +HWTEST(WorkerThreadTest, WorkerThread_GetThreadNameTest_001, TestSize.Level0) +{ + auto name = std::string("WorkerThread_GetThreadNameTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto factory = std::make_shared(); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_EQ(thread->GetThreadName(), std::string("PoolThread-1")); + } + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_EQ(thread->GetThreadName(), std::string("PoolThread-2")); + } + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_EQ(thread->GetThreadName(), std::string("PoolThread-3")); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(WorkerThreadTest, WorkerThread_GetThreadNameTest_002, TestSize.Level0) +{ + auto name = std::string("WorkerThread_GetThreadNameTest_002"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto factory = std::make_shared(); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + EXPECT_EQ(thread->GetThreadName(), std::string("")); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: WorkerThread + * Function: PollFirstTask + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify thread name + */ +HWTEST(WorkerThreadTest, WorkerThread_PollFirstTaskTest_001, TestSize.Level0) +{ + auto name = std::string("WorkerThread_PollFirstTaskTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto factory = std::make_shared(); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_EQ(thread->PollFirstTask(), nullptr); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(WorkerThreadTest, WorkerThread_PollFirstTaskTest_002, TestSize.Level0) +{ + auto name = std::string("WorkerThread_PollFirstTaskTest_002"); + GTEST_LOG_(INFO) << name + " start"; + auto factory = std::make_shared(); + auto firstTask = nullptr; + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_EQ(thread->PollFirstTask(), firstTask); + } + + GTEST_LOG_(INFO) << name + " end"; +} + +/* + * Feature: WorkerThread + * Function: GetThread + * SubFunction: + * FunctionPoints: + * EnvConditions: + * CaseDescription: verify thread name + */ +HWTEST(WorkerThreadTest, WorkerThread_GetThread_001, TestSize.Level0) +{ + auto name = std::string("WorkerThread_GetThread_001"); + GTEST_LOG_(INFO) << name + " start"; + std::atomic count(0); + auto factory = std::make_shared(); + auto taskRunner = std::make_shared([&count, &name]() { + count++; + GTEST_LOG_(INFO) << name + "task end"; + }); + auto priority = TaskPriority::DEFAULT; + auto firstTask = std::make_shared(taskRunner, priority, nullptr); + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + thread->CreateThread(); + sleep(1); + EXPECT_TRUE(thread->GetThread() != nullptr); + } + + GTEST_LOG_(INFO) << name + " end"; +} +HWTEST(WorkerThreadTest, WorkerThread_GetThread_002, TestSize.Level0) +{ + auto name = std::string("WorkerThread_GetThread_002"); + GTEST_LOG_(INFO) << name + " start"; + auto factory = std::make_shared(); + auto firstTask = nullptr; + + auto config = std::make_shared(); + auto delegate = std::make_shared(config); + + { + std::shared_ptr thread = std::make_shared(delegate, firstTask, factory); + EXPECT_EQ(thread->GetThread(), nullptr); + } + + GTEST_LOG_(INFO) << name + " end"; +} diff --git a/common/task_dispatcher/test/unittest/worker_pool_test/BUILD.gn b/common/task_dispatcher/test/unittest/worker_pool_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0bd65420cf03611f251e3f95657b67b5e9761529 --- /dev/null +++ b/common/task_dispatcher/test/unittest/worker_pool_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("WorkerPoolTest") { + module_out_path = "ability_runtime/dispatcher_test" + + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + + sources += [ "worker_pool_test.cpp" ] + + configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":WorkerPoolTest" ] +} diff --git a/common/task_dispatcher/test/unittest/worker_pool_test/worker_pool_test.cpp b/common/task_dispatcher/test/unittest/worker_pool_test/worker_pool_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..594fcb73c9407ba2bb515ff26f4ef686b3cdc0fc --- /dev/null +++ b/common/task_dispatcher/test/unittest/worker_pool_test/worker_pool_test.cpp @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "worker_pool.h" +#include "default_worker_pool_config.h" +#include "worker_pool_config.h" +#include "work_thread.h" +#include "delay_execute_service.h" +#include "task.h" +#include "runnable.h" +#include "task_executor.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class WorkerPoolTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr createWorkerPool(); +}; + +void WorkerPoolTest::SetUpTestCase(void) +{} + +void WorkerPoolTest::TearDownTestCase(void) +{} + +void WorkerPoolTest::SetUp(void) +{} + +void WorkerPoolTest::TearDown(void) +{} + +std::shared_ptr createWorkerPool() +{ + const std::shared_ptr config = std::make_shared(); + std::shared_ptr testWorkerPool = std::make_shared(config); + return testWorkerPool; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_Constructor_0100 + * @tc.name: Constructor + * @tc.desc: Test whether constructor are called normally + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_Constructor_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_Constructor_0100 start"; + const std::shared_ptr config = std::make_shared(); + std::make_shared(config); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_Constructor_0100 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_AddWorker_0100 + * @tc.name: AddWorker + * @tc.desc: Test whether the addWorker return value is true. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_AddWorker_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0100 start"; + Runnable TestTask([]() { GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0100 task is running"; }); + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr delegate = std::make_shared(config); + const std::shared_ptr func = std::make_shared(TestTask); + const std::shared_ptr task = std::make_shared(func, TaskPriority::DEFAULT, nullptr); + std::shared_ptr testWorkerPool = createWorkerPool(); + bool addWorker = testWorkerPool->AddWorker(delegate, task); + sleep(1); + EXPECT_EQ(true, addWorker); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0100 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_AddWorker_0200 + * @tc.name: AddWorker + * @tc.desc: Test whether the addWorker return value is false. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_AddWorker_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0200 start"; + Runnable TestTask([]() { GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0200 task is running"; }); + const std::shared_ptr delegate = nullptr; + const std::shared_ptr func = std::make_shared(TestTask); + const std::shared_ptr task = std::make_shared(func, TaskPriority::DEFAULT, nullptr); + std::shared_ptr testWorkerPool = createWorkerPool(); + bool addWorker = testWorkerPool->AddWorker(delegate, task); + EXPECT_EQ(false, addWorker); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0200 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_AddWorker_0300 + * @tc.name: AddWorker + * @tc.desc: Test whether the addWorker return value is false. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_AddWorker_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0300 start"; + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr delegate = std::make_shared(config); + const std::shared_ptr task = nullptr; + std::shared_ptr testWorkerPool = createWorkerPool(); + bool addWorker = testWorkerPool->AddWorker(delegate, task); + EXPECT_EQ(false, addWorker); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_AddWorker_0300 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_GetKeepAliveTime_0100 + * @tc.name: GetKeepAliveTime + * @tc.desc: Test whether the getKeepAliveTime return value equal to 50. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_GetKeepAliveTime_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetKeepAliveTime_0100 start"; + std::shared_ptr testWorkerPool = createWorkerPool(); + long keepAliveTime = testWorkerPool->GetKeepAliveTime(); + EXPECT_EQ(50, keepAliveTime); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetKeepAliveTime_0100 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_GetCoreThreadCount_0100 + * @tc.name: GetCoreThreadCount + * @tc.desc: Test whether the getCoreThreadCount return value equal to 16. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_GetCoreThreadCount_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetCoreThreadCount_0100 start"; + std::shared_ptr testWorkerPool = createWorkerPool(); + int coreThreadCount = testWorkerPool->GetCoreThreadCount(); + EXPECT_EQ(16, coreThreadCount); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetCoreThreadCount_0100 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_GetMaxThreadCount_0100 + * @tc.name: GetMaxThreadCount + * @tc.desc: Test whether the getMaxThreadCount return value equal to 32. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_GetMaxThreadCount_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetMaxThreadCount_0100 start"; + std::shared_ptr testWorkerPool = createWorkerPool(); + int maxThreadCount = testWorkerPool->GetMaxThreadCount(); + EXPECT_EQ(32, maxThreadCount); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetMaxThreadCount_0100 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_GetWorkCount_0100 + * @tc.name: GetWorkCount + * @tc.desc: Test whether the getWorkCount return value equal to 1. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_GetWorkCount_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetWorkCount_0100 start"; + Runnable TestTask([]() { GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetWorkCount_0100 task is running"; }); + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr delegate = std::make_shared(config); + const std::shared_ptr func = std::make_shared(TestTask); + const std::shared_ptr task = std::make_shared(func, TaskPriority::DEFAULT, nullptr); + std::shared_ptr testWorkerPool = createWorkerPool(); + testWorkerPool->AddWorker(delegate, task); + sleep(1); + int workCount = testWorkerPool->GetWorkCount(); + EXPECT_EQ(1, workCount); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetWorkCount_0100 end"; +} + +/** + * @tc.number: AppExecFwk_WorkerPool_GetWorkerThreadsInfo_0100 + * @tc.name: GetWorkerThreadsInfo + * @tc.desc: Test whether the getWorkerThreadsInfo return value equal to 1. + */ +HWTEST(WorkerPoolTest, AppExecFwk_WorkerPool_GetWorkerThreadsInfo_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetWorkerThreadsInfo_0100 start"; + Runnable TestTask([]() { GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetWorkerThreadsInfo_0100 task is running"; }); + const std::shared_ptr config = std::make_shared(); + const std::shared_ptr delegate = std::make_shared(config); + const std::shared_ptr func = std::make_shared(TestTask); + const std::shared_ptr task = std::make_shared(func, TaskPriority::DEFAULT, nullptr); + std::shared_ptr testWorkerPool = createWorkerPool(); + testWorkerPool->AddWorker(delegate, task); + sleep(1); + std::map workerThreadsInfoMap = testWorkerPool->GetWorkerThreadsInfo(); + int size = workerThreadsInfoMap.size(); + EXPECT_EQ(1, size); + + GTEST_LOG_(INFO) << "AppExecFwk_WorkerPool_GetWorkerThreadsInfo_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/common/test/BUILD.gn b/common/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c2f769c0c60c3033a983ca019b8af09141455fc2 --- /dev/null +++ b/common/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +group("moduletest") { + testonly = true + + deps = [ "moduletest/task_dispatcher:moduletest" ] +} diff --git a/common/test/moduletest/task_dispatcher/BUILD.gn b/common/test/moduletest/task_dispatcher/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..67aa37956107b1ea9415e47517c56b28ecd8edb2 --- /dev/null +++ b/common/test/moduletest/task_dispatcher/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("dispatcher_mt_test_config") { + configs = [] + + defines = [] + + include_dirs = [ + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + + "${dispatcher_path}/include/dispatcher", + "${dispatcher_path}/include/threading", + "${dispatcher_path}/include/task", + + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + "${aafwk_path}/frameworks/kits/appkit/native/app/include/task", + ] +} + +group("moduletest") { + testonly = true + + deps = [ + "global_task_dispatcher_module_test:moduletest", + "parallel_task_dispatcher_module_test:moduletest", + "serial_task_dispatcher_module_test:moduletest", + "spec_task_dispatcher_module_test:moduletest", + ] +} diff --git a/common/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/BUILD.gn b/common/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..695f28d5ddf95f2374d119c2e58362f9ff597eb6 --- /dev/null +++ b/common/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +module_output_path = "ability_runtime/mt_dispatcher_test" + +ohos_moduletest("GlobalTaskDispatcherModuleTest") { + module_out_path = module_output_path + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + sources += [ "global_task_dispatcher_module_test.cpp" ] + configs = [ "${aafwk_path}/common/test/moduletest/task_dispatcher:dispatcher_mt_test_config" ] + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":GlobalTaskDispatcherModuleTest" ] +} diff --git a/common/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp b/common/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ceec0ac66218bb1bdcfb7e078ad4238ed272fba --- /dev/null +++ b/common/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function +#include + +#include "app_log_wrapper.h" +#include "base_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_dispatcher_context.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class GlobalTaskDispatcherModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr GetMtGlobalTaskDispatcher(TaskPriority priority) const; + std::shared_ptr context; +}; + +void GlobalTaskDispatcherModuleTest::SetUpTestCase() +{} + +void GlobalTaskDispatcherModuleTest::TearDownTestCase() +{} + +void GlobalTaskDispatcherModuleTest::SetUp() +{ + context = std::make_shared(); + printf("GlobalTaskDispatcherModuleTest::SetUp()\r\n"); +} + +void GlobalTaskDispatcherModuleTest::TearDown() +{ + printf("GlobalTaskDispatcherModuleTest::TearDown()\r\n"); + context = nullptr; + printf("GlobalTaskDispatcherModuleTest::TearDown() after \r\n"); +} + +std::shared_ptr GlobalTaskDispatcherModuleTest::GetMtGlobalTaskDispatcher(TaskPriority priority) const +{ + std::shared_ptr ptrGlobalTaskDispatcher = context->GetGlobalTaskDispatcher(priority); + return ptrGlobalTaskDispatcher; +} + +/** + * @tc.number: GetMtGlobalTaskDispatcherTest_001 + * @tc.name: GetGlobalTaskDispatcher + * @tc.desc: Test GlobalTaskDispatcher get GlobalTaskDispatcher. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GetMtGlobalTaskDispatcherTest_001, TestSize.Level1) +{ + auto name = std::string("GetMtGlobalTaskDispatcherTest_001"); + GTEST_LOG_(INFO) << name + " start"; + TaskPriority defaultPriority = TaskPriority::DEFAULT; + std::shared_ptr defaultPtr1 = GetMtGlobalTaskDispatcher(defaultPriority); + std::shared_ptr defaultPtr2 = GetMtGlobalTaskDispatcher(defaultPriority); + EXPECT_EQ(defaultPtr1.get(), defaultPtr2.get()); + std::shared_ptr lowPtr1 = GetMtGlobalTaskDispatcher(TaskPriority::LOW); + std::shared_ptr lowPtr2 = GetMtGlobalTaskDispatcher(TaskPriority::LOW); + EXPECT_NE(lowPtr1.get(), defaultPtr1.get()); + EXPECT_EQ(lowPtr1.get(), lowPtr2.get()); + std::shared_ptr highPtr1 = GetMtGlobalTaskDispatcher(TaskPriority::HIGH); + std::shared_ptr highPtr2 = GetMtGlobalTaskDispatcher(TaskPriority::HIGH); + EXPECT_NE(defaultPtr1.get(), highPtr1.get()); + EXPECT_NE(lowPtr1.get(), highPtr1.get()); + EXPECT_EQ(highPtr1.get(), highPtr2.get()); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: GlobalTaskDispatcher_SyncDispatchTest_001 + * @tc.name: SyncDispatch + * @tc.desc: Test GlobalTaskDispatcher sync dispatch. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GlobalTaskDispatcher_SyncDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("GlobalTaskDispatcher_SyncDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = GetMtGlobalTaskDispatcher(TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + long sleep1 = 200; + ptr->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " Runnable1"; + })); + EXPECT_TRUE(count.load() == 1); + long sleep2 = 100; + ptr->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " Runnable2"; + })); + EXPECT_TRUE(count.load() == 2); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: GlobalTaskDispatcher_AsyncDispatchTest_001 + * @tc.name: AsyncDispatch + * @tc.desc: Test GlobalTaskDispatcher async dispatch. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GlobalTaskDispatcher_AsyncDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("GlobalTaskDispatcher_AsyncDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = GetMtGlobalTaskDispatcher(TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + std::shared_ptr func = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Runnable1"; + }); + ptr->AsyncDispatch(func); + EXPECT_LT(count.load(), 1); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + EXPECT_EQ(count.load(), 1); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: GlobalTaskDispatcher_AsyncGroupDispatchTest_001 + * @tc.name: AsyncGroupDispatch + * @tc.desc: Test GlobalTaskDispatcher group. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GlobalTaskDispatcher_AsyncGroupDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("GlobalTaskDispatcher_AsyncGroupDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = GetMtGlobalTaskDispatcher(TaskPriority::DEFAULT); + // init + std::atomic count(0); + long sleep1 = 200; + std::shared_ptr group = ptr->CreateDispatchGroup(); + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1 : sleep1 time=" << sleep1; + })); + + long sleep2 = 100; + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1 : sleep2 time=" << sleep2; + })); + EXPECT_TRUE(count.load() < 2); + std::shared_ptr runnable = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + GTEST_LOG_(INFO) << name << " GroupDispatchNotify Runnable"; + }); + ptr->GroupDispatchNotify(group, runnable); + EXPECT_TRUE(ptr->GroupDispatchWait(group, 1000)); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + EXPECT_TRUE(count.load() == 3); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: GlobalTaskDispatcher_AsyncGroupDispatchTest_002 + * @tc.name: AsyncGroupDispatch + * @tc.desc: Test GlobalTaskDispatcher group. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GlobalTaskDispatcher_AsyncGroupDispatchTest_002, TestSize.Level1) +{ + auto name = std::string("GlobalTaskDispatcher_AsyncGroupDispatchTest_002"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = GetMtGlobalTaskDispatcher(TaskPriority::DEFAULT); + long sleep1 = 200; + std::shared_ptr group = ptr->CreateDispatchGroup(); + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1 : sleep1 time=" << sleep1; + })); + + long sleep2 = 100; + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1 : sleep2 time=" << sleep2; + })); + bool result = ptr->GroupDispatchWait(group, 10); + EXPECT_EQ(false, result); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: GlobalTaskDispatcher_ApplyDispatchTest_001 + * @tc.name: ApplyDispatch + * @tc.desc: Test GlobalTaskDispatcher apply dispatch. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GlobalTaskDispatcher_ApplyDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("GlobalTaskDispatcher_ApplyDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = GetMtGlobalTaskDispatcher(TaskPriority::DEFAULT); + std::atomic count(0); + const int repeatCount = 10; + long sleep1 = 200; + auto repeats1 = std::make_shared>([&](long index1) { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index >= repeatCount); + EXPECT_TRUE(index < repeatCount * 2); + GTEST_LOG_(INFO) << name + " repeats1"; + }); + ptr->ApplyDispatch(repeats1, repeatCount); + + const long sleep2 = 10; + auto repeats2 = std::make_shared>([&](long index1) { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index < repeatCount); + GTEST_LOG_(INFO) << name + " repeats2"; + }); + ptr->ApplyDispatch(repeats2, repeatCount); + + EXPECT_TRUE(count.load() < 20); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 20); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: GlobalTaskDispatcher_DelayDispatchTest_001 + * @tc.name: DelayDispatch + * @tc.desc: Test GlobalTaskDispatcher delay dispatch. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GlobalTaskDispatcher_DelayDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("GlobalTaskDispatcher_DelayDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = GetMtGlobalTaskDispatcher(TaskPriority::DEFAULT); + std::atomic count(0); + long sleep1 = 200; + ptr->DelayDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + // execute second + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " Runnable1"; + }), + sleep1); + + long sleep2 = 100; + ptr->DelayDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + // execute first + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " Runnable2"; + }), + sleep2); + EXPECT_TRUE(count.load() < 2); + long wait = 1000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: GlobalTaskDispatcher_SyncDispatchBarrierTest_001 + * @tc.name: AsyncDispatchBarrier + * @tc.desc: Test GlobalTaskDispatcher barrier. + */ +HWTEST_F(GlobalTaskDispatcherModuleTest, GlobalTaskDispatcher_SyncDispatchBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("GlobalTaskDispatcher_SyncDispatchBarrierTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = GetMtGlobalTaskDispatcher(TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + auto group = ptr->CreateDispatchGroup(); + long sleepG1 = 200; + ptr->AsyncGroupDispatch((group), std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG1); + std::this_thread::sleep_for(time); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "AsyncGroupDispatch Runnable"; + })); + ptr->SyncDispatchBarrier(std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "SyncDispatchBarrier Runnable"; + })); + ptr->SyncDispatch(std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "SyncDispatch Runnable"; + })); + long wait = sleepG1 + 1000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + GTEST_LOG_(INFO) << name << " end"; +} diff --git a/common/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/BUILD.gn b/common/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9796fb4748b96fe529762713a2cdb8771311c4ec --- /dev/null +++ b/common/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +module_output_path = "ability_runtime/mt_dispatcher_test" + +ohos_moduletest("ParallelTaskDispatcherModuleTest") { + module_out_path = module_output_path + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + sources += [ "parallel_task_dispatcher_module_test.cpp" ] + configs = [ "${aafwk_path}/common/test/moduletest/task_dispatcher:dispatcher_mt_test_config" ] + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":ParallelTaskDispatcherModuleTest" ] +} diff --git a/common/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/parallel_task_dispatcher_module_test.cpp b/common/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/parallel_task_dispatcher_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2724e7393b710068bcde8542427fe967ce8d86a6 --- /dev/null +++ b/common/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/parallel_task_dispatcher_module_test.cpp @@ -0,0 +1,395 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function + +#include +#include "app_log_wrapper.h" +#include "base_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_dispatcher_context.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class ParallelTaskDispatcherModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr CreateMtParallelTaskDispatcher(std::string &name, TaskPriority priority); + std::shared_ptr context; +}; + +void ParallelTaskDispatcherModuleTest::SetUpTestCase() +{} + +void ParallelTaskDispatcherModuleTest::TearDownTestCase() +{} + +void ParallelTaskDispatcherModuleTest::SetUp() +{ + context = std::make_shared(); +} + +void ParallelTaskDispatcherModuleTest::TearDown() +{ + context = nullptr; +} + +std::shared_ptr ParallelTaskDispatcherModuleTest::CreateMtParallelTaskDispatcher( + std::string &name, TaskPriority priority) +{ + return context->CreateParallelDispatcher(name, priority); +} + +/** + * @tc.number: ParallelTaskDispatcher_LifeCycleTest_001 + * @tc.name: Shutdown + * @tc.desc: Test ParallelTaskDispatcher task shutdown. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_LifeCycleTest_001, TestSize.Level1) +{ + auto name = std::string("ParallelTaskDispatcher_LifeCycleTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + std::shared_ptr runnable = std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " GroupDispatchNotify Runnable"; + }); + ptr->AsyncDispatch(runnable); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + context->Shutdown(true); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_CreateParallelDispatcherTest_001 + * @tc.name: CreateParallelDispatcher + * @tc.desc: Test ParallelTaskDispatcher create parallel dispatcher + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_CreateParallelDispatcherTest_001, TestSize.Level1) +{ + auto name = std::string("ParallelTaskDispatcher_CreateParallelDispatcherTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr1 = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::shared_ptr ptr2 = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + EXPECT_FALSE((ptr1.get() == ptr2.get())); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_SyncDispatchTest_001 + * @tc.name: SyncDispatch + * @tc.desc: Test ParallelTaskDispatcher sync dispatch. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_SyncDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("ParallelTaskDispatcher_SyncDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + long sleep1 = 200; + ptr->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " Runnable1"; + })); + EXPECT_TRUE(count.load() == 1); + long sleep2 = 100; + ptr->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " Runnable2"; + })); + EXPECT_TRUE(count.load() == 2); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_AsyncDispatchTest_001 + * @tc.name: AsyncDispatch + * @tc.desc: Test ParallelTaskDispatcher async dispatch. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_AsyncDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_AsyncDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_EQ(count.load(), 0); + std::shared_ptr func = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " Runnable1"; + }); + ptr->AsyncDispatch(func); + EXPECT_LT(count.load(), 1); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + EXPECT_EQ(count.load(), 1); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_AsyncGroupDispatchTest_001 + * @tc.name: AsyncGroup + * @tc.desc: Test ParallelTaskDispatcher group. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_AsyncGroupDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("ParallelTaskDispatcher_AsyncGroupDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + long sleep1 = 200; + std::shared_ptr group = ptr->CreateDispatchGroup(); + + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1 : sleep1 time=" << sleep1; + })); + + long sleep2 = 100; + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1 : sleep2 time=" << sleep2; + })); + std::shared_ptr runnable = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + GTEST_LOG_(INFO) << name << " GroupDispatchNotify Runnable"; + }); + ptr->GroupDispatchNotify(group, runnable); + EXPECT_TRUE(count.load() < 2); + EXPECT_TRUE(ptr->GroupDispatchWait(group, 1000)); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + EXPECT_TRUE(count.load() == 3); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_AsyncGroupDispatchTest_002 + * @tc.name: AsyncGroup + * @tc.desc: Test ParallelTaskDispatcher group. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_AsyncGroupDispatchTest_002, TestSize.Level1) +{ + auto name = std::string("ParallelTaskDispatcher_AsyncGroupDispatchTest_002"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::shared_ptr group = ptr->CreateDispatchGroup(); + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(200); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1"; + })); + + ptr->AsyncGroupDispatch(group, std::make_shared([&]() { + auto time = std::chrono::milliseconds(200); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name << " AsyncGroupDispatch1"; + })); + bool result = ptr->GroupDispatchWait(group, 10); + EXPECT_EQ(result, false); + auto time = std::chrono::milliseconds(600); + std::this_thread::sleep_for(time); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_ApplyDispatchTest_001 + * @tc.name: ApplyDispatch + * @tc.desc: Test ParallelTaskDispatcher apply dispatch. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_ApplyDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_ApplyDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + // init + std::atomic count(0); + const int repeatCount = 10; + long sleep1 = 200; + auto repeats1 = std::make_shared>([&](long index1) { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index >= repeatCount); + EXPECT_TRUE(index < repeatCount * 2); + GTEST_LOG_(INFO) << name + " repeats1"; + }); + ptr->ApplyDispatch(repeats1, repeatCount); + + const long sleep2 = 10; + auto repeats2 = std::make_shared>([&](long index1) { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index < repeatCount); + GTEST_LOG_(INFO) << name + " repeats2"; + }); + ptr->ApplyDispatch(repeats2, repeatCount); + + EXPECT_TRUE(count.load() < 20); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 20); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_DelayDispatchTest_001 + * @tc.name: DelayDispatch + * @tc.desc: Test ParallelTaskDispatcher delay dispatch. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_DelayDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_DelayDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + long sleep1 = 200; + ptr->DelayDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + // execute second + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " Runnable1"; + }), + sleep1); + + long sleep2 = 100; + ptr->DelayDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + // execute first + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " Runnable2"; + }), + sleep2); + EXPECT_TRUE(count.load() < 2); + long wait = 1000; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_AsyncDispatchBarrierTest_001 + * @tc.name: AsyncDispatchBarrier + * @tc.desc: Test ParallelTaskDispatcher barrier. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_AsyncDispatchBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_AsyncDispatchBarrierTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + auto group = ptr->CreateDispatchGroup(); + long sleepG1 = 200; + ptr->AsyncGroupDispatch((group), std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << "group Runnable1"; + })); + long sleepG2 = 100; + ptr->AsyncGroupDispatch((group), std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << "group Runnable2"; + })); + EXPECT_TRUE(count.load() == 0); + ptr->AsyncDispatchBarrier(std::make_shared([&]() { + EXPECT_TRUE(count.load() == 2); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "AsyncDispatchBarrier Runnable"; + })); + GTEST_LOG_(INFO) << name << "AsyncDispatchBarrier After"; + + auto time = std::chrono::milliseconds(1000); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: ParallelTaskDispatcher_SyncDispatchBarrierTest_001 + * @tc.name: SyncDispatchBarrier + * @tc.desc: Test ParallelTaskDispatcher sync barrier. + */ +HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_SyncDispatchBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("ParallelTaskDispatcher_SyncDispatchBarrierTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = CreateMtParallelTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + auto group = ptr->CreateDispatchGroup(); + long sleepG1 = 200; + ptr->AsyncGroupDispatch((group), std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << "group Runnable1"; + })); + long sleepG2 = 100; + ptr->AsyncGroupDispatch((group), std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " group Runnable2"; + })); + EXPECT_TRUE(count.load() == 0); + ptr->SyncDispatchBarrier(std::make_shared([&]() { + EXPECT_TRUE(count.load() == 2); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "SyncDispatchBarrier Runnable"; + })); + GTEST_LOG_(INFO) << name << "SyncDispatchBarrier After"; + + auto time = std::chrono::milliseconds(1000); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + GTEST_LOG_(INFO) << name << " end"; +} diff --git a/common/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/BUILD.gn b/common/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cb7313d728cc18da84e3cd3d4b405a7fd8fa8c98 --- /dev/null +++ b/common/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +module_output_path = "ability_runtime/mt_dispatcher_test" + +ohos_moduletest("SerialTaskDispatcherModuleTest") { + module_out_path = module_output_path + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + sources += [ "serial_task_dispatcher_module_test.cpp" ] + configs = [ "${aafwk_path}/common/test/moduletest/task_dispatcher:dispatcher_mt_test_config" ] + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":SerialTaskDispatcherModuleTest" ] +} diff --git a/common/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp b/common/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee540863f7bea3473a55fb9d1ed25d8b7618f0dd --- /dev/null +++ b/common/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp @@ -0,0 +1,459 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function +#define private public +#define protected public +#include "base_task_dispatcher.h" +#include "task_dispatcher_context.h" +#include "task_dispatcher.h" + +#undef private +#undef protected +#include +#include "app_log_wrapper.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class SerialTaskDispatcherModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr CreateMtSerialTaskDispatcher(std::string &name, TaskPriority priority); + std::shared_ptr context; +}; + +void SerialTaskDispatcherModuleTest::SetUpTestCase() +{} + +void SerialTaskDispatcherModuleTest::TearDownTestCase() +{} + +void SerialTaskDispatcherModuleTest::SetUp() +{ + context = std::make_shared(); +} + +void SerialTaskDispatcherModuleTest::TearDown() +{ + context = nullptr; +} + +std::shared_ptr SerialTaskDispatcherModuleTest::CreateMtSerialTaskDispatcher( + std::string &name, TaskPriority priority) +{ + std::shared_ptr ptrSerialTaskDispatcher = context->CreateSerialDispatcher(name, priority); + return ptrSerialTaskDispatcher; +} + +/** + * @tc.number: SerialTaskDispatcher_LifeCycleTest_001 + * @tc.name: Shutdown + * @tc.desc: Test SerialTaskDispatcher task shutdown. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_LifeCycleTest_001, TestSize.Level1) +{ + auto name = std::string("SerialTaskDispatcher_LifeCycleTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + std::shared_ptr runnable = std::make_shared([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " GroupDispatchNotify Runnable"; + }); + ptr->SyncDispatch(runnable); + context->Shutdown(true); + EXPECT_EQ(count.load(), 1); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_CreateSerialDispatcherTest_001 + * @tc.name: CreateSerialDispatcher + * @tc.desc: Test SerialTaskDispatcher create serial dispatcher. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_CreateSerialDispatcherTest_001, TestSize.Level1) +{ + auto name = std::string("SerialTaskDispatcher_CreateSerialDispatcherTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr1 = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::shared_ptr ptr2 = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + EXPECT_FALSE((ptr1.get() == ptr2.get())); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_SyncDispatchTest_001 + * @tc.name: SyncDispatch + * @tc.desc: Test SerialTaskDispatcher sync dispatch. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_SyncDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("SerialTaskDispatcher_SyncDispatch_002"); + GTEST_LOG_(INFO) << name << " start"; + + std::shared_ptr ptr = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + long sleep1 = 200; + ptr->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " SyncDispatch1 : sleep1 time=" << sleep1; + })); + EXPECT_TRUE(count.load() == 1); + + long sleep2 = 100; + ptr->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " SyncDispatch2 : sleep2 time=" << sleep2; + })); + EXPECT_TRUE(count.load() == 2); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_AsyncDispatchTest_001 + * @tc.name: AsyncDispatch + * @tc.desc: Test SerialTaskDispatcher async dispatch. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_AsyncDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("SerialTaskDispatcher_AsyncDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + long sleep1 = 200; + ptr->AsyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " AsyncDispatch1 : sleep2 time=" << sleep1; + })); + EXPECT_TRUE(count.load() < 1); + long sleep2 = 100; + ptr->AsyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " AsyncDispatch2 : sleep2 time=" << sleep2; + })); + EXPECT_TRUE(count.load() < 2); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_AsyncDispatchTest_002 + * @tc.name: AsyncDispatch + * @tc.desc: Test SerialTaskDispatcher async dispatch. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_AsyncDispatchTest_002, TestSize.Level1) +{ + auto name = std::string("SerialTaskDispatcher_AsyncDispatchTest_002"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + const int total = 300; + std::atomic count(0); + long wait = 100; + for (int i = 0; i < total; i++) { + ptr->AsyncDispatch(std::make_shared([&count, &name]() { + auto time = std::chrono::milliseconds(1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_002 task" + std::to_string(index) + "end"; + })); + wait += 10; + } + EXPECT_TRUE(count.load() < total); + auto time = std::chrono::milliseconds(wait + 1000); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == total); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_DelayDispatchTest_001 + * @tc.name: DelayDispatch + * @tc.desc: Test SerialTaskDispatcher delay dispatch. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_DelayDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_DelayDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr dispatcher = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + int sleep1 = 2000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep1); + EXPECT_TRUE(count.load() == 0); + + int sleep2 = 1000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep2); + EXPECT_TRUE(count.load() == 0); + + int sleep3 = 1000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep3]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep3); + EXPECT_TRUE(count.load() == 0); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_DelayDispatchTest_002 + * @tc.name: DelayDispatch + * @tc.desc: Test SerialTaskDispatcher delay dispatch. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_DelayDispatchTest_002, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_DelayDispatchTest_003"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr dispatcher = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + int sleep1 = 2000; + dispatcher->DelayDispatch(nullptr, sleep1); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_DelayDispatchTest_003 + * @tc.name: DelayDispatch + * @tc.desc: Test SerialTaskDispatcher delay dispatch. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_DelayDispatchTest_003, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_DelayDispatchTest_004"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr dispatcher = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + int sleep1 = -2000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1 || index == 0); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_004 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep1); + + int sleep2 = -1000; + dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_004 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep2); + { + long wait = 100; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_ApplyDispatchTest_001 + * @tc.name: ApplyDispatch + * @tc.desc: Test SerialTaskDispatcher applay dispatch. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_ApplyDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_ApplyDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + std::shared_ptr ptr = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + long sleep1 = 101; + auto repeats1 = std::make_shared>([&](long index) { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " repeats1 sleep1=" << sleep1; + }); + ptr->ApplyDispatch(repeats1, 10); + + long sleep2 = 100; + auto repeats2 = std::make_shared>([&](long index) { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " repeats2 sleep2=" << sleep2; + }); + ptr->ApplyDispatch(repeats2, 10); + + EXPECT_TRUE(count.load() < 20); + long wait = sleep1 * 10 + sleep2 * 10 + 100 + 100; + GTEST_LOG_(INFO) << name << " main wait time=" << wait; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 20); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_AsyncDispatchBarrierTest_001 + * @tc.name: AsyncDispatchBarrier + * @tc.desc: Test SerialTaskDispatcher barrier. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_AsyncDispatchBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_AsyncDispatchBarrierTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + auto group = ptr->CreateDispatchGroup(); + long sleepG1 = 200; + ptr->AsyncGroupDispatch((group), std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1 || index == 0); + GTEST_LOG_(INFO) << name << "group Runnable1"; + })); + long sleepG2 = 100; + ptr->AsyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1 || index == 0); + GTEST_LOG_(INFO) << name << "group Runnable2"; + })); + EXPECT_TRUE(count.load() == 0); + ptr->AsyncDispatchBarrier(std::make_shared([&]() { + EXPECT_TRUE(count.load() == 2); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "AsyncDispatchBarrier Runnable"; + })); + ptr->AsyncDispatch(std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "group Runnable2"; + })); + GTEST_LOG_(INFO) << name << "AsyncDispatchBarrier After"; + + auto time = std::chrono::milliseconds(1000); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 4); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: SerialTaskDispatcher_SyncDispatchBarrierTest_001 + * @tc.name: SyncDispatchBarrier + * @tc.desc: Test SerialTaskDispatcher sync barrier. + */ +HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_SyncDispatchBarrierTest_001, TestSize.Level0) +{ + auto name = std::string("SerialTaskDispatcher_SyncDispatchBarrierTest_001"); + GTEST_LOG_(INFO) << name << " start"; + std::shared_ptr ptr = CreateMtSerialTaskDispatcher(name, TaskPriority::DEFAULT); + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + auto group = ptr->CreateDispatchGroup(); + long sleepG1 = 200; + ptr->AsyncGroupDispatch((group), std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1 || index == 0); + GTEST_LOG_(INFO) << name << "group Runnable1"; + })); + long sleepG2 = 100; + ptr->AsyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleepG2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1 || index == 0); + GTEST_LOG_(INFO) << name << "AsyncDispatch Runnable2"; + })); + EXPECT_TRUE(count.load() == 0); + ptr->SyncDispatchBarrier(std::make_shared([&]() { + EXPECT_TRUE(count.load() == 2); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "SyncDispatchBarrier Runnable"; + })); + ptr->SyncDispatch(std::make_shared([&]() { + count.fetch_add(1); + GTEST_LOG_(INFO) << name << "SyncDispatch Runnable2"; + })); + GTEST_LOG_(INFO) << name << "SyncDispatchBarrier After"; + + auto time = std::chrono::milliseconds(1000); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 4); + GTEST_LOG_(INFO) << name << " end"; +} diff --git a/common/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/BUILD.gn b/common/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..551b443ff04c0675b28c42de1ef50037bc474656 --- /dev/null +++ b/common/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +module_output_path = "ability_runtime/mt_dispatcher_test" + +ohos_moduletest("SpecTaskDispatcherModuleTest") { + module_out_path = module_output_path + sources = [ + "${dispatcher_path}/src/dispatcher/base_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/global_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/group_impl.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/parallel_task_dispatcher_base.cpp", + "${dispatcher_path}/src/dispatcher/serial_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/spec_task_dispatcher.cpp", + "${dispatcher_path}/src/dispatcher/task_dispatcher_context.cpp", + "${dispatcher_path}/src/task/barrier_handler.cpp", + "${dispatcher_path}/src/task/sync_task.cpp", + "${dispatcher_path}/src/task/task.cpp", + "${dispatcher_path}/src/threading/default_thread_factory.cpp", + "${dispatcher_path}/src/threading/default_worker_pool_config.cpp", + "${dispatcher_path}/src/threading/task_executor.cpp", + "${dispatcher_path}/src/threading/work_thread.cpp", + "${dispatcher_path}/src/threading/worker_pool.cpp", + ] + sources += [ "spec_task_dispatcher_module_test.cpp" ] + configs = [ "${aafwk_path}/common/test/moduletest/task_dispatcher:dispatcher_mt_test_config" ] + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${dispatcher_path}/test:dispatcher_test_source", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":SpecTaskDispatcherModuleTest" ] +} diff --git a/common/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp b/common/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d251f276ddc7fe8429f51db6ea7b744b7d33e7d6 --- /dev/null +++ b/common/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function +#include +#include "app_log_wrapper.h" +#include "base_task_dispatcher.h" +#include "task_dispatcher_context.h" +#include "task_dispatcher.h" +#include "spec_task_dispatcher.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +class SpecTaskDispatcherModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr ptrSpecTaskDispatcher; +}; + +void SpecTaskDispatcherModuleTest::SetUpTestCase() +{} + +void SpecTaskDispatcherModuleTest::TearDownTestCase() +{} + +void SpecTaskDispatcherModuleTest::SetUp() +{ + std::string dispatcherName = SpecDispatcherConfig::MAIN; + TaskPriority taskPriority = TaskPriority::HIGH; + std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); + std::shared_ptr runner = EventRunner::Create(true); + ptrSpecTaskDispatcher = std::make_shared(config, runner); +} + +void SpecTaskDispatcherModuleTest::TearDown() +{ + ptrSpecTaskDispatcher = nullptr; +} + +/** + * @tc.number: SpecTaskDispatcher_SyncDispatchTest_001 + * @tc.name: SyncDispatch + * @tc.desc: Test SpecTaskDispatcher sync dispatch. + */ +HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_SyncDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("SpecTaskDispatcher_SyncDispatchTest_001"); + GTEST_LOG_(INFO) << name << " start"; + + std::atomic count(0); + EXPECT_TRUE(count.load() == 0); + long sleep1 = 200; + ptrSpecTaskDispatcher->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " SyncDispatch1 : sleep1 time=" << sleep1; + })); + // serial execute + EXPECT_TRUE(count.load() == 1); + + long sleep2 = 100; + ptrSpecTaskDispatcher->SyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " SyncDispatch2 : sleep2 time=" << sleep2; + })); + // serial execute + EXPECT_TRUE(count.load() == 2); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + GTEST_LOG_(INFO) << name << " end"; +} + +/** + * @tc.number: SpecTaskDispatcher_AsyncDispatchTest_001 + * @tc.name: AsyncDispatch + * @tc.desc: Test SpecTaskDispatcher async dispatch. + */ +HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_AsyncDispatchTest_001, TestSize.Level1) +{ + auto name = std::string("SpecTaskDispatcher_AsyncDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + + std::atomic count(0); + long sleep1 = 200; + ptrSpecTaskDispatcher->AsyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0); + GTEST_LOG_(INFO) << name << " AsyncDispatch1 : sleep2 time=" << sleep1; + })); + // async execute + EXPECT_TRUE(count.load() < 1); + long sleep2 = 100; + ptrSpecTaskDispatcher->AsyncDispatch(std::make_shared([&]() { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1); + GTEST_LOG_(INFO) << name << " AsyncDispatch2 : sleep2 time=" << sleep2; + })); + EXPECT_TRUE(count.load() < 2); + long wait = sleep1 + sleep2 + 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SpecTaskDispatcher_DelayDispatchTest_001 + * @tc.name: DelayDispatch + * @tc.desc: Test SpecTaskDispatcher delay dispatch. + */ +HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_DelayDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("SpecTaskDispatcher_DelayDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + + std::atomic count(0); + int sleep1 = 2000; + const std::shared_ptr runnanle = std::make_shared([&count, sleep = sleep1]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 2); + GTEST_LOG_(INFO) << "SpecTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }); + ptrSpecTaskDispatcher->DelayDispatch(runnanle, sleep1); + EXPECT_TRUE(count.load() == 0); + + int sleep2 = 1000; + ptrSpecTaskDispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SpecTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep2); + EXPECT_TRUE(count.load() == 0); + + int sleep3 = 1000; + ptrSpecTaskDispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep3]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SpecTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep3); + EXPECT_TRUE(count.load() == 0); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SpecTaskDispatcher_DelayDispatchTest_002 + * @tc.name: DelayDispatch + * @tc.desc: Test SpecTaskDispatcher delay dispatch. + */ +HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_DelayDispatchTest_002, TestSize.Level0) +{ + auto name = std::string("SpecTaskDispatcher_DelayDispatchTest_002"); + GTEST_LOG_(INFO) << name + " start"; + + int sleep1 = 2000; + ptrSpecTaskDispatcher->DelayDispatch(std::make_shared(nullptr), sleep1); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SpecTaskDispatcher_DelayDispatchTest_003 + * @tc.name: DelayDispatch + * @tc.desc: Test SpecTaskDispatcher delay dispatch. + */ +HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_DelayDispatchTest_003, TestSize.Level0) +{ + auto name = std::string("SpecTaskDispatcher_DelayDispatchTest_003"); + GTEST_LOG_(INFO) << name + " start"; + + int sleep1 = 2000; + ptrSpecTaskDispatcher->DelayDispatch(nullptr, sleep1); + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SpecTaskDispatcher_DelayDispatchTest_004 + * @tc.name: DelayDispatch + * @tc.desc: Test SpecTaskDispatcher delay dispatch. + */ +HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_DelayDispatchTest_004, TestSize.Level0) +{ + auto name = std::string("SpecTaskDispatcher_DelayDispatchTest_004"); + GTEST_LOG_(INFO) << name + " start"; + + std::atomic count(0); + int sleep1 = -2000; + ptrSpecTaskDispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 1 || index == 0); + GTEST_LOG_(INFO) << "SpecTaskDispatcher_DelayDispatchTest_004 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep1); + + int sleep2 = -1000; + ptrSpecTaskDispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { + int index = count.fetch_add(1); + EXPECT_TRUE(index == 0 || index == 1); + GTEST_LOG_(INFO) << "SpecTaskDispatcher_DelayDispatchTest_004 task" + std::to_string(index) + "end, elapsed" + + std::to_string(sleep) + " ms"; + }), + sleep2); + + { + long wait = 100; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + GTEST_LOG_(INFO) << name + " end"; +} + +/** + * @tc.number: SpecTaskDispatcher_ApplyDispatchTest_001 + * @tc.name: ApplyDispatch + * @tc.desc: Test SpecTaskDispatcher apply dispatch. + */ +HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_ApplyDispatchTest_001, TestSize.Level0) +{ + auto name = std::string("SpecTaskDispatcher_ApplyDispatchTest_001"); + GTEST_LOG_(INFO) << name + " start"; + + std::atomic count(0); + long sleep1 = 101; + auto repeats1 = std::make_shared>([&](long index) { + auto time = std::chrono::milliseconds(sleep1); + std::this_thread::sleep_for(time); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " repeats1 sleep1=" << sleep1; + }); + ptrSpecTaskDispatcher->ApplyDispatch(repeats1, 10); + + long sleep2 = 100; + auto repeats2 = std::make_shared>([&](long index) { + auto time = std::chrono::milliseconds(sleep2); + std::this_thread::sleep_for(time); + count.fetch_add(1); + GTEST_LOG_(INFO) << name << " repeats2 sleep2=" << sleep2; + }); + ptrSpecTaskDispatcher->ApplyDispatch(repeats2, 10); + + // async execute + EXPECT_TRUE(count.load() < 20); + long wait = sleep1 * 10 + sleep2 * 10 + 100 + 100; + GTEST_LOG_(INFO) << name << " main wait time=" << wait; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 20); + GTEST_LOG_(INFO) << name + " end"; +} \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/BUILD.gn b/frameworks/kits/ability/ability_runtime/BUILD.gn index 25671b0711bcfbb89b259259082509eaab5af40e..8926749f510e9fb05c1f2b57416768bf36efc28d 100644 --- a/frameworks/kits/ability/ability_runtime/BUILD.gn +++ b/frameworks/kits/ability/ability_runtime/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos.gni") SO_DIR = "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime" INNERKITS_DIR = "//foundation/aafwk/standard/interfaces/innerkits" -APPKIT_DIR = "//foundation/appexecfwk/standard/kits" +APPKIT_DIR = "//foundation/aafwk/standard/frameworks/kits" config("ability_context_public_config") { visibility = [ ":*" ] @@ -38,10 +38,12 @@ ohos_shared_library("ability_context_native") { "${SO_DIR}/src/ability_context_impl.cpp", "${SO_DIR}/src/connection_manager.cpp", "${SO_DIR}/src/js_extension_context.cpp", + "${SO_DIR}/src/local_call_container.cpp", + "${SO_DIR}/src/local_call_record.cpp", ] deps = [ - "${APPKIT_DIR}:app_context", + "${APPKIT_DIR}/appkit:app_context", "${INNERKITS_DIR}/ability_manager:ability_manager", "${INNERKITS_DIR}/want:want", "//foundation/ace/napi:ace_napi", @@ -49,7 +51,8 @@ ohos_shared_library("ability_context_native") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:app_manager", + "ability_runtime:runtime", "bytrace_standard:bytrace_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", @@ -57,5 +60,5 @@ ohos_shared_library("ability_context_native") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/frameworks/kits/ability/ability_runtime/include/ability_connect_callback.h b/frameworks/kits/ability/ability_runtime/include/ability_connect_callback.h old mode 100644 new mode 100755 diff --git a/frameworks/kits/ability/ability_runtime/include/ability_connection.h b/frameworks/kits/ability/ability_runtime/include/ability_connection.h old mode 100644 new mode 100755 index 13ec528008ebd0e9b72b6ed097c79bb555e90e09..ccb62d817fb39970e24828ea2a4fa0c2855807b0 --- a/frameworks/kits/ability/ability_runtime/include/ability_connection.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_connection.h @@ -37,7 +37,7 @@ public: * @brief Constructor. * @param abilityConnectCallback is used to notify caller ability that connect or disconnect is complete */ - explicit AbilityConnection(const std::shared_ptr &abilityConnectCallback); + explicit AbilityConnection(const sptr &abilityConnectCallback); /** * @brief Destructor. @@ -62,8 +62,25 @@ public: * @param resultCode, ERR_OK on success, others on failure. */ void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + + /** + * set abilityConnectCallback + * + * @param abilityConnectCallback is used to notify caller ability that connect or disconnect is complete + */ + void SetConnectCallback(sptr abilityConnectCallback); + + void SetRemoteObject(const sptr &remoteObject); + + void SetResultCode(int resultCode); + + sptr GetRemoteObject(); + + int GetResultCode(); private: - std::shared_ptr abilityConnectCallback_; + sptr abilityConnectCallback_; + sptr remoteObject_ = nullptr; + int resultCode_ = -1; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/include/ability_context.h b/frameworks/kits/ability/ability_runtime/include/ability_context.h old mode 100644 new mode 100755 index 9f0563d58bdf77459bf9b61116c0abf846f02b41..5b4e07de892a0f9a1bb8ada38e8af6f5965d13c1 --- a/frameworks/kits/ability/ability_runtime/include/ability_context.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context.h @@ -16,17 +16,20 @@ #ifndef ABILITY_RUNTIME_ABILITY_CONTEXT_H #define ABILITY_RUNTIME_ABILITY_CONTEXT_H -#include "foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/context/context.h" +#include "foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context.h" +#include "foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr/configuration.h" #include "ability_connect_callback.h" #include "ability_info.h" #include "native_engine/native_value.h" #include "start_options.h" #include "want.h" +#include "caller_callback.h" namespace OHOS { namespace AbilityRuntime { using RuntimeTask = std::function; +using PermissionRequestTask = std::function&, const std::vector&)>; class AbilityContext : public Context { public: virtual ~AbilityContext() = default; @@ -45,6 +48,21 @@ public: */ virtual ErrCode StartAbility(const AAFwk::Want &want, int requestCode) = 0; + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * @param accountId ability caller accountId. + * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE + * template is started. You can define the request code to identify the results returned by abilities. The value + * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE + * template. + */ + virtual ErrCode StartAbilityWithAccount(const AAFwk::Want &want, int accountId, int requestCode) = 0; + /** * @brief Starts a new ability. * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method @@ -62,32 +80,72 @@ public: */ virtual ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, int requestCode) = 0; + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and the value of the start options and then starts it. You can specify the ability to + * start using the two parameters. + * + * @param want Indicates the Want containing application side information about the target ability to start. + * @param accountId caller userId. + * @param startOptions Indicates the StartOptions containing service side information about the target ability to + * start. + * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE + * template is started. You can define the request code to identify the results returned by abilities. The value + * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE + * template. + */ + virtual ErrCode StartAbilityWithAccount( + const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions, int requestCode) = 0; + virtual ErrCode StartAbilityForResult(const AAFwk::Want &Want, int requestCode, RuntimeTask &&task) = 0; + virtual ErrCode StartAbilityForResultWithAccount( + const AAFwk::Want &Want, int accountId, int requestCode, RuntimeTask &&task) = 0; + + virtual ErrCode StartAbilityForResult(const AAFwk::Want &Want, const AAFwk::StartOptions &startOptions, + int requestCode, RuntimeTask &&task) = 0; + + virtual ErrCode StartAbilityForResultWithAccount( + const AAFwk::Want &Want, int accountId, const AAFwk::StartOptions &startOptions, + int requestCode, RuntimeTask &&task) = 0; + virtual ErrCode TerminateAbilityWithResult(const AAFwk::Want &want, int resultCode) = 0; virtual ErrCode RestoreWindowStage(void* contentStorage) = 0; virtual void OnAbilityResult(int requestCode, int resultCode, const AAFwk::Want &resultData) = 0; + /** + * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. + * + * @param want Indicates the want containing information about the ability to connect + * @param connectCallback Indicates the callback object when the target ability is connected. + * @return True means success and false means failure + */ + virtual bool ConnectAbility(const AAFwk::Want &want, + const sptr &connectCallback) = 0; + /** * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. - * + * @param accountId caller userId. * @param want Indicates the want containing information about the ability to connect * @param conn Indicates the callback object when the target ability is connected. * @return True means success and false means failure */ - virtual bool ConnectAbility(const AAFwk::Want &want, - const std::shared_ptr &connectCallback) = 0; + virtual bool ConnectAbilityWithAccount(const AAFwk::Want &want, int accountId, + const sptr &connectCallback) = 0; /** - * @brief Disconnects the current ability from an ability - * - * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection - * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. - */ + * @brief Disconnects the current ability from an ability + * + * @param want Indicates the want containing information about the ability to disconnect + * @param connectCallback Indicates the callback object when the target ability is connected. + * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + */ virtual void DisconnectAbility(const AAFwk::Want &want, - const std::shared_ptr &connectCallback) = 0; + const sptr &connectCallback) = 0; /** * @brief get ability info of the current ability @@ -114,13 +172,30 @@ public: /** * @brief Requests certain permissions from the system. * This method is called for permission request. This is an asynchronous method. When it is executed, - * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. + * the OnRequestPermissionsFromUserResult(int, vector, vector) method will be called back. * * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, - * String[], int[]) callback method. This code cannot be a negative number. + * @param requestCode Indicates the request code to be passed to the OnRequestPermissionsFromUserResult(int, + * vector, vector) callback method. This code cannot be a negative number. + * @param task The callback or promise fo js interface. */ - virtual void RequestPermissionsFromUser(const std::vector &permissions, int requestCode) = 0; + virtual void RequestPermissionsFromUser(const std::vector &permissions, + int requestCode, PermissionRequestTask &&task) = 0; + + /** + * @brief Called back after permissions are requested by using + * RequestPermissionsFromUser(vector, int, PermissionRequestTask). + * + * @param requestCode Indicates the request code passed to this method from + * RequestPermissionsFromUser(vector, int, PermissionRequestTask). + * @param permissions Indicates the list of permissions requested by using + * RequestPermissionsFromUser(vector, int, PermissionRequestTask). + * @param grantResults Indicates the granting results of the corresponding permissions requested using + * RequestPermissionsFromUser(vector, int, PermissionRequestTask). The value 0 indicates that a + * permission is granted, and the value -1 indicates not. + */ + virtual void OnRequestPermissionsFromUserResult( + int requestCode, const std::vector &permissions, const std::vector &grantResults) = 0; /** * @brief Get ContentStorage. @@ -128,6 +203,46 @@ public: * @return Returns the ContentStorage. */ virtual void* GetContentStorage() = 0; + + /** + * call function by callback object + * + * @param want Request info for ability. + * @param callback Indicates the callback object. + * + * @return Returns zero on success, others on failure. + */ + virtual ErrCode StartAbility(const AAFwk::Want& want, const std::shared_ptr &callback) = 0; + + /** + * caller release by callback object + * + * @param callback Indicates the callback object. + * + * @return Returns zero on success, others on failure. + */ + virtual ErrCode ReleaseAbility(const std::shared_ptr &callback) = 0; + + /** + * @brief Set mission label of this ability. + * + * @param label the label of this ability. + * @return Returns ERR_OK if success. + */ + virtual ErrCode SetMissionLabel(const std::string &label) = 0; + + virtual void SetConfiguration(const std::shared_ptr &config) = 0; + + virtual std::shared_ptr GetConfiguration() const = 0; + + using SelfType = AbilityContext; + static const size_t CONTEXT_TYPE_ID; + +protected: + bool IsContext(size_t contextTypeId) override + { + return contextTypeId == CONTEXT_TYPE_ID || Context::IsContext(contextTypeId); + } }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h b/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h old mode 100644 new mode 100755 index 2d2515cdf2ca960aa24d835531dd5aeb03fa09b8..b35f3092c3b5275c309bbea6f6e76c42ef9bb66f --- a/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h @@ -19,6 +19,8 @@ #include "ability_context.h" #include "context_impl.h" +#include "configuration.h" +#include "local_call_container.h" namespace OHOS { namespace AbilityRuntime { @@ -34,6 +36,7 @@ public: std::string GetDatabaseDir() override; std::string GetStorageDir() override; std::string GetDistributedFilesDir() override; + void SwitchArea(int mode) override; std::string GetBundleName() const override; std::shared_ptr GetApplicationInfo() const override; std::shared_ptr GetResourceManager() const override; @@ -41,23 +44,45 @@ public: std::string GetBundleCodePath() const override; ErrCode StartAbility(const AAFwk::Want &want, int requestCode) override; + ErrCode StartAbilityWithAccount(const AAFwk::Want &want, int accountId, int requestCode) override; ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, int requestCode) override; + ErrCode StartAbilityWithAccount( + const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions, int requestCode) override; ErrCode StartAbilityForResult(const AAFwk::Want &want, int requestCode, RuntimeTask &&task) override; + ErrCode StartAbilityForResultWithAccount( + const AAFwk::Want &want, int accountId, int requestCode, RuntimeTask &&task) override; + ErrCode StartAbilityForResultWithAccount(const AAFwk::Want &want, int accountId, + const AAFwk::StartOptions &startOptions, int requestCode, RuntimeTask &&task) override; + ErrCode StartAbilityForResult(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, + int requestCode, RuntimeTask &&task) override; ErrCode TerminateAbilityWithResult(const AAFwk::Want &want, int resultCode) override; void OnAbilityResult(int requestCode, int resultCode, const AAFwk::Want &resultData) override; bool ConnectAbility(const AAFwk::Want &want, - const std::shared_ptr &connectCallback) override; + const sptr &connectCallback) override; + bool ConnectAbilityWithAccount(const AAFwk::Want &want, int accountId, + const sptr &connectCallback) override; void DisconnectAbility(const AAFwk::Want &want, - const std::shared_ptr &connectCallback) override; + const sptr &connectCallback) override; std::shared_ptr GetHapModuleInfo() const override; std::shared_ptr GetAbilityInfo() const override; void MinimizeAbility() override; ErrCode TerminateSelf() override; sptr GetAbilityToken() override; - void RequestPermissionsFromUser(const std::vector &permissions, int requestCode) override; + void RequestPermissionsFromUser(const std::vector &permissions, + int requestCode, PermissionRequestTask &&task) override; + void OnRequestPermissionsFromUserResult( + int requestCode, const std::vector &permissions, const std::vector &grantResults) override; ErrCode RestoreWindowStage(void* contentStorage) override; + /** + * @brief Set mission label of this ability. + * + * @param label the label of this ability. + * @return Returns ERR_OK if success. + */ + ErrCode SetMissionLabel(const std::string &label) override; + void SetStageContext(const std::shared_ptr &stageContext); /** @@ -87,12 +112,37 @@ public: return contentStorage_; } + void SetConfiguration(const std::shared_ptr &config) override; + + std::shared_ptr GetConfiguration() const override; + /** + * call function by callback object + * + * @param want Request info for ability. + * @param callback Indicates the callback object. + * + * @return Returns zero on success, others on failure. + */ + ErrCode StartAbility(const AAFwk::Want& want, const std::shared_ptr &callback) override; + + /** + * caller release by callback object + * + * @param callback Indicates the callback object. + * + * @return Returns zero on success, others on failure. + */ + ErrCode ReleaseAbility(const std::shared_ptr &callback) override; + private: sptr token_; std::shared_ptr abilityInfo_ = nullptr; std::shared_ptr stageContext_ = nullptr; std::map resultCallbacks_; + std::map permissionRequestCallbacks_; void* contentStorage_ = nullptr; + std::shared_ptr config_; + sptr localCallContainer_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/include/caller_callback.h b/frameworks/kits/ability/ability_runtime/include/caller_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..9c778cea81ceda10a976ea9ad931b43e89f1bd0f --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/include/caller_callback.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_CALLER_CALLBACK_H +#define ABILITY_RUNTIME_CALLER_CALLBACK_H + +#include "iremote_object.h" + +namespace OHOS { +namespace AbilityRuntime { +const std::string ON_RELEASE = "release"; +const std::string ON_DIED = "died"; +/** + * @class CallerCallBack + * CallerCallBack the callback function of caller. + */ +class CallerCallBack : public std::enable_shared_from_this { +public: + /* Caller's callback object */ + using CallBackClosure = std::function &)>; + using OnReleaeClosure = std::function; + + CallerCallBack() = default; + virtual ~CallerCallBack() = default; + + void SetCallBack(CallBackClosure callback) + { + callback_ = callback; + }; + void SetOnRelease(OnReleaeClosure onRelease) + { + onRelease_ = onRelease; + }; + void InvokeCallBack(const sptr &remoteObject) + { + if (callback_) { + callback_(remoteObject); + isCallBack_ = true; + } + }; + void InvokeOnRelease(const std::string &key) + { + if (onRelease_) { + onRelease_(key); + } + }; + bool IsCallBack() + { + return isCallBack_; + }; + +private: + CallBackClosure callback_ = {}; + OnReleaeClosure onRelease_ = {}; + bool isCallBack_ = false; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_CALLER_CALLBACK_H \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/include/connection_manager.h b/frameworks/kits/ability/ability_runtime/include/connection_manager.h old mode 100644 new mode 100755 index 9b53e0a99f35febe3174438635bc5a66f8f1be96..21ea3c693a406e3ec03952f01a314c488947731b --- a/frameworks/kits/ability/ability_runtime/include/connection_manager.h +++ b/frameworks/kits/ability/ability_runtime/include/connection_manager.h @@ -82,7 +82,19 @@ public: * @return Returns the result of connecting ability connection. */ ErrCode ConnectAbility(const sptr &connectCaller, - const AAFwk::Want &want, const std::shared_ptr &connectCallback); + const AAFwk::Want &want, const sptr &connectCallback); + + /** + * @brief connect ability connection by user. + * + * @param connectCaller The connection caller. + * @param connectReceiver The connection receiver. + * @param accountId caller user. + * @param connectCallback The connection callback. + * @return Returns the result of connecting ability connection. + */ + ErrCode ConnectAbilityWithAccount(const sptr &connectCaller, + const AAFwk::Want &want, int accountId, const sptr &connectCallback); /** * @brief disconnect ability connection. @@ -93,7 +105,7 @@ public: * @return Returns the result of disconnecting ability connection. */ ErrCode DisconnectAbility(const sptr &connectCaller, - const AppExecFwk::ElementName &connectReceiver, const std::shared_ptr &connectCallback); + const AppExecFwk::ElementName &connectReceiver, const sptr &connectCallback); /** * @brief check the ability connection of caller is disconnect. @@ -115,7 +127,10 @@ private: bool IsConnectCallerEqual(const sptr &connectCaller, const sptr &connectCallerOther); bool IsConnectReceiverEqual(const AppExecFwk::ElementName &connectReceiver, const AppExecFwk::ElementName &connectReceiverOther); - std::map>> abilityConnections_; + ErrCode HandleCallbackTimeOut(const sptr &connectCaller, const AAFwk::Want &want, + const AppExecFwk::ElementName &connectReceiver, sptr abilityConnection, + const sptr &connectCallback); + std::map>> abilityConnections_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/include/local_call_container.h b/frameworks/kits/ability/ability_runtime/include/local_call_container.h new file mode 100644 index 0000000000000000000000000000000000000000..02659ff295302c712ba07fc4dfcf80847ae09420 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/include/local_call_container.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_LOCAL_CALL_CONTAINER_H +#define ABILITY_RUNTIME_LOCAL_CALL_CONTAINER_H + +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "local_call_record.h" +#include "want.h" + +namespace OHOS { +namespace AbilityRuntime { +using Want = OHOS::AAFwk::Want; +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +class LocalCallContainer : public AbilityConnectionStub { +public: + LocalCallContainer() = default; + virtual ~LocalCallContainer() = default; + + int StartAbilityInner( + const Want &want, const std::shared_ptr &callback, const sptr &callerToken); + + int Release(const std::shared_ptr &callback); + + void DumpCalls(std::vector &info) const; + + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + +private: + bool GetCallLocalreocrd( + const AppExecFwk::ElementName &elementName, std::shared_ptr &localCallRecord); + +private: + std::map> callProxyRecords_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_LOCAL_CALL_CONTAINER_H diff --git a/frameworks/kits/ability/ability_runtime/include/local_call_record.h b/frameworks/kits/ability/ability_runtime/include/local_call_record.h new file mode 100644 index 0000000000000000000000000000000000000000..4fb8ae25b232867c3d264ea50c4aad35055ef91e --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/include/local_call_record.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_LOCAL_CALL_RECORD_H +#define ABILITY_RUNTIME_LOCAL_CALL_RECORD_H + +#include "caller_callback.h" +#include "element_name.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @class LocalCallRecord + * LocalCallRecord record local call info. + */ +class LocalCallRecord : public std::enable_shared_from_this { +public: + LocalCallRecord(const AppExecFwk::ElementName &elementName); + virtual ~LocalCallRecord(); + + void SetRemoteObject(const sptr &call); + void AddCaller(const std::shared_ptr &callback); + bool RemoveCaller(const std::shared_ptr &callback); + void OnCallStubDied(const wptr &remote); + sptr GetRemoteObject() const; + void InvokeCallBack() const; + AppExecFwk::ElementName GetElementName() const; + bool IsExistCallBack() const; + +private: + static int64_t callRecordId; + int recordId_ = 0; // record id + sptr remoteObject_ = nullptr; + sptr callRecipient_ = nullptr; + std::vector> callers_; + AppExecFwk::ElementName elementName_ = {}; +}; + +/** + * @class CallRecipient + * CallRecipient notices IRemoteBroker died. + */ +class CallRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + + CallRecipient(RemoteDiedHandler handler) : handler_(handler) {}; + virtual ~CallRecipient() = default; + + void OnRemoteDied(const wptr &__attribute__((unused)) remote) override + { + if (handler_) { + handler_(remote); + } + }; + +private: + RemoteDiedHandler handler_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_LOCAL_CALL_RECORD_H diff --git a/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp b/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp old mode 100644 new mode 100755 index b5ebc37be25832bbfeed2fd326c7fee70ceaf9b3..a42fa5133f072267f4e678cde98a8df9d6fa85d6 --- a/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp +++ b/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp @@ -19,7 +19,8 @@ namespace OHOS { namespace AbilityRuntime { -AbilityConnection::AbilityConnection(const std::shared_ptr &abilityConnectCallback) +const int DIED = -1; +AbilityConnection::AbilityConnection(const sptr &abilityConnectCallback) { abilityConnectCallback_ = abilityConnectCallback; } @@ -31,6 +32,8 @@ void AbilityConnection::OnAbilityConnectDone( if (abilityConnectCallback_ == nullptr) { HILOG_ERROR("%{public}s abilityConnectCallback is nullptr.", __func__); } + SetRemoteObject(remoteObject); + SetResultCode(resultCode); abilityConnectCallback_->OnAbilityConnectDone(element, remoteObject, resultCode); HILOG_DEBUG("%{public}s end, remoteObject:%{public}p, bundleName:%{public}s, abilityName:%{public}s.", __func__, remoteObject.GetRefPtr(), element.GetBundleName().c_str(), element.GetAbilityName().c_str()); @@ -38,13 +41,47 @@ void AbilityConnection::OnAbilityConnectDone( void AbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) { - HILOG_DEBUG("%{public}s begin.", __func__); + HILOG_DEBUG("%{public}s begin, resultCode:%{public}d.", __func__, resultCode); if (abilityConnectCallback_ == nullptr) { HILOG_ERROR("%{public}s abilityConnectCallback is nullptr.", __func__); } - abilityConnectCallback_->OnAbilityDisconnectDone(element, resultCode); + // if resultCode < 0 that means the connectReceiver is died + if (resultCode == DIED) { + bool ret = ConnectionManager::GetInstance().DisconnectReceiver(element); + if (ret) { + HILOG_INFO("The service connection is not disconnected."); + } + abilityConnectCallback_->OnAbilityDisconnectDone(element, DIED + 1); + } else { + abilityConnectCallback_->OnAbilityDisconnectDone(element, resultCode); + } HILOG_DEBUG("%{public}s end, bundleName:%{public}s, abilityName:%{public}s.", __func__, element.GetBundleName().c_str(), element.GetAbilityName().c_str()); } + +void AbilityConnection::SetConnectCallback(sptr abilityConnectCallback) +{ + abilityConnectCallback_ = abilityConnectCallback; +} + +void AbilityConnection::SetRemoteObject(const sptr &remoteObject) +{ + remoteObject_ = remoteObject; +} + +void AbilityConnection::SetResultCode(int resultCode) +{ + resultCode_ = resultCode; +} + +sptr AbilityConnection::GetRemoteObject() +{ + return remoteObject_; +} + +int AbilityConnection::GetResultCode() +{ + return resultCode_; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp old mode 100644 new mode 100755 index 2abf85bd7020849b51e43893699024888d1bac72..1095c4478a704727fb474d387d40bf49c8b4a0e5 --- a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp +++ b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp @@ -22,6 +22,11 @@ namespace OHOS { namespace AbilityRuntime { +const size_t AbilityContext::CONTEXT_TYPE_ID(std::hash {} ("AbilityContext")); +const std::string GRANT_ABILITY_BUNDLE_NAME = "com.ohos.permissionmanager"; +const std::string GRANT_ABILITY_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility"; +const std::string PERMISSION_KEY = "ohos.user.grant.permission"; + std::string AbilityContextImpl::GetBundleCodeDir() { return stageContext_ ? stageContext_->GetBundleCodeDir() : ""; @@ -57,6 +62,14 @@ std::string AbilityContextImpl::GetDistributedFilesDir() return stageContext_ ? stageContext_->GetDistributedFilesDir() : ""; } +void AbilityContextImpl::SwitchArea(int mode) +{ + HILOG_DEBUG("AbilityContextImpl::SwitchArea."); + if (stageContext_ != nullptr) { + stageContext_->SwitchArea(mode); + } +} + ErrCode AbilityContextImpl::StartAbility(const AAFwk::Want &want, int requestCode) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -66,6 +79,14 @@ ErrCode AbilityContextImpl::StartAbility(const AAFwk::Want &want, int requestCod return err; } +ErrCode AbilityContextImpl::StartAbilityWithAccount(const AAFwk::Want &want, int accountId, int requestCode) +{ + HILOG_DEBUG("AbilityContextImpl::StartAbilityWithAccount. Start calling StartAbility."); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode, accountId); + HILOG_INFO("AbilityContextImpl::StartAbilityWithAccount. End calling StartAbility. ret=%{public}d", err); + return err; +} + ErrCode AbilityContextImpl::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, int requestCode) { @@ -75,6 +96,19 @@ ErrCode AbilityContextImpl::StartAbility(const AAFwk::Want &want, const AAFwk::S return err; } +ErrCode AbilityContextImpl::StartAbilityWithAccount( + const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions, int requestCode) +{ + HILOG_DEBUG("AbilityContextImpl::StartAbilityWithAccount. Start calling StartAbility."); + HILOG_INFO( + "%{public}s called, bundleName=%{public}s, abilityName=%{public}s, accountId=%{public}d", + __func__, want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), accountId); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility( + want, startOptions, token_, requestCode, accountId); + HILOG_INFO("AbilityContextImpl::StartAbilityWithAccount. End calling StartAbility. ret=%{public}d", err); + return err; +} + ErrCode AbilityContextImpl::StartAbilityForResult(const AAFwk::Want &want, int requestCode, RuntimeTask &&task) { HILOG_DEBUG("%{public}s. Start calling StartAbilityForResult.", __func__); @@ -84,6 +118,38 @@ ErrCode AbilityContextImpl::StartAbilityForResult(const AAFwk::Want &want, int r return err; } +ErrCode AbilityContextImpl::StartAbilityForResultWithAccount( + const AAFwk::Want &want, const int accountId, int requestCode, RuntimeTask &&task) +{ + HILOG_DEBUG("%{public}s. Start calling StartAbilityForResultWithAccount. accountId:%{public}d", + __func__, accountId); + resultCallbacks_.insert(make_pair(requestCode, std::move(task))); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode, accountId); + HILOG_INFO("%{public}s. End calling StartAbilityForResultWithAccount. ret=%{public}d", __func__, err); + return err; +} + +ErrCode AbilityContextImpl::StartAbilityForResult(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, + int requestCode, RuntimeTask &&task) +{ + HILOG_DEBUG("%{public}s. Start calling StartAbilityForResult.", __func__); + resultCallbacks_.insert(make_pair(requestCode, std::move(task))); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, requestCode); + HILOG_INFO("%{public}s. End calling StartAbilityForResult. ret=%{public}d", __func__, err); + return err; +} + +ErrCode AbilityContextImpl::StartAbilityForResultWithAccount( + const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions, + int requestCode, RuntimeTask &&task) +{ + HILOG_DEBUG("%{public}s. Start calling StartAbilityForResultWithAccount.", __func__); + resultCallbacks_.insert(make_pair(requestCode, std::move(task))); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility( + want, startOptions, token_, requestCode, accountId); + HILOG_INFO("%{public}s. End calling StartAbilityForResultWithAccount. ret=%{public}d", __func__, err); + return err; +} ErrCode AbilityContextImpl::TerminateAbilityWithResult(const AAFwk::Want &want, int resultCode) { @@ -102,7 +168,7 @@ void AbilityContextImpl::OnAbilityResult(int requestCode, int resultCode, const } bool AbilityContextImpl::ConnectAbility(const AAFwk::Want &want, - const std::shared_ptr &connectCallback) + const sptr &connectCallback) { HILOG_DEBUG("%{public}s begin.", __func__); ErrCode ret = @@ -111,8 +177,18 @@ bool AbilityContextImpl::ConnectAbility(const AAFwk::Want &want, return ret == ERR_OK; } +bool AbilityContextImpl::ConnectAbilityWithAccount(const AAFwk::Want &want, int accountId, + const sptr &connectCallback) +{ + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode ret = + ConnectionManager::GetInstance().ConnectAbilityWithAccount(token_, want, accountId, connectCallback); + HILOG_INFO("AbilityContextImpl::ConnectAbility ErrorCode = %{public}d", ret); + return ret == ERR_OK; +} + void AbilityContextImpl::DisconnectAbility(const AAFwk::Want &want, - const std::shared_ptr &connectCallback) + const sptr &connectCallback) { HILOG_DEBUG("%{public}s begin.", __func__); ErrCode ret = @@ -168,6 +244,16 @@ void AbilityContextImpl::SetStageContext(const std::shared_ptr &config) +{ + config_ = config; +} + +std::shared_ptr AbilityContextImpl::GetConfiguration() const +{ + return config_; +} + void AbilityContextImpl::MinimizeAbility() { HILOG_DEBUG("%{public}s begin.", __func__); @@ -195,9 +281,29 @@ sptr AbilityContextImpl::GetAbilityToken() return token_; } -void AbilityContextImpl::RequestPermissionsFromUser(const std::vector &permissions, int requestCode) +void AbilityContextImpl::RequestPermissionsFromUser(const std::vector &permissions, + int requestCode, PermissionRequestTask &&task) { HILOG_INFO("%{public}s called.", __func__); + if (permissions.size() == 0 || requestCode < 0) { + HILOG_ERROR("%{public}s. The params are invalid.", __func__); + } + AAFwk::Want want; + want.SetElementName(GRANT_ABILITY_BUNDLE_NAME, GRANT_ABILITY_ABILITY_NAME); + want.SetParam(PERMISSION_KEY, permissions); + permissionRequestCallbacks_.insert(make_pair(requestCode, std::move(task))); + HILOG_DEBUG("%{public}s. Start calling StartAbility.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode); + HILOG_INFO("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err); +} + +void AbilityContextImpl::OnRequestPermissionsFromUserResult( + int requestCode, const std::vector &permissions, const std::vector &grantResults) +{ + HILOG_DEBUG("%{public}s. Start calling OnRequestPermissionsFromUserResult.", __func__); + permissionRequestCallbacks_[requestCode](permissions, grantResults); + permissionRequestCallbacks_.erase(requestCode); + HILOG_INFO("%{public}s. End calling OnRequestPermissionsFromUserResult.", __func__); } ErrCode AbilityContextImpl::RestoreWindowStage(void* contentStorage) @@ -207,5 +313,35 @@ ErrCode AbilityContextImpl::RestoreWindowStage(void* contentStorage) contentStorage_ = contentStorage; return err; } + +ErrCode AbilityContextImpl::StartAbility( + const AAFwk::Want& want, const std::shared_ptr &callback) +{ + if (!localCallContainer_) { + localCallContainer_ = new (std::nothrow)LocalCallContainer(); + } + + return localCallContainer_->StartAbilityInner(want, callback, token_); +} + +ErrCode AbilityContextImpl::ReleaseAbility(const std::shared_ptr &callback) +{ + if (!localCallContainer_) { + HILOG_ERROR("%{public}s false.", __func__); + return ERR_INVALID_VALUE; + } + + return localCallContainer_->Release(callback); +} + +ErrCode AbilityContextImpl::SetMissionLabel(const std::string &label) +{ + HILOG_INFO("%{public}s begin. label = %{public}s", __func__, label.c_str()); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->SetMissionLabel(token_, label); + if (err != ERR_OK) { + HILOG_ERROR("AbilityContextImpl::SetMissionLabel is failed %{public}d", err); + } + return err; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp b/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp old mode 100644 new mode 100755 index e380e4ce517e7793042976394eacf6c58e04386b..6c35e04942128e71c41a8e54d53119796253c70d --- a/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp +++ b/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp @@ -28,7 +28,7 @@ ConnectionManager& ConnectionManager::GetInstance() } ErrCode ConnectionManager::ConnectAbility(const sptr &connectCaller, - const AAFwk::Want &want, const std::shared_ptr &connectCallback) + const AAFwk::Want &want, const sptr &connectCallback) { if (connectCaller == nullptr || connectCallback == nullptr) { HILOG_ERROR("%{public}s, connectCaller or connectCallback is nullptr.", __func__); @@ -43,33 +43,96 @@ ErrCode ConnectionManager::ConnectAbility(const sptr &connectCall sptr abilityConnection; auto item = std::find_if(abilityConnections_.begin(), abilityConnections_.end(), [&connectCaller, &connectReceiver](const std::map>>::value_type &obj) { + std::vector>>::value_type &obj) { return connectCaller == obj.first.connectCaller && connectReceiver.GetBundleName() == obj.first.connectReceiver.GetBundleName() && connectReceiver.GetAbilityName() == obj.first.connectReceiver.GetAbilityName(); }); if (item != abilityConnections_.end()) { - std::vector> callbacks = item->second; + std::vector> callbacks = item->second; callbacks.push_back(connectCallback); + abilityConnections_[item->first] = callbacks; abilityConnection = item->first.abilityConnection; - HILOG_INFO("%{public}s find abilityConnection:%{public}p exist, callbackSize:%{public}d.", + abilityConnection->SetConnectCallback(connectCallback); + HILOG_INFO("%{public}s end, find abilityConnection:%{public}p exist, callbackSize:%{public}d.", __func__, abilityConnection.GetRefPtr(), (int32_t)callbacks.size()); + if (abilityConnection->GetResultCode() == ERR_OK) { + connectCallback->OnAbilityConnectDone(connectReceiver, abilityConnection->GetRemoteObject(), + abilityConnection->GetResultCode()); + return ERR_OK; + } else { + return HandleCallbackTimeOut(connectCaller, want, connectReceiver, abilityConnection, connectCallback); + } } else { abilityConnection = new AbilityConnection(connectCallback); - ConnectionInfo connectionInfo(connectCaller, connectReceiver, abilityConnection); - std::vector> callbacks; - callbacks.push_back(connectCallback); - abilityConnections_[connectionInfo] = callbacks; - HILOG_DEBUG("%{public}s end, abilityConnection is not exist, make a new abilityConnection.", __func__); - HILOG_DEBUG("%{public}s end, abilityConnection: %{public}p, abilityConnectionsSize:%{public}d.", + ErrCode ret = + AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, abilityConnection, connectCaller); + if (ret == ERR_OK) { + ConnectionInfo connectionInfo(connectCaller, connectReceiver, abilityConnection); + std::vector> callbacks; + callbacks.push_back(connectCallback); + abilityConnections_[connectionInfo] = callbacks; + } + HILOG_DEBUG("%{public}s end, not find connection, connection: %{public}p, abilityConnectionsSize:%{public}d.", __func__, abilityConnection.GetRefPtr(), (int32_t)abilityConnections_.size()); + return ret; } +} + +ErrCode ConnectionManager::ConnectAbilityWithAccount(const sptr &connectCaller, + const AAFwk::Want &want, int accountId, const sptr &connectCallback) +{ + if (connectCaller == nullptr || connectCallback == nullptr) { + HILOG_ERROR("%{public}s, connectCaller or connectCallback is nullptr.", __func__); + return ERR_INVALID_VALUE; + } + + AppExecFwk::ElementName connectReceiver = want.GetElement(); + HILOG_DEBUG("%{public}s begin, connectCaller: %{public}p, connectReceiver: %{public}s.", + __func__, connectCaller.GetRefPtr(), + (connectReceiver.GetBundleName() + ":" + connectReceiver.GetAbilityName()).c_str()); - return AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, abilityConnection, connectCaller); + sptr abilityConnection; + auto item = std::find_if(abilityConnections_.begin(), abilityConnections_.end(), + [&connectCaller, &connectReceiver](const std::map>>::value_type &obj) { + return connectCaller == obj.first.connectCaller && + connectReceiver.GetBundleName() == obj.first.connectReceiver.GetBundleName() && + connectReceiver.GetAbilityName() == obj.first.connectReceiver.GetAbilityName(); + }); + if (item != abilityConnections_.end()) { + std::vector> callbacks = item->second; + callbacks.push_back(connectCallback); + abilityConnections_[item->first] = callbacks; + abilityConnection = item->first.abilityConnection; + abilityConnection->SetConnectCallback(connectCallback); + HILOG_INFO("%{public}s end, find abilityConnection:%{public}p exist, callbackSize:%{public}d.", + __func__, abilityConnection.GetRefPtr(), (int32_t)callbacks.size()); + if (abilityConnection->GetResultCode() == ERR_OK) { + connectCallback->OnAbilityConnectDone(connectReceiver, abilityConnection->GetRemoteObject(), + abilityConnection->GetResultCode()); + return ERR_OK; + } else { + return HandleCallbackTimeOut(connectCaller, want, connectReceiver, abilityConnection, connectCallback); + } + } else { + abilityConnection = new AbilityConnection(connectCallback); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility( + want, abilityConnection, connectCaller, accountId); + if (ret == ERR_OK) { + ConnectionInfo connectionInfo(connectCaller, connectReceiver, abilityConnection); + std::vector> callbacks; + callbacks.push_back(connectCallback); + abilityConnections_[connectionInfo] = callbacks; + } + HILOG_DEBUG("%{public}s end, not find connection, connection: %{public}p, abilityConnectionsSize:%{public}d.", + __func__, abilityConnection.GetRefPtr(), (int32_t)abilityConnections_.size()); + return ret; + } } ErrCode ConnectionManager::DisconnectAbility(const sptr &connectCaller, - const AppExecFwk::ElementName &connectReceiver, const std::shared_ptr &connectCallback) + const AppExecFwk::ElementName &connectReceiver, const sptr &connectCallback) { if (connectCaller == nullptr || connectCallback == nullptr) { HILOG_ERROR("%{public}s, connectCaller or connectCallback is nullptr.", __func__); @@ -82,27 +145,34 @@ ErrCode ConnectionManager::DisconnectAbility(const sptr &connectC auto item = std::find_if(abilityConnections_.begin(), abilityConnections_.end(), [&connectCaller, &connectReceiver]( - const std::map>>::value_type &obj) { + const std::map>>::value_type &obj) { return connectCaller == obj.first.connectCaller && connectReceiver.GetBundleName() == obj.first.connectReceiver.GetBundleName() && connectReceiver.GetAbilityName() == obj.first.connectReceiver.GetAbilityName(); }); if (item != abilityConnections_.end()) { - std::vector> callbacks = item->second; + std::vector> callbacks = item->second; HILOG_DEBUG("%{public}s begin remove callback, callbackSize:%{public}d.", __func__, (int32_t)callbacks.size()); - for (auto iter = callbacks.begin(); iter != callbacks.end(); iter++) { + auto iter = callbacks.begin(); + while (iter != callbacks.end()) { if (*iter == connectCallback) { - callbacks.erase(iter); + iter = callbacks.erase(iter); + } else { + iter++; } } + abilityConnections_[item->first] = callbacks; sptr abilityConnection; abilityConnection = item->first.abilityConnection; + abilityConnection->SetConnectCallback(connectCallback); HILOG_INFO("%{public}s end, find abilityConnection:%{public}p exist, abilityConnectionsSize:%{public}d.", __func__, abilityConnection.GetRefPtr(), (int32_t)abilityConnections_.size()); if (callbacks.size() == 0) { + abilityConnections_.erase(item); HILOG_DEBUG("%{public}s disconnectAbility.", __func__); return AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(abilityConnection); } else { + connectCallback->OnAbilityDisconnectDone(connectReceiver, ERR_OK); HILOG_DEBUG("%{public}s callbacks is not empty, do not need disconnectAbility.", __func__); return ERR_OK; } @@ -119,13 +189,17 @@ bool ConnectionManager::DisconnectCaller(const sptr &connectCalle HILOG_ERROR("%{public}s end, connectCaller is nullptr.", __func__); return false; } + HILOG_DEBUG("%{public}s, connectCaller:%{public}p, abilityConnectionsSize:%{public}d.", __func__, connectCaller.GetRefPtr(), (int32_t)abilityConnections_.size()); + bool isDisconnect = false; auto iter = abilityConnections_.begin(); while (iter != abilityConnections_.end()) { ConnectionInfo connectionInfo = iter->first; if (IsConnectCallerEqual(connectionInfo.connectCaller, connectCaller)) { + HILOG_DEBUG("%{public}s DisconnectAbility connection:%{public}p.", + __func__, connectionInfo.abilityConnection.GetRefPtr()); ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(connectionInfo.abilityConnection); if (ret != ERR_OK) { @@ -147,16 +221,12 @@ bool ConnectionManager::DisconnectReceiver(const AppExecFwk::ElementName &connec HILOG_DEBUG("%{public}s begin, abilityConnectionsSize:%{public}d, bundleName:%{public}s, abilityName:%{public}s.", __func__, (int32_t)abilityConnections_.size(), connectReceiver.GetBundleName().c_str(), connectReceiver.GetAbilityName().c_str()); + bool isDisconnect = false; auto iter = abilityConnections_.begin(); while (iter != abilityConnections_.end()) { ConnectionInfo connectionInfo = iter->first; if (IsConnectReceiverEqual(connectionInfo.connectReceiver, connectReceiver)) { - ErrCode ret = - AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(connectionInfo.abilityConnection); - if (ret != ERR_OK) { - HILOG_ERROR("%{public}s ams->DisconnectAbility error, ret=%{public}d", __func__, ret); - } iter = abilityConnections_.erase(iter); isDisconnect = true; } else { @@ -180,5 +250,22 @@ bool ConnectionManager::IsConnectReceiverEqual(const AppExecFwk::ElementName &co return connectReceiver.GetBundleName() == connectReceiverOther.GetBundleName() && connectReceiver.GetAbilityName() == connectReceiverOther.GetAbilityName(); } + +ErrCode ConnectionManager::HandleCallbackTimeOut(const sptr &connectCaller, const AAFwk::Want &want, + const AppExecFwk::ElementName &connectReceiver, sptr abilityConnection, + const sptr &connectCallback) +{ + if (abilityConnection->GetRemoteObject() == nullptr) { + while (true) { + if (abilityConnection->GetRemoteObject() != nullptr) { + connectCallback->OnAbilityConnectDone(connectReceiver, abilityConnection->GetRemoteObject(), + abilityConnection->GetResultCode()); + return ERR_OK; + } + } + } else { + return AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, abilityConnection, connectCaller); + } +} } // namespace AbilityRuntime -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp b/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ef298e70f40786018b681ff1a77208f1ce96ad6 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "hilog_wrapper.h" +#include "ability_manager_client.h" +#include "local_call_container.h" + +namespace OHOS { +namespace AbilityRuntime { +int LocalCallContainer::StartAbilityInner( + const Want &want, const std::shared_ptr &callback, const sptr &callerToken) +{ + HILOG_DEBUG("start ability by call."); + + if (!callback) { + HILOG_ERROR("callback)is nullptr."); + return ERR_INVALID_VALUE; + } + + if (want.GetElement().GetBundleName().empty() + || want.GetElement().GetAbilityName().empty()) { + HILOG_ERROR("the element of want is empty."); + return ERR_INVALID_VALUE; + } + + if (want.GetElement().GetDeviceID().empty()) { + HILOG_DEBUG("start ability by call, element:DeviceID is empty"); + } + + HILOG_DEBUG("start ability by call, element:%{public}s", want.GetElement().GetURI().c_str()); + + AppExecFwk::ElementName element = want.GetElement(); + std::shared_ptr localCallRecord; + if (!GetCallLocalreocrd(element, localCallRecord)) { + localCallRecord = std::make_shared(element); + if (!localCallRecord) { + HILOG_ERROR("localCallRecord create fail."); + return ERR_INVALID_VALUE; + } + std::string uri = element.GetURI(); + callProxyRecords_.emplace(uri, localCallRecord); + } + + HILOG_DEBUG("start ability by call, localCallRecord->AddCaller(callback) begin"); + localCallRecord->AddCaller(callback); + HILOG_DEBUG("start ability by call, localCallRecord->AddCaller(callback) end"); + + auto remote = localCallRecord->GetRemoteObject(); + if (!remote) { + auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityClient == nullptr) { + HILOG_ERROR("LocalCallContainer::Resolve abilityClient is nullptr"); + return ERR_INVALID_VALUE; + } + sptr connect = iface_cast(this); + HILOG_DEBUG("start ability by call, abilityClient->StartAbilityByCall call"); + return abilityClient->StartAbilityByCall(want, this, callerToken); + } + // already finish call requst. + HILOG_DEBUG("start ability by call, callback->InvokeCallBack(remote) begin"); + callback->InvokeCallBack(remote); + HILOG_DEBUG("start ability by call, callback->InvokeCallBack(remote) end"); + + return ERR_OK; +} + +int LocalCallContainer::Release(const std::shared_ptr& callback) +{ + auto isExist = [&callback](auto &record) { + return record.second->RemoveCaller(callback); + }; + + auto iter = std::find_if(callProxyRecords_.begin(), callProxyRecords_.end(), isExist); + if (iter == callProxyRecords_.end()) { + HILOG_ERROR("release localcallrecord failed."); + return ERR_INVALID_VALUE; + } + + std::shared_ptr record = iter->second; + if (!record) { + HILOG_ERROR("record is nullptr."); + return ERR_INVALID_VALUE; + } + + if (record->IsExistCallBack()) { + // just release callback. + return ERR_OK; + } + + // notify ams this connect need to release. + AppExecFwk::ElementName elementName = record->GetElementName() ; + auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityClient == nullptr) { + HILOG_ERROR("LocalCallContainer::Resolve abilityClient is nullptr"); + return ERR_INVALID_VALUE; + } + sptr connect = iface_cast(this); + if (abilityClient->ReleaseAbility(connect, elementName) != ERR_OK) { + HILOG_ERROR("ReleaseAbility failed."); + return ERR_INVALID_VALUE; + } + + callProxyRecords_.erase(iter); + + return ERR_OK; +} + +void LocalCallContainer::DumpCalls(std::vector &info) const +{ + HILOG_DEBUG("LocalCallContainer::DumpCalls called."); +} + +void LocalCallContainer::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + HILOG_DEBUG("LocalCallContainer::OnAbilityConnectDone start %{public}s .", element.GetURI().c_str()); + if (resultCode != ERR_OK) { + HILOG_ERROR("OnAbilityConnectDone failed."); + } + std::shared_ptr localCallRecord; + if (GetCallLocalreocrd(element, localCallRecord)) { + localCallRecord->SetRemoteObject(remoteObject); + } + + if (localCallRecord) { + localCallRecord->InvokeCallBack(); + } + + HILOG_DEBUG("LocalCallContainer::OnAbilityConnectDone end."); + + return; +} + +void LocalCallContainer::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ +} + +bool LocalCallContainer::GetCallLocalreocrd( + const AppExecFwk::ElementName &elementName, std::shared_ptr &localCallRecord) +{ + auto iter = callProxyRecords_.find(elementName.GetURI()); + if (iter != callProxyRecords_.end()) { + localCallRecord = iter->second; + return true; + } + + return false; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/src/local_call_record.cpp b/frameworks/kits/ability/ability_runtime/src/local_call_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2c30b86491f756d8cbabf5632cea57ff93b373b --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/src/local_call_record.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "local_call_record.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +int64_t LocalCallRecord::callRecordId = 0; +LocalCallRecord::LocalCallRecord(const AppExecFwk::ElementName &elementName) +{ + recordId_ = callRecordId++; + elementName_ = elementName; +} + +LocalCallRecord::~LocalCallRecord() +{ + if (remoteObject_ && callRecipient_) { + remoteObject_->RemoveDeathRecipient(callRecipient_); + } +} + +void LocalCallRecord::SetRemoteObject(const sptr &call) +{ + if (!call) { + HILOG_ERROR("remote object is nullptr"); + return; + } + + remoteObject_ = call; + + if (!callRecipient_) { + callRecipient_ = + new CallRecipient(std::bind(&LocalCallRecord::OnCallStubDied, this, std::placeholders::_1)); + } + + remoteObject_->AddDeathRecipient(callRecipient_); + HILOG_DEBUG("SetRemoteObject complete."); +} + +void LocalCallRecord::AddCaller(const std::shared_ptr &callback) +{ + callers_.emplace_back(callback); +} + +bool LocalCallRecord::RemoveCaller(const std::shared_ptr &callback) +{ + if (callers_.empty()) { + HILOG_ERROR("this caller vector is empty."); + return false; + } + + auto iter = std::find(callers_.begin(), callers_.end(), callback); + if (iter != callers_.end()) { + callback->InvokeOnRelease(ON_RELEASE); + callers_.erase(iter); + return true; + } + + HILOG_ERROR("this caller callback can't find."); + return false; +} + +void LocalCallRecord::OnCallStubDied(const wptr &remote) +{ + HILOG_DEBUG("OnCallStubDied."); + for (auto &callBack:callers_) { + if (callBack) { + HILOG_ERROR("invoke caller's OnRelease."); + callBack->InvokeOnRelease(ON_DIED); + } + } +} + +void LocalCallRecord::InvokeCallBack() const +{ + if (!remoteObject_) { + HILOG_ERROR("remote object is nullptr, can't callback."); + return; + } + + for (auto &callBack:callers_) { + if (callBack && !callBack->IsCallBack()) { + callBack->InvokeCallBack(remoteObject_); + } + } + HILOG_DEBUG("finish callback with remote object."); +} + +sptr LocalCallRecord::GetRemoteObject() const +{ + return remoteObject_; +} + +AppExecFwk::ElementName LocalCallRecord::GetElementName() const +{ + return elementName_; +} + +bool LocalCallRecord::IsExistCallBack() const +{ + return (callers_.size() > 0); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/test/BUILD.gn b/frameworks/kits/ability/ability_runtime/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..98257f7c4fa5b05589b955d982347fa9821c13d7 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +module_output_path = "ability_runtime/ability_call_test" + +############################################################################### +#1. intent(c++) get/set test without transport + +config("module_private_config") { + visibility = [ ":*" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/Ability/include", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/BMS/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] +} + +ohos_moduletest("ability_caller_fw_module_test") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", + "moduletest/ability_caller_fw_module_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] +} + +################################################################################ +group("moduletest") { + testonly = true + + deps = [] + deps += [ ":ability_caller_fw_module_test" ] + + # if (is_phone_product) { + # deps += [ ":ability_caller_fw_module_test" ] + # } +} diff --git a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..284df7e225e4b63fccdde2add4d7ba972b9985b1 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_manager_client.h" +#include "ability_manager_interface.h" +#include "string_ex.h" +#include "hilog_wrapper.h" +#include "ipc_skeleton.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "sys_mgr_client.h" + +namespace OHOS { +namespace AAFwk { +std::shared_ptr mockMTInstance_ = nullptr; +std::mutex mockMTMutex_; + +std::shared_ptr AbilityManagerClient::GetInstance() +{ + if (mockMTInstance_ == nullptr) { + std::lock_guard lock_l(mockMTMutex_); + if (mockMTInstance_ == nullptr) { + mockMTInstance_ = std::make_shared(); + } + } + return mockMTInstance_; +} + +AbilityManagerClient::AbilityManagerClient() +{} + +AbilityManagerClient::~AbilityManagerClient() +{} + +ErrCode AbilityManagerClient::AttachAbilityThread( + const sptr &scheduler, const sptr &token) +{ + HILOG_INFO("AbilityManagerClient::AttachAbilityThread start"); + ErrCode err = Connect(); + if (err != ERR_OK) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->AttachAbilityThread(scheduler, token); +} + +ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr &token, int state, const PacMap &saveData) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->AbilityTransitionDone(token, state, saveData); +} + +ErrCode AbilityManagerClient::ScheduleConnectAbilityDone( + const sptr &token, const sptr &remoteObject) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->ScheduleConnectAbilityDone(token, remoteObject); +} + +ErrCode AbilityManagerClient::ScheduleDisconnectAbilityDone(const sptr &token) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->ScheduleDisconnectAbilityDone(token); +} + +ErrCode AbilityManagerClient::ScheduleCommandAbilityDone(const sptr &token) +{ + if (remoteObject_ == nullptr) { + HILOG_ERROR("%{private}s:ability service not command", __func__); + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->ScheduleCommandAbilityDone(token); +} + +void AbilityManagerClient::AddWindowInfo(const sptr &token, int32_t windowToken) +{ + if (remoteObject_ == nullptr) { + return; + } + sptr abms = iface_cast(remoteObject_); + abms->AddWindowInfo(token, windowToken); +} + +ErrCode AbilityManagerClient::StartAbility(const Want &want, int32_t userId, int requestCode) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->StartAbility(want, userId, requestCode); +} + +ErrCode AbilityManagerClient::StartAbility( + const Want &want, const sptr &callerToken, int32_t userId, int requestCode) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->StartAbility(want, callerToken, userId, requestCode); +} + +ErrCode AbilityManagerClient::StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) +{ + HILOG_INFO("AbilityManagerClient::StartAbilityByCall start"); + if (remoteObject_ == nullptr) { + HILOG_INFO("AbilityManagerClient::StartAbilityByCall fail because remoteobject is null"); + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->StartAbilityByCall(want, connect, callerToken); +} + +ErrCode AbilityManagerClient::ReleaseAbility( + const sptr &connect, const AppExecFwk::ElementName &element) +{ + HILOG_INFO("AbilityManagerClient::ReleaseAbility start"); + if (remoteObject_ == nullptr) { + HILOG_INFO("AbilityManagerClient::ReleaseAbility fail because remoteobject is null"); + return ABILITY_SERVICE_NOT_CONNECTED; + } + HILOG_INFO("AbilityManagerClient::StartAbility start2"); + sptr abms = iface_cast(remoteObject_); + return abms->ReleaseAbility(connect, element); +} + +ErrCode AbilityManagerClient::TerminateAbility( + const sptr &token, int resultCode, const Want *resultWant) +{ + HILOG_INFO("AbilityManagerClient::TerminateAbility start"); + if (remoteObject_ == nullptr) { + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + } + sptr abms = iface_cast(remoteObject_); + HILOG_INFO("AbilityManagerClient::TerminateAbility end"); + return abms->TerminateAbility(token, resultCode, resultWant); +} + +ErrCode AbilityManagerClient::TerminateAbility(const sptr &callerToken, int requestCode) +{ + if (remoteObject_ == nullptr) { + HILOG_ERROR("%{private}s:ability service not connect", __func__); + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->TerminateAbility(callerToken, requestCode); +} + +ErrCode AbilityManagerClient::ConnectAbility( + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) +{ + if (remoteObject_ == nullptr) { + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + } + sptr abms = iface_cast(remoteObject_); + return abms->ConnectAbility(want, connect, callerToken, userId); +} + +ErrCode AbilityManagerClient::DisconnectAbility(const sptr &connect) +{ + if (remoteObject_ == nullptr) { + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + } + sptr abms = iface_cast(remoteObject_); + return abms->DisconnectAbility(connect); +} + +ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector &state) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + abms->DumpState(args, state); + return ERR_OK; +} + +ErrCode AbilityManagerClient::Connect() +{ + std::lock_guard lock(mockMTMutex_); + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject_ == nullptr) { + HILOG_ERROR("AbilityManagerClient::Connect remoteObject_ == nullptr"); + return ERR_NO_MEMORY; + } + + return ERR_OK; +} + +ErrCode AbilityManagerClient::GetAllStackInfo(StackInfo &stackInfo) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->GetAllStackInfo(stackInfo); +} + +ErrCode AbilityManagerClient::StopServiceAbility(const Want &want) +{ + if (remoteObject_ == nullptr) { + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + } + sptr abms = iface_cast(remoteObject_); + return abms->StopServiceAbility(want); +} + +sptr AbilityManagerClient::AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) +{ + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject_ == nullptr) { + return nullptr; + } + + sptr abms = iface_cast(remoteObject_); + return abms->AcquireDataAbility(uri, tryBind, callerToken); +} + +ErrCode AbilityManagerClient::ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) +{ + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject_ == nullptr) { + return -1; + } + + sptr abms = iface_cast(remoteObject_); + return abms->ReleaseDataAbility(dataAbilityScheduler, callerToken); +} + +ErrCode AbilityManagerClient::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, + int32_t missionId, const sptr &callback, AAFwk::WantParams &wantParams) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->ContinueMission(srcDeviceId, dstDeviceId, missionId, callback, wantParams); +} + +ErrCode AbilityManagerClient::StartContinuation(const Want &want, const sptr &abilityToken, + int32_t status) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->StartContinuation(want, abilityToken, status); +} + +void AbilityManagerClient::NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) +{ + if (remoteObject_ == nullptr) { + return; + } + + sptr abms = iface_cast(remoteObject_); + abms->NotifyCompleteContinuation(deviceId, sessionId, isSuccess); +} + +ErrCode AbilityManagerClient::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->StartSyncRemoteMissions(devId, fixConflict, tag); +} + +ErrCode AbilityManagerClient::StopSyncRemoteMissions(const std::string& devId) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->StopSyncRemoteMissions(devId); +} + +ErrCode AbilityManagerClient::StartUser(int accountId) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->StartUser(accountId); +} + +ErrCode AbilityManagerClient::StopUser(int accountId, const sptr &callback) +{ + if (remoteObject_ == nullptr) { + return ABILITY_SERVICE_NOT_CONNECTED; + } + + sptr abms = iface_cast(remoteObject_); + return abms->StopUser(accountId, callback); +} +} // namespace AAFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2e1125b34861be734b6ac5ded468b519469b756d --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "mock_serviceability_manager_service.h" +#include + +#include +#include +#include +#include + +using OHOS::AppExecFwk::ElementName; + +namespace OHOS { +namespace AAFwk { +MockServiceAbilityManagerService::MockServiceAbilityManagerService() +{} + +MockServiceAbilityManagerService::~MockServiceAbilityManagerService() +{} + +int MockServiceAbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode) +{ + return 0; +} + +int MockServiceAbilityManagerService::StartAbility( + const Want &want, const sptr &callerToken, int32_t userId, int requestCode) +{ + return 0; +} + +int MockServiceAbilityManagerService::StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) +{ + GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::StartAbilityByCall"; + if (!connect) { + GTEST_LOG_(INFO) << "MockAbilityManagerService::StartAbilityByCall connect is null"; + return -1; + } + return 0; +} + +int MockServiceAbilityManagerService::StartAbility( + const Want &want, const StartOptions &startOptions, + const sptr &callerToken, int32_t userId, int requestCode) +{ + return 0; +} + +int MockServiceAbilityManagerService::TerminateAbility( + const sptr &token, int resultCode, const Want *resultWant) +{ + return 0; +} + +int MockServiceAbilityManagerService::ConnectAbility( + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) +{ + return -1; +} + +int MockServiceAbilityManagerService::DisconnectAbility(const sptr &connect) +{ + return 0; +} + +int MockServiceAbilityManagerService::AttachAbilityThread( + const sptr &scheduler, const sptr &token) +{ + return 0; +} + +void MockServiceAbilityManagerService::DumpState(const std::string &args, std::vector &info) +{} + +void MockServiceAbilityManagerService::DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) +{} + +int MockServiceAbilityManagerService::AbilityTransitionDone( + const sptr &token, int state, const PacMap &saveData) +{ + return 0; +} + +int MockServiceAbilityManagerService::ScheduleConnectAbilityDone( + const sptr &token, const sptr &remoteObject) +{ + return 0; +} + +int MockServiceAbilityManagerService::ScheduleDisconnectAbilityDone(const sptr &token) +{ + return 0; +} + +int MockServiceAbilityManagerService::ScheduleCommandAbilityDone(const sptr &token) +{ + return 0; +} + +void MockServiceAbilityManagerService::AddWindowInfo(const sptr &token, int32_t windowToken) +{} + +int MockServiceAbilityManagerService::TerminateAbilityResult(const sptr &token, int startId) +{ + return 0; +} + +int MockServiceAbilityManagerService::TerminateAbilityByCaller(const sptr &callerToken, int requestCode) +{ + return 0; +} + +int MockServiceAbilityManagerService::ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) +{ + GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::ReleaseAbility"; + return 0; +} + +int MockServiceAbilityManagerService::StopServiceAbility(const Want &want, int32_t userId) +{ + return 0; +} + +int MockServiceAbilityManagerService::RemoveMission(int id) +{ + return 0; +} + +int MockServiceAbilityManagerService::RemoveStack(int id) +{ + return 0; +} + +int MockServiceAbilityManagerService::MoveMissionToEnd(const sptr &token, const bool nonFirst) +{ + return 0; +} + +bool MockServiceAbilityManagerService::IsFirstInMission(const sptr &token) +{ + return true; +} + +int MockServiceAbilityManagerService::CompelVerifyPermission( + const std::string &permission, int pid, int uid, std::string &message) +{ + return 0; +} + +int MockServiceAbilityManagerService::PowerOff() +{ + return 0; +} +int MockServiceAbilityManagerService::PowerOn() +{ + return 0; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h new file mode 100644 index 0000000000000000000000000000000000000000..b32dd76274c04dc826794ce76bd386686e26284b --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h @@ -0,0 +1,317 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_SERVICEABILITY_MOCK_MANAGER_SERVICE_H +#define OHOS_AAFWK_SERVICEABILITY_MOCK_MANAGER_SERVICE_H + +#include +#include +#include +#include + +#include "ability_manager_stub.h" +#include "iremote_object.h" + +#include "gmock/gmock.h" + +namespace OHOS { +namespace AAFwk { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class MockServiceAbilityManagerService : public AbilityManagerStub, + public std::enable_shared_from_this { +public: + MockServiceAbilityManagerService(); + ~MockServiceAbilityManagerService(); + + int StartAbility( + const Want &want, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; + int StartAbility( + const Want &want, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; + int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; + + int StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken); + + int TerminateAbility( + const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; + int MinimizeAbility(const sptr &token) override + { + return 0; + } + int ConnectAbility( + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) override; + int DisconnectAbility(const sptr &connect) override; + + void AddWindowInfo(const sptr &token, int32_t windowToken) override; + + int AttachAbilityThread(const sptr &scheduler, const sptr &token) override; + + int AbilityTransitionDone(const sptr &token, int state, const PacMap &saveData) override; + int ScheduleConnectAbilityDone(const sptr &token, const sptr &remoteObject) override; + int ScheduleDisconnectAbilityDone(const sptr &token) override; + int ScheduleCommandAbilityDone(const sptr &token) override; + + void DumpState(const std::string &args, std::vector &info) override; + void DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) override; + + int TerminateAbilityResult(const sptr &token, int startId) override; + int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) override; + + int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) override; + + int ReleaseAbility(const sptr &connect, const AppExecFwk::ElementName &element) override; + + MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); + MOCK_METHOD1(MoveMissionToTop, int(int32_t missionId)); + MOCK_METHOD1(KillProcess, int(const std::string &bundleName)); + MOCK_METHOD1(UninstallApp, int(const std::string &bundleName)); + MOCK_METHOD2( + GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); + MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); + MOCK_METHOD1(CancelWantSender, void(const sptr &sender)); + MOCK_METHOD1(GetPendingWantUid, int(const sptr &target)); + MOCK_METHOD1(GetPendingWantUserId, int(const sptr &target)); + MOCK_METHOD1(GetPendingWantBundleName, std::string(const sptr &target)); + MOCK_METHOD1(GetPendingWantCode, int(const sptr &target)); + MOCK_METHOD1(GetPendingWantType, int(const sptr &target)); + MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); + MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); + MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); + MOCK_METHOD5(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int32_t userId, int requestCode)); + MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); + MOCK_METHOD2(MoveMissionToSplitScreenStack, int(const MissionOption &primary, const MissionOption &secondary)); + MOCK_METHOD2( + ChangeFocusAbility, int(const sptr &lostFocusToken, const sptr &getFocusToken)); + MOCK_METHOD1(MinimizeMultiWindow, int(int missionId)); + MOCK_METHOD1(MaximizeMultiWindow, int(int missionId)); + MOCK_METHOD1(GetFloatingMissions, int(std::vector &list)); + MOCK_METHOD1(CloseMultiWindow, int(int missionId)); + MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); + MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); + MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); + MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + + MOCK_METHOD1(LockMissionForCleanup, int(int32_t missionId)); + MOCK_METHOD1(UnlockMissionForCleanup, int(int32_t missionId)); + + MOCK_METHOD1(RegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD1(UnRegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD2(RegisterMissionListener, int(const std::string &deviceId, + const sptr &listener)); + MOCK_METHOD2(UnRegisterMissionListener, int(const std::string &deviceId, + const sptr &listener)); + MOCK_METHOD3( + GetMissionInfos, int(const std::string& deviceId, int32_t numMax, std::vector &missionInfos)); + MOCK_METHOD3(GetMissionInfo, int(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo)); + MOCK_METHOD1(CleanMission, int(int32_t missionId)); + MOCK_METHOD0(CleanAllMissions, int()); + MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + + MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); + + int MoveMissionToEnd(const sptr &token, const bool nonFirst) override; + bool IsFirstInMission(const sptr &token) override; + int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override; + + int RemoveMission(int id) override; + + int RemoveStack(int id) override; + int PowerOff() override; + int PowerOn() override; + int LockMission(int missionId) override + { + return 0; + } + int UnlockMission(int missionId) override + { + return 0; + } + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + int GetMissionLockModeState() + { + return 0; + } + int UpdateConfiguration(const AppExecFwk::Configuration &config) + { + return 0; + } + + sptr AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) override + { + return nullptr; + } + + int ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) override + { + return 0; + } + + int GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) override + { + return 0; + } + + int GetMissionSnapshot( + const std::string& deviceId, const int32_t missionId, MissionSnapshot& snapshot) override + { + return 0; + } + + virtual int SetShowOnLockScreen(bool isAllow) override + { + return 0; + } + + virtual int ClearUpApplicationData(const std::string &bundleName) override + { + return 0; + } + + int ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, + int32_t missionId, const sptr &callback, AAFwk::WantParams &wantParams) + { + return 0; + } + + int ContinueAbility(const std::string &deviceId, int32_t missionId) + { + return 0; + } + + void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) + {} + + int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) + { + return 0; + } + + int StopSyncRemoteMissions(const std::string& devId) + { + return 0; + } + + int StartUser(int accountId) + { + return 0; + } + + int StopUser(int accountId, const sptr &callback) + { + return 0; + } + + int SetMissionLabel(const sptr &abilityToken, const std::string &label) + { + return 0; + } + + int GetMissionSnapshot(const int32_t missionId, MissionPixelMap &missionPixelMap) override + { + return 0; + } + + int GetAbilityRunningInfos(std::vector &info) override + { + return 0; + } + + int GetExtensionRunningInfos(int upperLimit, std::vector &info) override + { + return 0; + } + + int GetProcessRunningInfos(std::vector &info) override + { + return 0; + } + + int SetAbilityController( + const sptr &abilityController, bool imAStabilityTest) override + { + return 0; + } + + bool IsRunningInStabilityTest() override + { + return true; + } + + bool SendANRProcessID(int pid) override + { + return true; + } + + int RegisterSnapshotHandler(const sptr& handler) override + { + return 0; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } + + sptr abilityScheduler_ = nullptr; // kit interface used to schedule ability life + Want want_; + bool startAbility = false; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_SERVICEABILITY_MOCK_MANAGER_SERVICE_H diff --git a/frameworks/kits/ability/ability_runtime/test/moduletest/ability_caller_fw_module_test.cpp b/frameworks/kits/ability/ability_runtime/test/moduletest/ability_caller_fw_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c1f1449aa9198d094cfdbb599a51bb426d89ed1 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/moduletest/ability_caller_fw_module_test.cpp @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_thread.h" +#define private public +#define protected public +#include "ability_context_impl.h" +#include "caller_callback.h" +#undef private +#undef protected +#include "ability_context.h" +#include "ability_loader.h" +#include "ability_manager_client.h" +#include "mock_serviceability_manager_service.h" +#include "system_ability_definition.h" +#include "sys_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; +using namespace OHOS; +using namespace AAFwk; + +namespace { +const std::string ACE_SERVICE_ABILITY_NAME = "AceServiceAbility"; +} +class AbilityCallerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static constexpr int TEST_WAIT_TIME = 500 * 1000; // 500 ms +public: + std::unique_ptr context_ = nullptr; +}; + +void AbilityCallerTest::SetUpTestCase(void) +{ + OHOS::sptr abilityObject = new (std::nothrow) MockServiceAbilityManagerService(); + + auto sysMgr = OHOS::DelayedSingleton::GetInstance(); + if (sysMgr == NULL) { + GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager"; + return; + } + + sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject); + + auto task = []()->Ability* { return new (std::nothrow) Ability; }; + + AbilityLoader::GetInstance().RegisterAbility(ACE_SERVICE_ABILITY_NAME, task); +} + +void AbilityCallerTest::TearDownTestCase(void) +{} + +void AbilityCallerTest::SetUp(void) +{ + context_ = std::make_unique(); +} + +void AbilityCallerTest::TearDown(void) +{} + +/** + * @tc.number: AaFwk_Ability_StartAbility_0100 + * @tc.name: AbilityFwk + * @tc.desc: Ability caller to process StartAbility, and the result is success. + */ +HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0100, Function | MediumTest | Level1) +{ + std::shared_ptr application = std::make_shared(); + sptr abilityToken = sptr(new AbilityThread()); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AppExecFwk::AbilityType::SERVICE; + abilityInfo->name = "DemoAbilityNameA"; + abilityInfo->bundleName = "DemoBundleNameA"; + abilityInfo->deviceId = "DemoDeviceIdA"; + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, abilityToken); + + AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr); + + Want want; + want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + EXPECT_FALSE(callback->IsCallBack()); + + ErrCode ret = context_->StartAbility(want, callback); + EXPECT_TRUE(ret == 0); + + AppExecFwk::ElementName element("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + sptr callRemoteObject = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + context_->localCallContainer_->OnAbilityConnectDone(element, callRemoteObject, ERR_OK); + EXPECT_TRUE(callback->IsCallBack()); +} + +/** + * @tc.number: AaFwk_Ability_StartAbility_0200 + * @tc.name: AbilityFwk + * @tc.desc: Ability caller to process StartAbility, and the result is fail because call back is nullptr. + */ +HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0200, Function | MediumTest | Level1) +{ + Want want; + want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + + ErrCode ret = context_->StartAbility(want, nullptr); + EXPECT_FALSE(ret == 0); +} + +/** + * @tc.number: AaFwk_Ability_StartAbility_0300 + * @tc.name: AbilityFwk + * @tc.desc: Ability caller to process StartAbility, and the result is fail because the element of want is empty. + */ +HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0300, Function | MediumTest | Level1) +{ + Want want; + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + EXPECT_FALSE(callback->IsCallBack()); + + ErrCode ret = context_->StartAbility(want, callback); + EXPECT_FALSE(ret == 0); +} + +/** + * @tc.number: AaFwk_Ability_ReleaseAbility_0100 + * @tc.name: AbilityFwk + * @tc.desc: Ability Caller to process ReleaseAbility, and the result is success. + */ +HWTEST_F(AbilityCallerTest, AaFwk_Ability_ReleaseAbility_0100, Function | MediumTest | Level1) +{ + std::shared_ptr application = std::make_shared(); + sptr abilityToken = sptr(new AbilityThread()); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AppExecFwk::AbilityType::SERVICE; + abilityInfo->name = "DemoAbilityNameA"; + abilityInfo->bundleName = "DemoBundleNameA"; + abilityInfo->deviceId = "DemoDeviceIdA"; + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, abilityToken); + + AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr); + + Want want; + want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + + ErrCode ret = context_->StartAbility(want, callback); + EXPECT_TRUE(ret == 0); + + ret = context_->ReleaseAbility(callback); + EXPECT_TRUE(ret == 0); +} + +/** + * @tc.number: AaFwk_Ability_ReleaseAbility_0200 + * @tc.name: AbilityFwk + * @tc.desc: Ability Caller to process ReleaseAbility, and the result is fail because has no caller record. + */ +HWTEST_F(AbilityCallerTest, AaFwk_Ability_ReleaseAbility_0200, Function | MediumTest | Level1) +{ + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + + ErrCode ret = context_->ReleaseAbility(callback); + EXPECT_FALSE(ret == 0); +} + +/** + * @tc.number: AaFwk_Ability_OnCallStubDied_0100 + * @tc.name: AbilityFwk + * @tc.desc: Ability Caller to process OnCallStubDied, and the result is success. + */ +HWTEST_F(AbilityCallerTest, AaFwk_Ability_OnCallStubDied_0100, Function | MediumTest | Level1) +{ + std::shared_ptr application = std::make_shared(); + sptr abilityToken = sptr(new AbilityThread()); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AppExecFwk::AbilityType::SERVICE; + abilityInfo->name = "DemoAbilityNameA"; + abilityInfo->bundleName = "DemoBundleNameA"; + abilityInfo->deviceId = "DemoDeviceIdA"; + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, abilityToken); + + AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr); + + Want want; + want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + + std::shared_ptr callback = std::make_shared(); + bool isSetOnReleaseCalled = false; + callback->SetCallBack([](const sptr &) {}); + callback->SetOnRelease([&isSetOnReleaseCalled](const std::string &result) mutable { + GTEST_LOG_(ERROR) << "OnRelease-----------" << result; + EXPECT_TRUE(result == "died"); + isSetOnReleaseCalled = true; + }); + + ErrCode ret = context_->StartAbility(want, callback); + EXPECT_TRUE(ret == 0); + + std::shared_ptr localCallRecord; + AppExecFwk::ElementName elementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + context_->localCallContainer_->GetCallLocalreocrd(elementName, localCallRecord); + + sptr callRemoteObject = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + localCallRecord->OnCallStubDied(callRemoteObject); + EXPECT_TRUE(isSetOnReleaseCalled); +} + +/** + * @tc.number: AaFwk_Ability_OnCallStubDied_0200 + * @tc.name: AbilityFwk + * @tc.desc: Ability Caller to process OnCallStubDied, and the result is fail because no caller. + */ +HWTEST_F(AbilityCallerTest, AaFwk_Ability_OnCallStubDied_0200, Function | MediumTest | Level1) +{ + std::shared_ptr callback = std::make_shared(); + bool isSetOnReleaseCalled = false; + callback->SetOnRelease([&isSetOnReleaseCalled](const std::string &result) mutable { + GTEST_LOG_(ERROR) << "OnRelease-----------" << result; + isSetOnReleaseCalled = true; + }); + + AppExecFwk::ElementName elementName ("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + + sptr callRemoteObject = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + localCallRecord.OnCallStubDied(callRemoteObject); + EXPECT_FALSE(isSetOnReleaseCalled); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/BUILD.gn b/frameworks/kits/ability/native/BUILD.gn index 2db54135e167b09cb89ab8c4252287eca78cfc62..61691f2f0b031b9b65e54410d5c4bc87e4c5a66d 100644 --- a/frameworks/kits/ability/native/BUILD.gn +++ b/frameworks/kits/ability/native/BUILD.gn @@ -13,7 +13,6 @@ import("//build/ohos.gni") SUBSYSTEM_DIR = "//foundation/aafwk/standard/frameworks/kits/ability/native" -SUBSYSTEM_APPEXEXFWK_DIR = "//foundation/appexecfwk/standard" INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits" config("ability_config") { @@ -22,18 +21,20 @@ config("ability_config") { "${INNERKITS_PATH}/base/include", "//utils/native/base/include", "${SUBSYSTEM_DIR}/include", - "${SUBSYSTEM_APPEXEXFWK_DIR}/kits/appkit/native/app/include", - "${SUBSYSTEM_APPEXEXFWK_DIR}/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "${INNERKITS_PATH}/want/include/ohos/aafwk/content", "${INNERKITS_PATH}/ability_manager/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/standard/common/log/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/app", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/app", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/app/native/app/include", + "//foundation/aafwk/standard/services/common/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//base/global/resmgr_standard/interfaces/innerkits/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility", @@ -42,13 +43,14 @@ config("ability_config") { "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/remote_register_service", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/distributed", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include/continuation", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/kits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/dispatcher", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/task", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/threading", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include/task", + "//foundation/aafwk/standard/common/task_dispatcher/include/dispatcher", + "//foundation/aafwk/standard/common/task_dispatcher/include/task", + "//foundation/aafwk/standard/common/task_dispatcher/include/threading", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include/task", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", ] @@ -66,35 +68,67 @@ config("ability_public_config") { visibility = [ ":*" ] include_dirs = [ "${INNERKITS_PATH}/base/include", - "//foundation/appexecfwk/standard/kits/appkit/native", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/app", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime", + "//foundation/aafwk/standard/frameworks/kits/appkit/native", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/app", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", "${SUBSYSTEM_DIR}/include", "//third_party/libuv/include", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/context", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context", "//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/remote_register_service", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/distributed", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include/continuation", "//base/global/resmgr_standard/interfaces/innerkits/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/kits", - "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", "//foundation/windowmanager/interfaces/innerkits/wm", + "//foundation/windowmanager/interfaces/kits/napi/window_runtime/window_napi", + "//third_party/jsoncpp/include", + "//third_party/json/include", ] } +ohos_shared_library("static_subscriber_ipc") { + include_dirs = [ + "${SUBSYSTEM_DIR}/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", + ] + + sources = [ + "${SUBSYSTEM_DIR}/src/static_subscriber_proxy.cpp", + "${SUBSYSTEM_DIR}/src/static_subscriber_stub.cpp", + ] + + deps = [ + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:want", + "ces_standard:cesfwk_innerkits", + "ipc:ipc_core", + ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} + ohos_shared_library("abilitykit_native") { include_dirs = [ - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_dataability", - "${SUBSYSTEM_DIR}/src/ability_runtime/window", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_rdb/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/include", "//base/global/i18n_standard/frameworks/intl/include", ] sources = [ - "${SUBSYSTEM_APPEXEXFWK_DIR}/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp", + "${INNERKITS_PATH}/app_manager/src/appmgr/process_info.cpp", "${SUBSYSTEM_DIR}/src/ability.cpp", "${SUBSYSTEM_DIR}/src/ability_context.cpp", "${SUBSYSTEM_DIR}/src/ability_handler.cpp", @@ -115,25 +149,29 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/data_ability_result.cpp", "${SUBSYSTEM_DIR}/src/data_uri_utils.cpp", "${SUBSYSTEM_DIR}/src/extension.cpp", - "${SUBSYSTEM_DIR}/src/extension_base.cpp", "${SUBSYSTEM_DIR}/src/extension_impl.cpp", + "${SUBSYSTEM_DIR}/src/extension_module_loader.cpp", "${SUBSYSTEM_DIR}/src/form_extension.cpp", - "${SUBSYSTEM_DIR}/src/form_runtime/form_extension_provider_client.cpp", - "${SUBSYSTEM_DIR}/src/form_runtime/js_form_extension.cpp", - "${SUBSYSTEM_DIR}/src/form_runtime/js_form_extension_context.cpp", - "${SUBSYSTEM_DIR}/src/js_service_extension.cpp", - "${SUBSYSTEM_DIR}/src/js_service_extension_context.cpp", - "${SUBSYSTEM_DIR}/src/service_extension.cpp", #"${SUBSYSTEM_DIR}/src/dummy_data_ability_predicates.cpp", #"${SUBSYSTEM_DIR}/src/dummy_result_set.cpp", #"${SUBSYSTEM_DIR}/src/dummy_values_bucket.cpp", "${SUBSYSTEM_DIR}/src/form_js_event_handler.cpp", "${SUBSYSTEM_DIR}/src/form_provider_client.cpp", + "${SUBSYSTEM_DIR}/src/form_runtime/form_extension_provider_client.cpp", + "${SUBSYSTEM_DIR}/src/form_runtime/js_form_extension.cpp", + "${SUBSYSTEM_DIR}/src/form_runtime/js_form_extension_context.cpp", + "${SUBSYSTEM_DIR}/src/js_service_extension.cpp", + "${SUBSYSTEM_DIR}/src/js_service_extension_context.cpp", + "${SUBSYSTEM_DIR}/src/js_static_subscriber_extension.cpp", + "${SUBSYSTEM_DIR}/src/js_static_subscriber_extension_context.cpp", "${SUBSYSTEM_DIR}/src/mission_information.cpp", "${SUBSYSTEM_DIR}/src/new_ability_impl.cpp", "${SUBSYSTEM_DIR}/src/page_ability_impl.cpp", "${SUBSYSTEM_DIR}/src/service_ability_impl.cpp", + "${SUBSYSTEM_DIR}/src/service_extension.cpp", + "${SUBSYSTEM_DIR}/src/static_subscriber_extension.cpp", + "${SUBSYSTEM_DIR}/src/static_subscriber_stub_imp.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_start_setting.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/launch_param.cpp", @@ -142,7 +180,6 @@ ohos_shared_library("abilitykit_native") { # "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp", "${SUBSYSTEM_DIR}/src/continuation/distributed/continuation_handler.cpp", "${SUBSYSTEM_DIR}/src/continuation/distributed/continuation_manager.cpp", - "${SUBSYSTEM_DIR}/src/continuation/distributed/distributed_client.cpp", "${SUBSYSTEM_DIR}/src/continuation/distributed/reverse_continuation_scheduler_primary.cpp", "${SUBSYSTEM_DIR}/src/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp", "${SUBSYSTEM_DIR}/src/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp", @@ -158,29 +195,30 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/continuation/remote_register_service/continuation_register_manager_proxy.cpp", "${SUBSYSTEM_DIR}/src/continuation/remote_register_service/remote_register_service_proxy.cpp", "${SUBSYSTEM_DIR}/src/continuation/remote_register_service/remote_register_service_stub.cpp", + "${SUBSYSTEM_DIR}/src/distributed_ability_runtime/distributed_client.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/service_extension_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/static_subscriber_extension_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_deal.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/sys_mgr_client.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_start_options.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/context/context_impl.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/extension_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/form_extension_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/service_extension_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/sys_mgr_client.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/js_utils.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/src/js_utils.cpp", - #"//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb/napi_rdb_predicates.cpp", + #"//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_rdb/napi_rdb_predicates.cpp", "${SUBSYSTEM_DIR}/src/ability_runtime/js_ability.cpp", "${SUBSYSTEM_DIR}/src/ability_runtime/js_ability_context.cpp", + "${SUBSYSTEM_DIR}/src/ability_runtime/js_caller_complex.cpp", "${SUBSYSTEM_DIR}/src/ability_runtime/js_window_stage.cpp", - "${SUBSYSTEM_DIR}/src/ability_runtime/window/js_window.cpp", - "${SUBSYSTEM_DIR}/src/ability_runtime/window/js_window_manager.cpp", - "${SUBSYSTEM_DIR}/src/ability_runtime/window/js_window_utils.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_dataability/napi_data_ability_predicates.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb/napi_result_set.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/src/napi_data_ability_predicates.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/src/napi_result_set.cpp", ] configs = [ ":ability_config" ] public_configs = [ @@ -189,32 +227,35 @@ ohos_shared_library("abilitykit_native") { ] deps = [ + ":static_subscriber_ipc", "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager:dataobs_manager", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-common", - "//foundation/windowmanager/wm:libwmutil", "//third_party/icu/icu4c:shared_icuuc", ] external_deps = [ - "aafwk_standard:ability_context_native", - "aafwk_standard:runtime", - "appexecfwk_standard:fmskit_native", + "ability_runtime:ability_context_native", + "ability_runtime:app_manager", + "ability_runtime:napi_base_context", + "ability_runtime:runtime", "bytrace_standard:bytrace_core", - "hiviewdfx_hilog_native:libhilog", + "ces_standard:cesfwk_innerkits", + "form_runtime:fmskit_native", + "form_runtime:form_manager", "ipc:ipc_core", "ipc_js:rpc", "multimodalinput_base:libmmi-client", @@ -227,13 +268,16 @@ ohos_shared_library("abilitykit_native") { public_deps = [ "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/graphic/standard:libwmclient", + "//foundation/windowmanager/interfaces/kits/napi/window_runtime:window_native_kit", "//foundation/windowmanager/wm:libwm", ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } ohos_shared_library("dummy_classes") { @@ -257,5 +301,29 @@ ohos_shared_library("dummy_classes") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" +} + +ohos_shared_library("service_extension_module") { + include_dirs = + [ "//foundation/aafwk/standard/frameworks/kits/ability/native/include" ] + + sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/src/service_extension_module_loader.cpp" ] + + configs = [ ":ability_config" ] + public_configs = [ ":ability_public_config" ] + + deps = [ + ":abilitykit_native", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" } diff --git a/frameworks/kits/ability/native/include/ability.h b/frameworks/kits/ability/native/include/ability.h old mode 100644 new mode 100755 index b078ab08d9394e91e7c300d9abb871b330dc92ce..356477caed653eeaa59ec287dcb40d94c4858a2b --- a/frameworks/kits/ability/native/include/ability.h +++ b/frameworks/kits/ability/native/include/ability.h @@ -107,7 +107,7 @@ public: int TerminateAbility(Want &want); /** - * @brief By binding an action, you can set different action parameters in Intent to present different initial + * @brief By binding an action, you can set different action parameters in want to present different initial * pages. You must register actions in the profile file. * * @param action Indicates the action to bind. @@ -135,8 +135,10 @@ public: * @brief Destroys this Page or Service ability. * After a Page or Service ability performs all operations, it can use this method to destroy itself * to free up memory. This method can be called only after the ability is initialized. + * + * @return errCode ERR_OK on success, others on failure. */ - virtual void TerminateAbility() final; + virtual ErrCode TerminateAbility() final; /** * @brief Obtains the Lifecycle object of the current ability. @@ -172,8 +174,10 @@ public: * * @param want information of other ability * @param requestCode request code for abilityMS to return result + * + * @return errCode ERR_OK on success, others on failure. */ - virtual void StartAbilityForResult(const Want &want, int requestCode) final; + virtual ErrCode StartAbilityForResult(const Want &want, int requestCode) final; /** * Starts an ability with specific start settings and returns the execution result when the ability is destroyed. @@ -185,21 +189,25 @@ public: * @param requestCode Indicates the request code returned after the ability is started. You can define the request * code to identify the results returned by abilities. The value ranges from 0 to 65535. * @param abilityStartSetting Indicates the setting ability used to start. + * + * @return errCode ERR_OK on success, others on failure. */ - virtual void StartAbilityForResult( + virtual ErrCode StartAbilityForResult( const Want &want, int requestCode, AbilityStartSetting abilityStartSetting) final; /** * Starts a new ability with specific start settings. * A Page or Service ability uses this method to start a specific ability. * The system locates the target ability from installed abilities based on - * the value of the intent parameter and then starts it. You can specify the - * ability to start using the intent parameter. + * the value of the want parameter and then starts it. You can specify the + * ability to start using the want parameter. * * @param want Indicates the ability to start. * @param abilityStartSetting Indicates the setting ability used to start. + * + * @return errCode ERR_OK on success, others on failure. */ - void StartAbility(const Want &want, AbilityStartSetting abilityStartSetting); + ErrCode StartAbility(const Want &want, AbilityStartSetting abilityStartSetting); // lifecycle callback virtual void Init(const std::shared_ptr &abilityInfo, @@ -379,7 +387,7 @@ public: * * @param windowOption Indicates the window option defined by the user. */ - virtual void InitWindow(Rosen::WindowType winType); + virtual void InitWindow(Rosen::WindowType winType, int32_t displayId, sptr option); /** * @brief Get the window belong to the ability. @@ -842,13 +850,15 @@ public: /** * @brief A Page or Service ability uses this method to start a specific ability. The system locates the target - * ability from installed abilities based on the value of the intent parameter and then starts it. You can specify - * the ability to start using the intent parameter. + * ability from installed abilities based on the value of the want parameter and then starts it. You can specify + * the ability to start using the want parameter. * - * @param intent Indicates the ability to start. + * @param want Indicates the ability to start. + * + * @return errCode ERR_OK on success, others on failure. */ using AbilityContext::StartAbility; - virtual void StartAbility(const Want &want) final; + virtual ErrCode StartAbility(const Want &want) final; /** * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. @@ -866,8 +876,10 @@ public: * * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. */ - void DisconnectAbility(const sptr &conn) override; + ErrCode DisconnectAbility(const sptr &conn) override; /** * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. @@ -1274,6 +1286,22 @@ public: */ std::weak_ptr GetContinuationRegisterManager(); + /** + * @brief Prepare user data of local Ability. + * + * @param wantParams Indicates the user data to be saved. + * @return If the ability is willing to continue and data saved successfully, it returns true; + * otherwise, it returns false. + */ + virtual bool OnContinue(WantParams &wantParams); + + /** + * @brief Get page ability stack info. + * + * @return A string represents page ability stack info, empty if failed; + */ + virtual std::string GetContentInfo(); + /** * @brief Migrates this ability to the given device on the same distributed network. The ability to migrate and its * ability slices must implement the IAbilityContinuation interface. @@ -1357,6 +1385,12 @@ public: * @return None. */ void SetSceneListener(const sptr &listener); + + /** + * @brief request a remote object of callee from this ability. + * @return Returns the remote object of callee. + */ + virtual sptr CallRequest(); protected: /** @@ -1442,7 +1476,6 @@ private: std::shared_ptr continuationHandler_ = nullptr; std::shared_ptr continuationManager_ = nullptr; std::shared_ptr continuationRegisterManager_ = nullptr; - std::shared_ptr configuration_ = nullptr; std::shared_ptr abilityInfo_ = nullptr; std::shared_ptr handler_ = nullptr; std::shared_ptr lifecycle_ = nullptr; @@ -1452,7 +1485,7 @@ private: std::shared_ptr abilityWindow_ = nullptr; std::shared_ptr setWant_ = nullptr; sptr reverseContinuationSchedulerReplica_ = nullptr; - + bool bWindowFocus_ = false; int compatibleVersion_ = 0; @@ -1464,10 +1497,10 @@ private: // Keep consistent with DMS defines. Used to callback to DMS. static const std::string DMS_SESSION_ID; - // The originating deviceId passed by DMS using intent param. + // The originating deviceId passed by DMS using want param. static const std::string DMS_ORIGIN_DEVICE_ID; - // If session id cannot get from intent, assign it as default. + // If session id cannot get from want, assign it as default. static const int DEFAULT_DMS_SESSION_ID; std::vector lostedByReconnectTempForms_; @@ -1484,7 +1517,6 @@ private: static const int32_t RELEASE_FORM = 8; static const int32_t RELEASE_CACHED_FORM = 9; static const int64_t MIN_NEXT_TIME = 5; - static const std::map convertWindowModeMap_; private: /** diff --git a/frameworks/kits/ability/native/include/ability_context.h b/frameworks/kits/ability/native/include/ability_context.h index cd9865589976bc5c1f5ec4fdf5bacf86f7826189..946802351549154f5d4e703b7c9cecb57ed1f6d1 100644 --- a/frameworks/kits/ability/native/include/ability_context.h +++ b/frameworks/kits/ability/native/include/ability_context.h @@ -20,8 +20,6 @@ #include "context_container.h" #include "data_ability_helper.h" -#include "distributed_sched_interface.h" -#include "distributed_sched_proxy.h" namespace OHOS { namespace AppExecFwk { @@ -135,9 +133,10 @@ public: * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE * template. * + * @return errCode ERR_OK on success, others on failure. */ using ContextContainer::StartAbility; - void StartAbility(const AAFwk::Want &Want, int requestCode) override; + ErrCode StartAbility(const AAFwk::Want &Want, int requestCode) override; /** * @brief Starts a new ability with special ability start setting. @@ -147,8 +146,9 @@ public: * code to identify the results returned by abilities. The value ranges from 0 to 65535. * @param abilityStartSetting Indicates the special start setting used in starting ability. * + * @return errCode ERR_OK on success, others on failure. */ - void StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) override; + ErrCode StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) override; /** * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult @@ -157,14 +157,16 @@ public: * * @param requestCode Indicates the request code passed for starting the ability. * + * @return errCode ERR_OK on success, others on failure. */ - void TerminateAbility(int requestCode) override; + ErrCode TerminateAbility(int requestCode) override; /** * @brief Destroys the current ability. * + * @return errCode ERR_OK on success, others on failure. */ - void TerminateAbility() override; + ErrCode TerminateAbility() override; /** * @brief Obtains the bundle name of the ability that called the current ability. @@ -206,8 +208,10 @@ public: * * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. */ - void DisconnectAbility(const sptr &conn) override; + ErrCode DisconnectAbility(const sptr &conn) override; /** * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. @@ -695,19 +699,8 @@ public: void SetShowOnLockScreen(bool isAllow) override; friend DataAbilityHelper; - -public: static int ABILITY_CONTEXT_DEFAULT_REQUEST_CODE; -private: - /** - * @brief Get Current Ability Type - * - * @return Current Ability Type - */ - AppExecFwk::AbilityType GetAbilityInfoType(); - void GetPermissionDes(const std::string &permissionName, std::string &des); - protected: sptr GetToken() override; sptr token_; @@ -717,8 +710,16 @@ protected: std::string callingBundleName_; std::string callingAbilityName_; std::map, sptr> abilityConnectionMap_; -}; +private: + /** + * @brief Get Current Ability Type + * + * @return Current Ability Type + */ + AppExecFwk::AbilityType GetAbilityInfoType(); + void GetPermissionDes(const std::string &permissionName, std::string &des); +}; } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_CONTEXT_H diff --git a/frameworks/kits/ability/native/include/ability_impl.h b/frameworks/kits/ability/native/include/ability_impl.h index c1240698e951fdff2bafee00490f5f76c13a896c..cf2afeb8a7be214080708c16877ed46f0aef3014 100755 --- a/frameworks/kits/ability/native/include/ability_impl.h +++ b/frameworks/kits/ability/native/include/ability_impl.h @@ -351,6 +351,8 @@ public: */ virtual void NotifyContinuationResult(const int32_t result); + bool IsStageBasedModel() const; + int GetCompatibleVersion(); void AfterUnFocused(); @@ -428,6 +430,7 @@ protected: PacMap &GetRestoreData(); + bool isStageBasedModel_ = false; int lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; sptr token_; std::shared_ptr ability_; @@ -469,7 +472,6 @@ private: std::shared_ptr abilityLifecycleCallbacks_; std::shared_ptr applactionImpl_; std::shared_ptr contextDeal_; - std::shared_ptr configuration_ = nullptr; private: /** diff --git a/frameworks/kits/ability/native/include/ability_local_record.h b/frameworks/kits/ability/native/include/ability_local_record.h index 5352b51e43460b9512893976fca72931c92fd496..aedd0e9222ff6ee0384eb50fdd2fe869d9edb4ee 100644 --- a/frameworks/kits/ability/native/include/ability_local_record.h +++ b/frameworks/kits/ability/native/include/ability_local_record.h @@ -123,7 +123,6 @@ public: * @return None. */ void SetCompatibleVersion(int compatibleVersion); - private: std::shared_ptr abilityInfo_ = nullptr; sptr token_; diff --git a/frameworks/kits/ability/native/include/ability_process.h b/frameworks/kits/ability/native/include/ability_process.h index e8a4bb40235cc13c4deb653d1bd0df420c9334bc..0cdd83475fb3a179810996cb3ffa013479d810da 100644 --- a/frameworks/kits/ability/native/include/ability_process.h +++ b/frameworks/kits/ability/native/include/ability_process.h @@ -32,7 +32,7 @@ public: virtual ~AbilityProcess(); static std::shared_ptr GetInstance(); - void StartAbility(Ability *ability, CallAbilityParam param, CallbackInfo callbackInfo); + ErrCode StartAbility(Ability *ability, CallAbilityParam param, CallbackInfo callbackInfo); void OnAbilityResult(Ability *ability, int requestCode, int resultCode, const Want &resultData); void RequestPermissionsFromUser(Ability *ability, CallAbilityPermissionParam ¶m, CallbackInfo callbackInfo); diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h old mode 100644 new mode 100755 index 54cc070f8c2bd26287aad9f4f7ec81cccd9b0c1c..59db15887636c01c21f82e3bc06e5fdc1d0fc712 --- a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h @@ -31,12 +31,13 @@ using AbilityInfo = AppExecFwk::AbilityInfo; using OHOSApplication = AppExecFwk::OHOSApplication; using Want = AppExecFwk::Want; using AbilityStartSetting = AppExecFwk::AbilityStartSetting; +using Configuration = AppExecFwk::Configuration; class JsAbility : public Ability { public: - static Ability* Create(const std::unique_ptr& runtime); + static Ability *Create(const std::unique_ptr &runtime); - JsAbility(JsRuntime& jsRuntime); + JsAbility(JsRuntime &jsRuntime); ~JsAbility() override; void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, @@ -51,19 +52,26 @@ public: void OnForeground(const Want &want) override; void OnBackground() override; + bool OnContinue(WantParams &wantParams) override; + void OnConfigurationUpdated(const Configuration &configuration) override; + void OnNewWant(const Want &want) override; void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; void OnRequestPermissionsFromUserResult( int requestCode, const std::vector &permissions, const std::vector &grantResults) override; + sptr CallRequest() override; + protected: - void DoOnForeground(const Want& want) override; + void DoOnForeground(const Want &want) override; private: - void CallObjectMethod(const char* name, NativeValue* const* argv = nullptr, size_t argc = 0); + void CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0); std::unique_ptr CreateAppWindowStage(); + void GetPageStackFromWant(const Want &want, std::string &pageStack); - JsRuntime& jsRuntime_; + JsRuntime &jsRuntime_; + std::shared_ptr shellContextRef_; std::unique_ptr jsAbilityObj_; }; } // namespace AbilityRuntime diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h b/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h old mode 100644 new mode 100755 index 66fbf92e6ae91122af5042a06fe9d5794d4fd0f0..2058b5c0756ec9e6e14dfd971448a0e3b03f826f --- a/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h @@ -22,9 +22,9 @@ #include "ability_connect_callback.h" #include "foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/include/ability_context.h" +#include "js_runtime.h" #include "event_handler.h" -class NativeEngine; class NativeObject; class NativeReference; class NativeValue; @@ -39,13 +39,21 @@ public: static void Finalizer(NativeEngine* engine, void* data, void* hint); static NativeValue* StartAbility(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* StartAbilityWithAccount(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* StartAbilityByCall(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* StartAbilityForResult(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* StartAbilityForResultWithAccount(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* ConnectAbility(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* ConnectAbilityWithAccount(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* DisconnectAbility(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* TerminateSelf(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* TerminateSelfWithResult(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* RequestPermissionsFromUser(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* RestoreWindowStage(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* SetMissionLabel(NativeEngine* engine, NativeCallbackInfo* info); + + static void ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, + const std::shared_ptr &config); std::shared_ptr GetAbilityContext() { @@ -54,18 +62,25 @@ public: private: NativeValue* OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnStartAbilityWithAccount(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnStartAbilityByCall(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnStartAbilityForResult(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnStartAbilityForResultWithAccount(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnTerminateSelfWithResult(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnConnectAbility(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnConnectAbilityWithAccount(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnDisconnectAbility(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnTerminateSelf(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnRequestPermissionsFromUser(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnRestoreWindowStage(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnSetMissionLabel(NativeEngine& engine, NativeCallbackInfo& info); static bool UnWrapWant(NativeEngine& engine, NativeValue* argv, AAFwk::Want& want); static NativeValue* WrapWant(NativeEngine& engine, const AAFwk::Want& want); static bool UnWrapAbilityResult(NativeEngine& engine, NativeValue* argv, int& resultCode, AAFwk::Want& want); static NativeValue* WrapAbilityResult(NativeEngine& engine, const int& resultCode, const AAFwk::Want& want); + static NativeValue* WrapPermissionRequestResult(NativeEngine& engine, + const std::vector &permissions, const std::vector &grantResults); std::weak_ptr context_; int curRequestCode_ = 0; @@ -75,7 +90,7 @@ NativeValue* CreateJsAbilityContext(NativeEngine& engine, std::shared_ptr &remoteObject, int resultCode) override; @@ -87,7 +102,7 @@ public: void CallJsFailed(int32_t errorCode); private: NativeValue* ConvertElement(const AppExecFwk::ElementName &element); - std::unique_ptr engine_; + NativeEngine& engine_; std::unique_ptr jsConnectionObject_ = nullptr; }; @@ -106,9 +121,9 @@ struct KeyCompare { } }; -static std::map, KeyCompare> abilityConnects_; +static std::map, KeyCompare> abilityConnects_; static int64_t g_serialNumber = 0; static std::shared_ptr handler_ = nullptr; } // namespace AbilityRuntime } // namespace OHOS -#endif // ABILITY_RUNTIME_JS_ABILITY_CONTEXT_H +#endif // ABILITY_RUNTIME_JS_ABILITY_CONTEXT_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_caller_complex.h b/frameworks/kits/ability/native/include/ability_runtime/js_caller_complex.h new file mode 100644 index 0000000000000000000000000000000000000000..0bd343d3464b0a2d9d87bc7888a49caf9cf1cce4 --- /dev/null +++ b/frameworks/kits/ability/native/include/ability_runtime/js_caller_complex.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_JS_CALLERCOMPLEX_H +#define ABILITY_RUNTIME_JS_CALLERCOMPLEX_H + +#include +#include + +#include "iremote_object.h" +#include "foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/include/ability_context.h" + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsCallerComplex( + NativeEngine& engine, std::shared_ptr context, sptr callee, + std::shared_ptr callerCallBack); + +NativeValue* CreateJsCalleeRemoteObject(NativeEngine& engine, sptr callee); +} // AbilityRuntime +} // OHOS +#endif // ABILITY_RUNTIME_JS_CALLERCOMPLEX_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_window_stage.h b/frameworks/kits/ability/native/include/ability_runtime/js_window_stage.h index 4ae0cc1be21312afb994b8aad1f78797ab7d1a94..a74eb1804418881a93f85bb5805de320468e64c8 100644 --- a/frameworks/kits/ability/native/include/ability_runtime/js_window_stage.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_window_stage.h @@ -39,6 +39,8 @@ public: static NativeValue* GetMainWindow(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* On(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* Off(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* LoadContent(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetWindowMode(NativeEngine* engine, NativeCallbackInfo* info); virtual void AfterForeground() override; virtual void AfterBackground() override; virtual void AfterFocused() override; @@ -49,7 +51,8 @@ private: NativeValue* OnGetMainWindow(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnEvent(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OffEvent(NativeEngine& engine, NativeCallbackInfo& info); - + NativeValue* OnLoadContent(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetWindowMode(NativeEngine& engine, NativeCallbackInfo& info); enum WindowStageEventType { VISIBLE = 1, FOCUSED, @@ -61,6 +64,7 @@ private: std::shared_ptr windowScene_; NativeValue* object_ = nullptr; NativeEngine* engine_ = nullptr; + void* contentStorage_ = nullptr; sptr lifecycleListener_ = nullptr; std::map, int> eventCallbackMap_; bool regLifeCycleListenerFlag_ = false; diff --git a/frameworks/kits/ability/native/include/ability_thread.h b/frameworks/kits/ability/native/include/ability_thread.h index 7a5176453329edc9f2674068a9f7c3ec5d148649..2b870321f205bc52bf9e4ba1571d8da954edc34a 100644 --- a/frameworks/kits/ability/native/include/ability_thread.h +++ b/frameworks/kits/ability/native/include/ability_thread.h @@ -394,8 +394,18 @@ public: * @return Returns true on success, others on failure. */ bool CheckObsPermission(); + + /** + * @brief Dump ability runner info. + * + * @param runnerInfo ability runner info. + */ + void DumpAbilityInfo(std::vector &info); - std::vector> ExecuteBatch(const std::vector> &operations); + sptr CallRequest(); + + std::vector> ExecuteBatch( + const std::vector> &operations); private: /** * @description: Create the abilityname. diff --git a/frameworks/kits/ability/native/include/ability_window.h b/frameworks/kits/ability/native/include/ability_window.h index c69f8abda961bf665d39f1a1b06188b551fc977d..69b5005901dfde25e5486ec41c169991c16cc28b 100644 --- a/frameworks/kits/ability/native/include/ability_window.h +++ b/frameworks/kits/ability/native/include/ability_window.h @@ -51,7 +51,7 @@ public: */ bool InitWindow(Rosen::WindowType winType, std::shared_ptr &abilityContext, - sptr &listener); + sptr &listener, int32_t displayId, sptr option); /** * @brief Called when this ability is started. diff --git a/frameworks/kits/ability/native/include/continuation/distributed/continuation_manager.h b/frameworks/kits/ability/native/include/continuation/distributed/continuation_manager.h index 2cf3a35a47bff6fb87c463c3dca489a44e655d5e..e47be5e1a0bcd82880db519826b7f1307e6e3561 100644 --- a/frameworks/kits/ability/native/include/continuation/distributed/continuation_manager.h +++ b/frameworks/kits/ability/native/include/continuation/distributed/continuation_manager.h @@ -51,7 +51,11 @@ public: bool StartContinuation(); - bool OnContinue(WantParams &wantParams); + int32_t OnContinue(WantParams &wantParams); + + int32_t OnStartAndSaveData(WantParams &wantParams); + + int32_t OnContinueAndGetContent(WantParams &wantParams); bool SaveData(WantParams &saveData); @@ -97,6 +101,8 @@ private: bool DoRestoreFromRemote(const WantParams &restoreData); + bool GetContentInfo(WantParams &wantParams); + sptr continueToken_ = nullptr; std::weak_ptr ability_; std::weak_ptr abilityInfo_; diff --git a/frameworks/kits/ability/native/include/continuation/distributed/distributed_errors.h b/frameworks/kits/ability/native/include/continuation/distributed/distributed_errors.h index 87c236ab3e9d6896e913eb40e930a5762237c58f..a00899655af79d45eb85ef178e195a9e2a08f58c 100644 --- a/frameworks/kits/ability/native/include/continuation/distributed/distributed_errors.h +++ b/frameworks/kits/ability/native/include/continuation/distributed/distributed_errors.h @@ -33,7 +33,7 @@ enum { // 2097153 GET_DISTRIBUTED_ABILITY_SERVICE_FAILED, // 2097154 - DISTRIBUTED_ABILITY_SERVICE_NOT_CONNECTED, + DISTRIBUTED_ABILITY_SERVICE_NOT_READY, // 2097155 INCOMING_PARAMETER_POINTER_IS_NULL, /** diff --git a/frameworks/kits/ability/native/include/data_ability_result.h b/frameworks/kits/ability/native/include/data_ability_result.h index f6e8fe8e90c14c95ad7ca33977f7483c7e29ce51..7dc4304db20e1eaaaf8b7135a13be6eb908606d4 100644 --- a/frameworks/kits/ability/native/include/data_ability_result.h +++ b/frameworks/kits/ability/native/include/data_ability_result.h @@ -26,66 +26,66 @@ namespace AppExecFwk { class DataAbilityResult final : public Parcelable { public: /** - * @brief A constructor used to create a DataAbilityResult instance - * with the input parameter count specified. + * @brief A constructor used to create a DataAbilityResult instance + * with the input parameter count specified. */ DataAbilityResult(int count); - + /** - * @brief A constructor used to create a DataAbilityResult instance + * @brief A constructor used to create a DataAbilityResult instance * with the input parameter uri specified - */ + */ DataAbilityResult(const Uri &uri); - + /** - * @brief A constructor used to create a DataAbilityResult instance + * @brief A constructor used to create a DataAbilityResult instance * with a Parcel object specified. */ DataAbilityResult(Parcel &parcel); /** - * @brief A constructor used to create a DataAbilityResult instance - * with input parameters uri, count, and failure specified. + * @brief A constructor used to create a DataAbilityResult instance + * with input parameters uri, count, and failure specified. */ DataAbilityResult(const Uri &uri, int count); ~DataAbilityResult(); /** - * @brief Obtains the Uri object corresponding to the operation. - * @return Obtains the Uri object corresponding to the operation. + * @brief Obtains the Uri object corresponding to the operation. + * @return Obtains the Uri object corresponding to the operation. */ Uri GetUri(); /** - * @brief Obtains the number of rows affected by the operation. + * @brief Obtains the number of rows affected by the operation. * @return Returns the number of rows affected by the operation. */ int GetCount(); /** - * @brief Prints out a string containing the class object information. + * @brief Prints out a string containing the class object information. * @return Returns object information. */ std::string ToString(); /** - * @brief Marshals a DataAbilityResult object into a Parcel. + * @brief Marshals a DataAbilityResult object into a Parcel. * @param parcel Indicates the Parcel object for marshalling. * @return Returns true if the marshalling is successful; returns false otherwise. */ virtual bool Marshalling(Parcel &parcel) const; /** - * @brief Unmarshals a DataAbilityResult object from a Parcel. + * @brief Unmarshals a DataAbilityResult object from a Parcel. * @param parcel Indicates the Parcel object for unmarshalling. * @return Returns true if the unmarshalling is successful; returns false otherwise. */ static DataAbilityResult *Unmarshalling(Parcel &parcel); /** - * @brief Creates a DataAbilityResult instance based on the given Parcel object. - * Used to transfer DataAbilityResult object using Parcel. + * @brief Creates a DataAbilityResult instance based on the given Parcel object. + * Used to transfer DataAbilityResult object using Parcel. * @param parcel Indicates the Parcel object. * @return Returns the DataAbilityResult object. */ @@ -93,7 +93,7 @@ public: private: Uri uri_; - int count_; + int count_; bool ReadFromParcel(Parcel &parcel); // no object in parcel diff --git a/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h new file mode 100644 index 0000000000000000000000000000000000000000..f0223d26a40ba8da62e71098202f19cd62078dfe --- /dev/null +++ b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021-2022 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 FOUNDATION_AAFWK_STANDARD_FRAMEWORKS_KITS_ABILITY_NATIVE_INCLUDE_CONTINUATION_DISTRIBUTED_CLIENT_H +#define FOUNDATION_AAFWK_STANDARD_FRAMEWORKS_KITS_ABILITY_NATIVE_INCLUDE_CONTINUATION_DISTRIBUTED_CLIENT_H + + +#include + +#include "mission_info.h" +#include "mission_snapshot.h" +#include "want_params.h" +#include "want.h" +#include "iremote_broker.h" + +namespace OHOS { +namespace AAFwk { +class DistributedClient { +public: + DistributedClient() = default; + virtual ~DistributedClient() = default; + int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode); + int32_t ContinueMission(const std::string& srcDeviceId, const std::string& dstDeviceId, + int32_t missionId, const sptr& callback, const OHOS::AAFwk::WantParams& wantParams); + int32_t StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId, int32_t callerUid, + int32_t status); + int32_t NotifyCompleteContinuation(const std::u16string &devId, int32_t sessionId, bool isSuccess); + int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid); + int32_t DisconnectRemoteAbility(const sptr& connect); + int32_t StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag); + int32_t StopSyncRemoteMissions(const std::string& devId); + int32_t RegisterMissionListener(const std::u16string& devId, const sptr& obj); + int32_t UnRegisterMissionListener(const std::u16string& devId, const sptr& obj); + int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos); + int32_t GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, + std::unique_ptr& missionSnapshot); + enum { + START_REMOTE_ABILITY = 1, + CONNECT_REMOTE_ABILITY = 6, + DISCONNECT_REMOTE_ABILITY = 7, + START_CONTINUATION = 11, + NOTIFY_COMPLETE_CONTINUATION = 12, + CONTINUE_MISSION = 36, + GET_MISSION_INFOS = 80, + REGISTER_MISSION_LISTENER = 84, + UNREGISTER_MISSION_LISTENER = 85, + START_SYNC_MISSIONS = 92, + STOP_SYNC_MISSIONS = 98, + GET_REMOTE_MISSION_SNAPSHOT_INFO = 99, + }; +private: + sptr GetDmsProxy(); + bool ReadMissionInfosFromParcel(Parcel& parcel, std::vector& missionInfos); +}; +} // namespace AAFwk +} // namespace OHOS +#endif diff --git a/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_parcel_helper.h b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_parcel_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..13ce5241419a4f513695e5595ae38091495d299b --- /dev/null +++ b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_parcel_helper.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_PARCEL_HELPER_H +#define OHOS_DISTRIBUTED_PARCEL_HELPER_H + +#include + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +#define PARCEL_WRITE_HELPER(parcel, type, value) \ + do { \ + bool ret = parcel.Write##type((value)); \ + if (!ret) { \ + HILOG_ERROR("%{public}s write value failed!", __func__); \ + return ERR_FLATTEN_OBJECT; \ + } \ + } while (0) + +#define PARCEL_WRITE_HELPER_NORET(parcel, type, value) \ + do { \ + bool ret = parcel.Write##type((value)); \ + if (!ret) { \ + HILOG_ERROR("write value failed!"); \ + return; \ + } \ + } while (0) + +#define PARCEL_WRITE_HELPER_RET(parcel, type, value, failRet) \ + do { \ + bool ret = parcel.Write##type((value)); \ + if (!ret) { \ + HILOG_ERROR("%{public}s write value failed!", __func__); \ + return failRet; \ + } \ + } while (0) + +#define PARCEL_READ_HELPER(parcel, type, out) \ + do { \ + bool ret = parcel.Read##type((out)); \ + if (!ret) { \ + HILOG_ERROR("%{public}s read value failed!", __func__); \ + return ERR_FLATTEN_OBJECT; \ + } \ + } while (0) + +#define PARCEL_READ_HELPER_RET(parcel, type, out, failRet) \ + do { \ + bool ret = parcel.Read##type((out)); \ + if (!ret) { \ + HILOG_ERROR("%{public}s read value failed!", __func__); \ + return failRet; \ + } \ + } while (0) + +#define PARCEL_READ_HELPER_NORET(parcel, type, out) \ + do { \ + bool ret = parcel.Read##type((out)); \ + if (!ret) { \ + HILOG_WARN("%{public}s read value failed!", __func__); \ + } \ + } while (0) + +#define PARCEL_TRANSACT_SYNC_RET_INT(remote, code, data, reply) \ + do { \ + MessageOption option; \ + int32_t error = remote->SendRequest(code, data, reply, option); \ + if (error != ERR_NONE) { \ + HILOG_ERROR("%{public}s transact failed, error: %{public}d", __func__, error); \ + return error; \ + } \ + int32_t result = reply.ReadInt32(); \ + HILOG_INFO("%{public}s get result from server data = %{public}d", __func__, result); \ + return result; \ + } while (0) + +#define PARCEL_TRANSACT_SYNC_NORET(remote, code, data, reply) \ + do { \ + MessageOption option; \ + int32_t result = remote->SendRequest(code, data, reply, option); \ + if (result != ERR_NONE) { \ + HILOG_ERROR("%{public}s transact failed, result: %{public}d", __func__, result); \ + return; \ + } \ + HILOG_DEBUG("%{public}s transact success!", __func__); \ + } while (0) + +#define PARCEL_WRITE_REPLY_NOERROR(reply, type, result) \ + do { \ + bool ret = reply.Write##type(result); \ + if (!ret) { \ + HILOG_WARN("%{public}s write reply failed.", __func__); \ + } \ + return ERR_NONE; \ + } while (0) +} // namespace AAFwk +} // namespace OHOS +#endif /* OHOS_DISTRIBUTED_PARCEL_HELPER_H */ diff --git a/frameworks/kits/ability/native/include/extension_base.h b/frameworks/kits/ability/native/include/extension_base.h index 58b73012b0212d504dfef250b130f0464337eb93..ee5bb73485b85a61a0984c3105a0b7ce1b2793de 100644 --- a/frameworks/kits/ability/native/include/extension_base.h +++ b/frameworks/kits/ability/native/include/extension_base.h @@ -18,6 +18,7 @@ #include +#include "ability_local_record.h" #include "extension.h" #include "iremote_object.h" @@ -25,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { class OHOSApplication; class AbilityHandler; -class AbilityLocalRecord; } namespace AbilityRuntime { using namespace OHOS::AppExecFwk; @@ -77,4 +77,5 @@ private: }; } // namespace AbilityRuntime } // namespace OHOS +#include "extension_base.inl" #endif // FOUNDATION_ABILITYRUNTIME_OHOS_EXTENSION_BASE_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/extension_base.cpp b/frameworks/kits/ability/native/include/extension_base.inl similarity index 70% rename from frameworks/kits/ability/native/src/extension_base.cpp rename to frameworks/kits/ability/native/include/extension_base.inl index bece02508f6515f2aa5b56fff4a3379fecea1517..02d1f12e186e33558f435bce72e9738e153c168e 100644 --- a/frameworks/kits/ability/native/src/extension_base.cpp +++ b/frameworks/kits/ability/native/include/extension_base.inl @@ -13,10 +13,7 @@ * limitations under the License. */ -#include "extension_base.h" - -#include "ability_local_record.h" -#include "extension_context.h" +#include "foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context.h" #include "hilog_wrapper.h" namespace OHOS { @@ -38,8 +35,20 @@ std::shared_ptr ExtensionBase::CreateAndInitContext(const std::shared_ptr< std::shared_ptr &handler, const sptr &token) { + HILOG_INFO("begin init base"); std::shared_ptr context = std::make_shared(); context->SetToken(token); + auto appContext = Context::GetApplicationContext(); + context->SetApplicationInfo(appContext->GetApplicationInfo()); + context->SetResourceManager(appContext->GetResourceManager()); + if (record == nullptr) { + HILOG_ERROR("ServiceExtension::CreateAndInitContext record is nullptr"); + return context; + } + HILOG_INFO("begin init abilityInfo"); + auto abilityInfo = record->GetAbilityInfo(); + context->SetAbilityInfo(abilityInfo); + context->InitHapModuleInfo(abilityInfo); return context; } diff --git a/frameworks/kits/ability/native/include/extension_module_loader.h b/frameworks/kits/ability/native/include/extension_module_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..da16234de547aee05ae8d03b81849ee949aa1c26 --- /dev/null +++ b/frameworks/kits/ability/native/include/extension_module_loader.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_ABILITYRUNTIME_OHOS_EXTENSION_MODULE_LOADER_H +#define FOUNDATION_ABILITYRUNTIME_OHOS_EXTENSION_MODULE_LOADER_H + +#include "extension.h" +#include "runtime.h" +#include "singleton.h" + +namespace OHOS::AbilityRuntime { +/** + * @brief Load extension lib. + */ +class ExtensionModuleLoader { +public: + virtual ~ExtensionModuleLoader() = default; + + static ExtensionModuleLoader& GetLoader(const char* sharedLibrary = nullptr); + + /** + * @brief Create Extension. + * + * @param runtime The runtime. + * @return The Extension instance. + */ + virtual Extension *Create(const std::unique_ptr& runtime) const = 0; +}; +} // namespace OHOS::AbilityRuntime + +#endif // FOUNDATION_ABILITYRUNTIME_OHOS_EXTENSION_MODULE_LOADER_H diff --git a/frameworks/kits/ability/native/include/form_js_event_handler.h b/frameworks/kits/ability/native/include/form_js_event_handler.h index 8c70f8dc1ec86c40d8c24d10081cea029b0bf982..6de3d57b3c7f9ac7fdf3cd9f2ef410c3b39d7119 100644 --- a/frameworks/kits/ability/native/include/form_js_event_handler.h +++ b/frameworks/kits/ability/native/include/form_js_event_handler.h @@ -24,7 +24,7 @@ namespace OHOS { namespace AppExecFwk { class FormJsEventHandler : public EventHandler { public: - FormJsEventHandler(const std::shared_ptr &runner, + FormJsEventHandler(const std::shared_ptr &runner, const std::shared_ptr& ability, const FormJsInfo& formJsInfo); ~FormJsEventHandler() = default; diff --git a/frameworks/kits/ability/native/include/istatic_subscriber.h b/frameworks/kits/ability/native/include/istatic_subscriber.h new file mode 100644 index 0000000000000000000000000000000000000000..8ff87119b0f08f7e116749c697425cc961bdab62 --- /dev/null +++ b/frameworks/kits/ability/native/include/istatic_subscriber.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_I_STATIC_SUBSCRIBER_H +#define OHOS_APPEXECFWK_I_STATIC_SUBSCRIBER_H + +#include +#include +#include "common_event_data.h" + +namespace OHOS { +namespace AppExecFwk { +using EventFwk::CommonEventData; + +class IStaticSubscriber : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.AppExecFwk.IStaticSubscriber"); + + /** + * @brief Called when subscriber received common event. + * + * @param data Indicates the common event data.. + */ + virtual ErrCode OnCommonEventTriggered(CommonEventData* data) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_I_STATIC_SUBSCRIBER_H + diff --git a/frameworks/kits/ability/native/include/js_service_extension.h b/frameworks/kits/ability/native/include/js_service_extension.h index b95b15ab9a99a4e77483ea5b62da17d43dfdad75..036fe803236e59ca22f60abc7c92800f63609e73 100644 --- a/frameworks/kits/ability/native/include/js_service_extension.h +++ b/frameworks/kits/ability/native/include/js_service_extension.h @@ -107,6 +107,8 @@ public: private: NativeValue* CallObjectMethod(const char* name, NativeValue* const* argv = nullptr, size_t argc = 0); + void GetSrcPath(std::string &srcPath); + JsRuntime& jsRuntime_; std::unique_ptr jsObj_; }; diff --git a/frameworks/kits/ability/native/include/js_service_extension_context.h b/frameworks/kits/ability/native/include/js_service_extension_context.h old mode 100644 new mode 100755 index 67011adc304922afe71d7e797be1c55273179707..4648a5646b3a34a872e9ff7628f89a3f1a703898 --- a/frameworks/kits/ability/native/include/js_service_extension_context.h +++ b/frameworks/kits/ability/native/include/js_service_extension_context.h @@ -32,17 +32,18 @@ NativeValue* CreateJsServiceExtensionContext(NativeEngine& engine, std::shared_p class JSServiceExtensionConnection : public AbilityConnectCallback { public: + explicit JSServiceExtensionConnection(NativeEngine& engine); + ~JSServiceExtensionConnection(); void OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; void HandleOnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode); void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode); - void SetNativeEngine(NativeEngine* engine); void SetJsConnectionObject(NativeValue* jsConnectionObject); void CallJsFailed(int32_t errorCode); private: - NativeEngine* engine_ = nullptr; + NativeEngine& engine_; std::unique_ptr jsConnectionObject_ = nullptr; }; @@ -61,7 +62,7 @@ struct key_compare { } }; -static std::map, key_compare> connects_; +static std::map, key_compare> connects_; static int64_t serialNumber_ = 0; static std::shared_ptr handler_ = nullptr; } // namespace AbilityRuntime diff --git a/frameworks/kits/ability/native/include/js_static_subscriber_extension.h b/frameworks/kits/ability/native/include/js_static_subscriber_extension.h new file mode 100644 index 0000000000000000000000000000000000000000..cabcb0bc0d74b578bb001c61941a00ba953e1383 --- /dev/null +++ b/frameworks/kits/ability/native/include/js_static_subscriber_extension.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 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 FOUNDATION_ABILITYRUNTIME_OHOS_JS_STATIC_SUBSCRIBER_EXTENSION_H +#define FOUNDATION_ABILITYRUNTIME_OHOS_JS_STATIC_SUBSCRIBER_EXTENSION_H + +#include "common_event_data.h" +#include "static_subscriber_extension.h" + +class NativeReference; +class NativeValue; + +namespace OHOS { +namespace AbilityRuntime { +class JsRuntime; +/** + * @brief js-level static subscriber extension. + */ +class JsStaticSubscriberExtension : public StaticSubscriberExtension { +public: + JsStaticSubscriberExtension(JsRuntime& jsRuntime); + virtual ~JsStaticSubscriberExtension() override; + + /** + * @brief Create JsStaticSubscriberExtension. + * + * @param runtime The runtime. + * @return The JsStaticSubscriberExtension instance. + */ + static JsStaticSubscriberExtension* Create(const std::unique_ptr& runtime); + + void Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) override; + + void OnStart(const AAFwk::Want& want) override; + + sptr OnConnect(const AAFwk::Want& want) override; + + void OnDisconnect(const AAFwk::Want& want) override; + + void OnStop() override; + + void OnCommonEventTriggered(EventFwk::CommonEventData* data) override; +private: + JsRuntime& jsRuntime_; + std::unique_ptr jsObj_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_ABILITYRUNTIME_OHOS_JS_STATIC_SUBSCRIBER_EXTENSION_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/js_static_subscriber_extension_context.h b/frameworks/kits/ability/native/include/js_static_subscriber_extension_context.h new file mode 100644 index 0000000000000000000000000000000000000000..a1212a61ab73f49046a5e51cfa60f1b94d2b0881 --- /dev/null +++ b/frameworks/kits/ability/native/include/js_static_subscriber_extension_context.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 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 ABILITY_RUNTIME_JS_STATIC_SUBSCRIBER_EXTENSION_CONTEXT_H +#define ABILITY_RUNTIME_JS_STATIC_SUBSCRIBER_EXTENSION_CONTEXT_H + +#include + +#include "static_subscriber_extension_context.h" + +class NativeEngine; +class NativeValue; + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsStaticSubscriberExtensionContext(NativeEngine& engine, + std::shared_ptr context); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_STATIC_SUBSCRIBER_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/page_ability_impl.h b/frameworks/kits/ability/native/include/page_ability_impl.h index 7782fbe69dbd70654f3fe510014a78608d739cb8..2ddaee18949d03123139760940c3209273c52957 100644 --- a/frameworks/kits/ability/native/include/page_ability_impl.h +++ b/frameworks/kits/ability/native/include/page_ability_impl.h @@ -68,7 +68,7 @@ public: * */ bool AbilityTransactionNew(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); - + /** * @brief Execution the KeyDown callback of the ability * @param keyEvent Indicates the key-down event. diff --git a/frameworks/kits/ability/native/include/service_extension.h b/frameworks/kits/ability/native/include/service_extension.h old mode 100644 new mode 100755 index 044a00dc63025932e6b58aefd1640f39d0496548..8153c6746592ecc7ccb96fc862ac2cc0b87a9582 --- a/frameworks/kits/ability/native/include/service_extension.h +++ b/frameworks/kits/ability/native/include/service_extension.h @@ -66,12 +66,6 @@ public: * @return The ServiceExtension instance. */ static ServiceExtension* Create(const std::unique_ptr& runtime); - - /** - * @brief Stop the extension. - * - */ - virtual void OnStop() override; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/native/include/service_extension_module_loader.h b/frameworks/kits/ability/native/include/service_extension_module_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..2e602394e3c0660514cfeba7f69a50dfe78324f5 --- /dev/null +++ b/frameworks/kits/ability/native/include/service_extension_module_loader.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_ABILITYRUTIME_SERVICE_EXTENSION_MODULE_LOADER_H +#define FOUNDATION_ABILITYRUTIME_SERVICE_EXTENSION_MODULE_LOADER_H + +#include "extension_module_loader.h" + +namespace OHOS::AbilityRuntime { +class ServiceExtensionModuleLoader : public ExtensionModuleLoader, public Singleton { + DECLARE_SINGLETON(ServiceExtensionModuleLoader); + +public: + /** + * @brief Create Extension. + * + * @param runtime The runtime. + * @return The Extension instance. + */ + virtual Extension *Create(const std::unique_ptr& runtime) const override; +}; +} +#endif // FOUNDATION_ABILITYRUTIME_SERVICE_EXTENSION_MODULE_LOADER_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/static_subscriber_extension.h b/frameworks/kits/ability/native/include/static_subscriber_extension.h new file mode 100644 index 0000000000000000000000000000000000000000..8555ae6fee4ca97bebce6d88a39e1756147e1da5 --- /dev/null +++ b/frameworks/kits/ability/native/include/static_subscriber_extension.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 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 FOUNDATION_ABILITYRUNTIME_OHOS_STATIC_SUBSCRIBER_EXTENSION_H +#define FOUNDATION_ABILITYRUNTIME_OHOS_STATIC_SUBSCRIBER_EXTENSION_H + +#include "common_event_data.h" +#include "extension_base.h" + +namespace OHOS { +namespace AbilityRuntime { +class StaticSubscriberExtensionContext; +class Runtime; + +class StaticSubscriberExtension : public ExtensionBase { +public: + StaticSubscriberExtension() = default; + virtual ~StaticSubscriberExtension() = default; + + std::shared_ptr CreateAndInitContext( + const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) override; + + void Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) override; + + static StaticSubscriberExtension* Create(const std::unique_ptr& runtime); + + virtual void OnCommonEventTriggered(EventFwk::CommonEventData* data); +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_ABILITYRUNTIME_OHOS_STATIC_SUBSCRIBER_EXTENSION_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/static_subscriber_proxy.h b/frameworks/kits/ability/native/include/static_subscriber_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..e4a9eda0639013764a39da07fcc5b74ac6cca3c3 --- /dev/null +++ b/frameworks/kits/ability/native/include/static_subscriber_proxy.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_STATIC_SUBSCRIBER_PROXY_H +#define OHOS_APPEXECFWK_STATIC_SUBSCRIBER_PROXY_H + +#include +#include "istatic_subscriber.h" + +namespace OHOS { +namespace AppExecFwk { +class StaticSubscriberProxy : public IRemoteProxy { +public: + explicit StaticSubscriberProxy(const sptr& remote) + : IRemoteProxy(remote) {} + + virtual ~StaticSubscriberProxy() {} + + ErrCode OnCommonEventTriggered(CommonEventData* data) override; + +private: + static constexpr int COMMAND_ON_COMMON_EVENT_TRIGGERED = MIN_TRANSACTION_ID; + + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_STATIC_SUBSCRIBER_PROXY_H + diff --git a/frameworks/kits/ability/native/include/static_subscriber_stub.h b/frameworks/kits/ability/native/include/static_subscriber_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..ccf35f76b13a7ebda757fef50add8588b0c7c24c --- /dev/null +++ b/frameworks/kits/ability/native/include/static_subscriber_stub.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_STATIC_SUBSCRIBER_STUB_H +#define OHOS_APPEXECFWK_STATIC_SUBSCRIBER_STUB_H + +#include +#include "istatic_subscriber.h" + +namespace OHOS { +namespace AppExecFwk { +class StaticSubscriberStub : public IRemoteStub { +public: + StaticSubscriberStub() {} + + virtual ~StaticSubscriberStub() {} + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +private: + static constexpr int COMMAND_ON_COMMON_EVENT_TRIGGERED = MIN_TRANSACTION_ID; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_STATIC_SUBSCRIBER_STUB_H + diff --git a/frameworks/kits/ability/native/include/static_subscriber_stub_imp.h b/frameworks/kits/ability/native/include/static_subscriber_stub_imp.h new file mode 100644 index 0000000000000000000000000000000000000000..4c607ce10a75bf145db1dc8f5460a4b2325ccf6a --- /dev/null +++ b/frameworks/kits/ability/native/include/static_subscriber_stub_imp.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_STATIC_SUBSCRIBER_STUB_IMP_H +#define OHOS_APPEXECFWK_STATIC_SUBSCRIBER_STUB_IMP_H + +#include +#include "js_static_subscriber_extension.h" +#include "static_subscriber_stub.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityRuntime::JsStaticSubscriberExtension; +class StaticSubscriberStubImp : public StaticSubscriberStub { +public: + explicit StaticSubscriberStubImp(const std::shared_ptr& extension) + : extension_(extension) {} + + virtual ~StaticSubscriberStubImp() {} + + ErrCode OnCommonEventTriggered(CommonEventData* data) override; +private: + std::weak_ptr extension_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_STATIC_SUBSCRIBER_STUB_IMP_H + diff --git a/frameworks/kits/ability/native/src/ability.cpp b/frameworks/kits/ability/native/src/ability.cpp old mode 100644 new mode 100755 index f62297a73c27f7b73a2307c3e4371f54baca87b7..769d2baef4ff1a3c957e24c94cf44fb63ee737a5 --- a/frameworks/kits/ability/native/src/ability.cpp +++ b/frameworks/kits/ability/native/src/ability.cpp @@ -71,13 +71,8 @@ const std::string Ability::DMS_SESSION_ID("sessionId"); const std::string Ability::DMS_ORIGIN_DEVICE_ID("deviceId"); const int Ability::DEFAULT_DMS_SESSION_ID(0); const std::string PERMISSION_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; -const int TARGET_VERSION_THRESHOLDS = 8; -const std::map Ability::convertWindowModeMap_ = { - {AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN, Rosen::WindowMode::WINDOW_MODE_FULLSCREEN}, - //{AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY, Rosen::WindowMode::WINDOW_MODE_SPLIT_PRIMARY}, - //{AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY, Rosen::WindowMode::WINDOW_MODE_SPLIT_SECONDARY}, - {AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING, Rosen::WindowMode::WINDOW_MODE_FLOATING} -}; +const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher"; +const std::string LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility"; static std::mutex formLock; @@ -109,9 +104,8 @@ void Ability::Init(const std::shared_ptr &abilityInfo, const std::s // page ability only. if (abilityInfo_->type == AbilityType::PAGE) { - if (compatibleVersion_ < TARGET_VERSION_THRESHOLDS) { + if (!abilityInfo_->isStageBasedModel) { abilityWindow_ = std::make_shared(); - if (abilityWindow_ != nullptr) { APP_LOGI("%{public}s begin abilityWindow_->Init", __func__); abilityWindow_->Init(handler_, shared_from_this()); @@ -200,11 +194,20 @@ void Ability::OnStart(const Want &want) winType = Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW; } - APP_LOGI("Ability::OnStart bundleName:%{public}s abilityName:%{public}s: set config.type = %{public}d", + if (abilityInfo_->bundleName == LAUNCHER_BUNDLE_NAME && abilityInfo_->name == LAUNCHER_ABILITY_NAME) { + winType = Rosen::WindowType::WINDOW_TYPE_WALLPAPER; + } + + int defualtDisplayId = Rosen::WindowScene::DEFAULT_DISPLAY_ID; + int displayId = want.GetIntParam(StartOptions::STRING_DISPLAY_ID, defualtDisplayId); + APP_LOGI("Ability::OnStart bundleName:%{public}s, abilityName:%{public}s, windowType:%{public}d, " + "displayId:%{public}d", abilityInfo_->bundleName.c_str(), abilityInfo_->name.c_str(), - winType); - InitWindow(winType); + winType, + displayId); + auto option = GetWindowOption(want); + InitWindow(winType, displayId, option); if (abilityWindow_ != nullptr) { APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityStart.", __func__); @@ -223,7 +226,7 @@ void Ability::OnStart(const Want &want) APP_LOGE("Ability::OnStart error. abilityLifecycleExecutor_ == nullptr."); return; } - if (compatibleVersion_ < TARGET_VERSION_THRESHOLDS) { + if (!abilityInfo_->isStageBasedModel) { abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE); } else { abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::STARTED_NEW); @@ -267,11 +270,6 @@ void Ability::OnStop() return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_STOP); - - bool ret = AbilityRuntime::ConnectionManager::GetInstance().DisconnectCaller(AbilityContext::token_); - if (ret) { - APP_LOGI("The service connection is not disconnected."); - } APP_LOGI("%{public}s end.", __func__); } @@ -432,7 +430,7 @@ void Ability::OnBackground() APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { APP_LOGI("%{public}s begin OnPostAbilityBackground.", __func__); - if (compatibleVersion_ >= TARGET_VERSION_THRESHOLDS) { + if (abilityInfo_->isStageBasedModel) { if (scene_ == nullptr) { APP_LOGE("Ability::OnBackground error. scene_ == nullptr."); return; @@ -453,7 +451,7 @@ void Ability::OnBackground() return; } - if (compatibleVersion_ >= TARGET_VERSION_THRESHOLDS) { + if (abilityInfo_->isStageBasedModel) { abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW); } else { abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND); @@ -510,19 +508,24 @@ void Ability::OnDisconnect(const Want &want) * * @param want information of other ability * @param requestCode request code for abilityMS to return result + * + * @return errCode ERR_OK on success, others on failure. */ -void Ability::StartAbilityForResult(const Want &want, int requestCode) +ErrCode Ability::StartAbilityForResult(const Want &want, int requestCode) { APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::StartAbilityForResult abilityInfo_ == nullptr"); - return; + return ERR_NULL_OBJECT; } APP_LOGI("Ability::StartAbilityForResult called type = %{public}d", abilityInfo_->type); - if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { - AbilityContext::StartAbility(want, requestCode); + if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE) { + APP_LOGE("Ability::StartAbility ability type: %{public}d", abilityInfo_->type); + return ERR_INVALID_VALUE; } + ErrCode err = AbilityContext::StartAbility(want, requestCode); APP_LOGI("%{public}s end.", __func__); + return err; } /** @@ -535,19 +538,24 @@ void Ability::StartAbilityForResult(const Want &want, int requestCode) * @param requestCode Indicates the request code returned after the ability is started. You can define the request * code to identify the results returned by abilities. The value ranges from 0 to 65535. * @param abilityStartSetting Indicates the setting ability used to start. + * + * @return errCode ERR_OK on success, others on failure. */ -void Ability::StartAbilityForResult(const Want &want, int requestCode, AbilityStartSetting abilityStartSetting) +ErrCode Ability::StartAbilityForResult(const Want &want, int requestCode, AbilityStartSetting abilityStartSetting) { APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::StartAbilityForResult abilityInfo_ == nullptr"); - return; + return ERR_NULL_OBJECT; } APP_LOGI("Ability::StartAbilityForResult called type = %{public}d", abilityInfo_->type); - if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { - AbilityContext::StartAbility(want, requestCode, abilityStartSetting); + if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE) { + APP_LOGE("Ability::StartAbility ability type: %{public}d", abilityInfo_->type); + return ERR_INVALID_VALUE; } + ErrCode err = AbilityContext::StartAbility(want, requestCode, abilityStartSetting); APP_LOGI("%{public}s end.", __func__); + return err; } /** @@ -559,19 +567,24 @@ void Ability::StartAbilityForResult(const Want &want, int requestCode, AbilitySt * * @param want Indicates the ability to start. * @param abilityStartSetting Indicates the setting ability used to start. + * + * @return errCode ERR_OK on success, others on failure. */ -void Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSetting) +ErrCode Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSetting) { APP_LOGI("%{public}s beign.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::StartAbility abilityInfo_ == nullptr"); - return; + return ERR_NULL_OBJECT; } APP_LOGI("Ability::StartAbility called type = %{public}d", abilityInfo_->type); - if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE || abilityInfo_->type == AppExecFwk::AbilityType::SERVICE) { - AbilityContext::StartAbility(want, -1, abilityStartSetting); + if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE && abilityInfo_->type != AppExecFwk::AbilityType::SERVICE) { + APP_LOGE("Ability::StartAbility ability type: %{public}d", abilityInfo_->type); + return ERR_INVALID_VALUE; } + ErrCode err = AbilityContext::StartAbility(want, -1, abilityStartSetting); APP_LOGI("%{public}s end.", __func__); + return err; } /** @@ -668,7 +681,7 @@ void Ability::SetUIContent(int layoutRes, std::shared_ptr &context, int * * @param windowOption Indicates the window option defined by the user. */ -void Ability::InitWindow(Rosen::WindowType winType) +void Ability::InitWindow(Rosen::WindowType winType, int32_t displayId, sptr option) { if (abilityWindow_ == nullptr) { APP_LOGE("Ability::InitWindow abilityWindow_ is nullptr"); @@ -677,11 +690,11 @@ void Ability::InitWindow(Rosen::WindowType winType) bool useNewMission = AbilityImpl::IsUseNewMission(); APP_LOGI("%{public}s beign abilityWindow_->InitWindow.", __func__); if (useNewMission) { - abilityWindow_->InitWindow(winType, abilityContext_, sceneListener_); + abilityWindow_->InitWindow(winType, abilityContext_, sceneListener_, displayId, option); } else { std::shared_ptr context = nullptr; sptr listener = nullptr; - abilityWindow_->InitWindow(winType, context, listener); + abilityWindow_->InitWindow(winType, context, listener, displayId, option); } APP_LOGI("%{public}s end abilityWindow_->InitWindow.", __func__); } @@ -834,76 +847,48 @@ void Ability::OnConfigurationUpdated(const Configuration &configuration) APP_LOGI("%{public}s called.", __func__); } -void Ability::OnConfigurationUpdatedNotify(const Configuration &configuration) +void Ability::OnConfigurationUpdatedNotify(const Configuration &changeConfiguration) { APP_LOGI("%{public}s begin.", __func__); - if (configuration_ == nullptr) { - configuration_ = std::make_shared(configuration); - APP_LOGI("%{public}s begin Configuration init.", __func__); - return; - } - - // Data difference - Configuration differ; - std::vector changeKey; - configuration_->CompareDifferent(changeKey, configuration); - - if (changeKey.empty()) { - APP_LOGE("%{public}s Configuration differ is empty.", __func__); - return; + std::string language; + if (setting_) { + auto displayId = std::atoi(setting_->GetProperty(AbilityStartSetting::WINDOW_DISPLAY_ID_KEY).c_str()); + language = changeConfiguration.GetItem(displayId, GlobalConfigurationKey::SYSTEM_LANGUAGE); + APP_LOGI("displayId :[%{public}d] | language :[%{public}s]", displayId, language.c_str()); + } else { + language = changeConfiguration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE); + APP_LOGI("language :[%{public}s]", language.c_str()); } - for (auto &key : changeKey) { - auto item = configuration.GetItemForIdAndKey(key); - if (item.empty()) { - APP_LOGI("%{public}s configuration.GetItemForIdAndKey(%{public}s) is empty.", __func__, key.c_str()); - continue; - } - configuration_->Merge(key, configuration); - differ.Merge(key, configuration); - } - // Notify Ability Subclass - OnConfigurationUpdated(differ); - APP_LOGI("%{public}s Notify Ability Subclass.", __func__); - // Notify ResourceManager - std::string language = differ.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE); - while (language.compare("") != 0) { - std::unique_ptr resConfig(Global::Resource::CreateResConfig()); - if (resConfig == nullptr) { - APP_LOGE("%{public}s resConfig is nullptr.", __func__); - break; - } + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + if (resConfig != nullptr && !language.empty()) { + APP_LOGE("make resource mgr date"); UErrorCode status = U_ZERO_ERROR; icu::Locale locale = icu::Locale::forLanguageTag(language, status); - if (status != U_ZERO_ERROR) { - APP_LOGI("%{public}s Notify ResourceManager forLanguageTag error[%{public}d].", - __func__, - static_cast(status)); - break; - } - resConfig->SetLocaleInfo(locale); - auto resourceManager = GetResourceManager(); - if (resourceManager == nullptr) { - APP_LOGE("%{public}s resourceManager is nullptr.", __func__); - break; + APP_LOGI("get Locale::forLanguageTag return[%{public}d].", static_cast(status)); + if (status == U_ZERO_ERROR) { + resConfig->SetLocaleInfo(locale); + auto resourceManager = GetResourceManager(); + if (resourceManager != nullptr) { + resourceManager->UpdateResConfig(*resConfig); + APP_LOGI("%{public}s Notify ResourceManager.", __func__); + } } - resourceManager->UpdateResConfig(*resConfig); - APP_LOGI("%{public}s Notify ResourceManager.", __func__); - break; } // Notify WindowScene - if (scene_ != nullptr) { - auto diffConfiguration = std::make_shared(differ); + if (scene_ != nullptr && !language.empty()) { + auto diffConfiguration = std::make_shared(changeConfiguration); scene_->UpdateConfiguration(diffConfiguration); APP_LOGE("%{public}s scene_ -> UpdateConfiguration success.", __func__); - } else { - APP_LOGE("%{public}s scene_ is nullptr.", __func__); } - - APP_LOGI("%{public}s end.", __func__); + + abilityContext_->SetConfiguration(application_->GetConfiguration()); + // Notify Ability Subclass + OnConfigurationUpdated(changeConfiguration); + APP_LOGI("%{public}s Notify Ability Subclass.", __func__); } /** @@ -1463,24 +1448,26 @@ AbilityLifecycleExecutor::LifecycleState Ability::GetState() * the ability to start using the intent parameter. * * @param intent Indicates the ability to start. + * + * @return errCode ERR_OK on success, others on failure. */ -void Ability::StartAbility(const Want &want) +ErrCode Ability::StartAbility(const Want &want) { - APP_LOGI("%{public}s begin.", __func__); - AbilityContext::StartAbility(want, -1); - APP_LOGI("%{public}s end.", __func__); + APP_LOGI("%{public}s begin Ability::StartAbility", __func__); + return AbilityContext::StartAbility(want, -1); } /** * @brief Destroys this Page or Service ability. * After a Page or Service ability performs all operations, it can use this method to destroy itself * to free up memory. This method can be called only after the ability is initialized. + * + * @return errCode ERR_OK on success, others on failure. */ -void Ability::TerminateAbility() +ErrCode Ability::TerminateAbility() { - APP_LOGI("%{public}s begin.", __func__); - AbilityContext::TerminateAbility(); - APP_LOGI("%{public}s end.", __func__); + APP_LOGI("%{public}s begin Ability::TerminateAbility", __func__); + return AbilityContext::TerminateAbility(); } /** @@ -1557,8 +1544,10 @@ bool Ability::ConnectAbility(const Want &want, const sptr &conn) +ErrCode Ability::DisconnectAbility(const sptr &conn) { return AbilityContext::DisconnectAbility(conn); } @@ -1619,6 +1608,29 @@ std::weak_ptr Ability::GetContinuationRegisterMana return continuationRegisterManager; } +/** + * @brief Callback function to ask the user to prepare for the migration . + * + * @return If the user allows migration and saves data suscessfully, it returns true; otherwise, it returns false. + */ +bool Ability::OnContinue(WantParams &wantParams) +{ + return false; +} + +/** + * @brief Get page ability stack info. + * + * @return A string represents page ability stack info, empty if failed; + */ +std::string Ability::GetContentInfo() +{ + if (scene_ == nullptr) { + return ""; + } + return scene_->GetContentInfo(); +} + /** * @brief Migrates this ability to the given device on the same distributed network. The ability to migrate and its * ability slices must implement the IAbilityContinuation interface. @@ -1721,7 +1733,7 @@ void Ability::DispatchLifecycleOnForeground(const Want &want) APP_LOGE("Ability::OnForeground error. abilityLifecycleExecutor_ == nullptr."); return; } - if (compatibleVersion_ >= TARGET_VERSION_THRESHOLDS) { + if (abilityInfo_->isStageBasedModel) { abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::FOREGROUND_NEW); } else { abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE); @@ -2236,7 +2248,7 @@ void Ability::OnUpdate(const int64_t formId) {} /** - * @brief Called when the form provider is notified that a temporary form is successfully converted to a normal + * @brief Called when the form supplier is notified that a temporary form is successfully converted to a normal * form. * * @param formId Indicates the ID of the form. @@ -2246,7 +2258,7 @@ void Ability::OnCastTemptoNormal(const int64_t formId) {} /** - * @brief Called when the form provider receives form events from the fms. + * @brief Called when the form supplier receives form events from the fms. * * @param formEventsMap Indicates the form events occurred. The key in the Map object indicates the form ID, * and the value indicates the event type, which can be either FORM_VISIBLE @@ -2257,7 +2269,7 @@ void Ability::OnCastTemptoNormal(const int64_t formId) void Ability::OnVisibilityChanged(const std::map &formEventsMap) {} /** - * @brief Called to notify the form provider to update a specified form. + * @brief Called to notify the form supplier to update a specified form. * * @param formId Indicates the ID of the form to update. * @param message Form event message. @@ -2570,7 +2582,7 @@ bool Ability::LifecycleUpdate(std::vector formIds, int32_t updateType) * * This method must be called when the application has detected that a system setting item (such as the language, * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form - * provider automatically updates the form data (if there is any update) through the form framework, with the update + * supplier automatically updates the form data (if there is any update) through the form framework, with the update * process being unperceivable by the application. * * @param formId Indicates the ID of the form to update. @@ -2717,16 +2729,20 @@ bool Ability::CheckFMSReady() bool Ability::GetAllFormsInfo(std::vector &formInfos) { APP_LOGI("%{public}s called.", __func__); - sptr iBundleMgr = GetBundleMgr(); - if (iBundleMgr == nullptr) { - APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); return false; } - bool isHaveFormsInfo = iBundleMgr->GetAllFormsInfo(formInfos); - if (formInfos.size() == 0 || formInfos.empty()) { - isHaveFormsInfo = false; + + // GetAllFormsInfo request to fms + int resultCode = FormMgr::GetInstance().GetAllFormsInfo(formInfos); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s error, failed to GetAllFormsInfo, error code is %{public}d.", __func__, resultCode); + return false; } - return isHaveFormsInfo; + + return !formInfos.empty(); } /** @@ -2743,16 +2759,20 @@ bool Ability::GetFormsInfoByApp(std::string &bundleName, std::vector & APP_LOGW("Failed to Get forms info, because empty bundle name"); return false; } - sptr iBundleMgr = GetBundleMgr(); - if (iBundleMgr == nullptr) { - APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); return false; } - bool isHaveFormsInfo = iBundleMgr->GetFormsInfoByApp(bundleName, formInfos); - if (formInfos.size() == 0 || formInfos.empty()) { - isHaveFormsInfo = false; + + // GetFormsInfoByApp request to fms + int resultCode = FormMgr::GetInstance().GetFormsInfoByApp(bundleName, formInfos); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s error, failed to GetFormsInfoByApp, error code is %{public}d.", __func__, resultCode); + return false; } - return isHaveFormsInfo; + + return !formInfos.empty(); } /** @@ -2770,16 +2790,20 @@ bool Ability::GetFormsInfoByModule(std::string &bundleName, std::string &moduleN APP_LOGW("Failed to Get forms info, because empty bundleName or moduleName"); return false; } - sptr iBundleMgr = GetBundleMgr(); - if (iBundleMgr == nullptr) { - APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); return false; } - bool isHaveFormsInfo = iBundleMgr->GetFormsInfoByModule(bundleName, moduleName, formInfos); - if (formInfos.size() == 0 || formInfos.empty()) { - isHaveFormsInfo = false; + + // GetFormsInfoByModule request to fms + int resultCode = FormMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s error, failed to GetFormsInfoByModule, error code is %{public}d.", __func__, resultCode); + return false; } - return isHaveFormsInfo; + + return !formInfos.empty(); } /** @@ -3211,13 +3235,11 @@ sptr Ability::GetWindowOption(const Want &want) APP_LOGE("Ability::GetWindowOption option is null."); return nullptr; } - auto windowMode = want.GetIntParam(StartOptions::STRING_WINDOW_MODE, + auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); - auto iter = convertWindowModeMap_.find(windowMode); - if (iter != convertWindowModeMap_.end()) { - option->SetWindowMode(iter->second); - APP_LOGI("Ability::GetWindowOption window mode is %{public}d.", iter->second); - } + APP_LOGI("Ability::GetWindowOption window mode is %{public}d.", windowMode); + option->SetWindowMode(static_cast(windowMode)); + APP_LOGI("%{public}s end", __func__); return option; } @@ -3233,5 +3255,14 @@ void Ability::DoOnForeground(const Want& want) } } + +/** + * @brief request a remote object of callee from this ability. + * @return Returns the remote object of callee. + */ +sptr Ability::CallRequest() +{ + return nullptr; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_context.cpp b/frameworks/kits/ability/native/src/ability_context.cpp index d29249833438bb6d00304d8bd6ab7db413fc45ce..4b22e8595538aa7940490976cbed6ca21639c481 100644 --- a/frameworks/kits/ability/native/src/ability_context.cpp +++ b/frameworks/kits/ability/native/src/ability_context.cpp @@ -41,8 +41,10 @@ int AbilityContext::ABILITY_CONTEXT_DEFAULT_REQUEST_CODE(0); * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE * template. * + * @return errCode ERR_OK on success, others on failure. + * */ -void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) +ErrCode AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) { APP_LOGI("%{public}s begin.", __func__); APP_LOGI("AbilityContext::StartAbility called, requestCode = %{public}d", requestCode); @@ -50,7 +52,7 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) AppExecFwk::AbilityType type = GetAbilityInfoType(); if (type != AppExecFwk::AbilityType::PAGE && type != AppExecFwk::AbilityType::SERVICE) { APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type); - return; + return ERR_INVALID_VALUE; } APP_LOGI("%{public}s. Start calling ams->StartAbility.", __func__); @@ -60,6 +62,7 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err); } APP_LOGI("%{public}s end.", __func__); + return err; } /** @@ -70,14 +73,15 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) * to identify the results returned by abilities. The value ranges from 0 to 65535. * @param abilityStartSetting Indicates the special start setting used in starting ability. * + * @return errCode ERR_OK on success, others on failure. */ -void AbilityContext::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) +ErrCode AbilityContext::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) { APP_LOGI("%{public}s begin.", __func__); AppExecFwk::AbilityType type = GetAbilityInfoType(); if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type); - return; + return ERR_INVALID_VALUE; } APP_LOGI("%{public}s. Start calling ams->StartAbility.", __func__); @@ -89,6 +93,7 @@ void AbilityContext::StartAbility(const Want &want, int requestCode, const Abili } APP_LOGI("%{public}s end.", __func__); + return err; } /** @@ -97,8 +102,9 @@ void AbilityContext::StartAbility(const Want &want, int requestCode, const Abili * * @param requestCode Indicates the request code passed for starting the ability. * + * @return errCode ERR_OK on success, others on failure. */ -void AbilityContext::TerminateAbility(int requestCode) +ErrCode AbilityContext::TerminateAbility(int requestCode) { APP_LOGI("%{public}s begin.", __func__); ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, requestCode); @@ -106,19 +112,21 @@ void AbilityContext::TerminateAbility(int requestCode) APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err); } APP_LOGI("%{public}s end.", __func__); + return err; } /** * @brief Destroys the current ability. * + * @return errCode ERR_OK on success, others on failure. */ -void AbilityContext::TerminateAbility() +ErrCode AbilityContext::TerminateAbility() { APP_LOGI("%{public}s begin.", __func__); std::shared_ptr info = GetAbilityInfo(); if (info == nullptr) { APP_LOGE("AbilityContext::TerminateAbility info == nullptr"); - return; + return ERR_NULL_OBJECT; } ErrCode err = ERR_OK; @@ -143,6 +151,7 @@ void AbilityContext::TerminateAbility() APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err); } APP_LOGI("%{public}s end.", __func__); + return err; } /** @@ -245,15 +254,17 @@ bool AbilityContext::ConnectAbility(const Want &want, const sptr &conn) +ErrCode AbilityContext::DisconnectAbility(const sptr &conn) { APP_LOGI("%{public}s begin.", __func__); AppExecFwk::AbilityType type = GetAbilityInfoType(); if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { APP_LOGE("AbilityContext::DisconnectAbility AbilityType = %{public}d", type); - return; + return ERR_INVALID_VALUE; } ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn); @@ -262,6 +273,7 @@ void AbilityContext::DisconnectAbility(const sptr &co APP_LOGE("AbilityContext::DisconnectAbility error"); } APP_LOGD("AbilityContext::DisconnectAbility end"); + return ret; } /** diff --git a/frameworks/kits/ability/native/src/ability_impl.cpp b/frameworks/kits/ability/native/src/ability_impl.cpp index feb6cc865b5edb7dddeb3a161a069f539e25d5d4..a03ebf5caf71c71a1bdbb609f9587c6e00e5f186 100755 --- a/frameworks/kits/ability/native/src/ability_impl.cpp +++ b/frameworks/kits/ability/native/src/ability_impl.cpp @@ -22,9 +22,10 @@ namespace OHOS { namespace AppExecFwk { -const int TARGET_VERSION_THRESHOLDS = 8; static bool g_useNewMission = false; static bool g_isMissionFlagSetted = false; +const std::string PERMISSION_KEY = "ohos.user.grant.permission"; +const std::string GRANTED_RESULT_KEY = "ohos.user.grant.permission.result"; void AbilityImpl::Init(std::shared_ptr &application, const std::shared_ptr &record, std::shared_ptr &ability, std::shared_ptr &handler, const sptr &token, @@ -43,8 +44,12 @@ void AbilityImpl::Init(std::shared_ptr &application, const std: record->SetAbilityImpl(shared_from_this()); ability_ = ability; handler_ = handler; - ability_->SetSceneListener( - sptr(new (std::nothrow) WindowLifeCycleImpl(token_, shared_from_this()))); + auto info = record->GetAbilityInfo(); + isStageBasedModel_ = info && info->isStageBasedModel; + if (info && info->type == AbilityType::PAGE) { + ability_->SetSceneListener( + sptr(new (std::nothrow) WindowLifeCycleImpl(token_, shared_from_this()))); + } ability_->Init(record->GetAbilityInfo(), application, handler, token); lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; abilityLifecycleCallbacks_ = application; @@ -66,14 +71,15 @@ void AbilityImpl::Start(const Want &want) return; } - if (ability_->GetAbilityInfo()->type == AbilityType::PAGE) { + if ((ability_->GetAbilityInfo()->type == AbilityType::PAGE) && + (!ability_->GetAbilityInfo()->isStageBasedModel)) { ability_->HandleCreateAsContinuation(want); } APP_LOGI("AbilityImpl::Start"); ability_->OnStart(want); if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && - (ability_->GetCompatibleVersion() >= TARGET_VERSION_THRESHOLDS)) { + (ability_->GetAbilityInfo()->isStageBasedModel)) { lifecycleState_ = AAFwk::ABILITY_STATE_STARTED_NEW; } else { if (ability_->GetAbilityInfo()->type == AbilityType::DATA) { @@ -87,7 +93,7 @@ void AbilityImpl::Start(const Want &want) // Multimodal Events Register if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && - (ability_->GetCompatibleVersion() < TARGET_VERSION_THRESHOLDS)) { + (!ability_->GetAbilityInfo()->isStageBasedModel)) { WindowEventRegister(); } APP_LOGI("%{public}s end.", __func__); @@ -109,7 +115,7 @@ void AbilityImpl::Stop() APP_LOGI("AbilityImpl::Stop"); ability_->OnStop(); if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && - (ability_->GetCompatibleVersion() >= TARGET_VERSION_THRESHOLDS)) { + (ability_->GetAbilityInfo()->isStageBasedModel)) { lifecycleState_ = AAFwk::ABILITY_STATE_STOPED_NEW; } else { lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; @@ -171,6 +177,11 @@ void AbilityImpl::Inactive() APP_LOGI("%{public}s end.", __func__); } +bool AbilityImpl::IsStageBasedModel() const +{ + return isStageBasedModel_; +} + int AbilityImpl::GetCompatibleVersion() { if (ability_) { @@ -187,7 +198,7 @@ void AbilityImpl::AfterUnFocused() return; } - if (ability_->GetCompatibleVersion() >= TARGET_VERSION_THRESHOLDS) { + if (ability_->GetAbilityInfo()->isStageBasedModel) { APP_LOGI("new version ability, do nothing when after unfocused."); return; } @@ -208,7 +219,7 @@ void AbilityImpl::WindowLifeCycleImpl::AfterForeground() BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); APP_LOGI("%{public}s begin.", __func__); auto owner = owner_.lock(); - if (owner && owner->GetCompatibleVersion() < TARGET_VERSION_THRESHOLDS) { + if (owner && !owner->IsStageBasedModel()) { return; } @@ -223,7 +234,7 @@ void AbilityImpl::WindowLifeCycleImpl::AfterBackground() BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); APP_LOGI("%{public}s begin.", __func__); auto owner = owner_.lock(); - if (owner && owner->GetCompatibleVersion() < TARGET_VERSION_THRESHOLDS) { + if (owner && !owner->IsStageBasedModel()) { return; } @@ -265,7 +276,7 @@ void AbilityImpl::Foreground(const Want &want) APP_LOGI("AbilityImpl::Foreground"); ability_->OnForeground(want); if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && - (ability_->GetCompatibleVersion() >= TARGET_VERSION_THRESHOLDS)) { + (ability_->GetAbilityInfo()->isStageBasedModel)) { lifecycleState_ = AAFwk::ABILITY_STATE_FOREGROUND_NEW; } else { lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; @@ -291,7 +302,7 @@ void AbilityImpl::Background() ability_->OnLeaveForeground(); ability_->OnBackground(); if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && - (ability_->GetCompatibleVersion() >= TARGET_VERSION_THRESHOLDS)) { + (ability_->GetAbilityInfo()->isStageBasedModel)) { lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND_NEW; } else { lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND; @@ -499,6 +510,14 @@ void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &result } else { APP_LOGI("%{public}s user cancel permissions.", __func__); } + } else if (resultData.HasParameter(PERMISSION_KEY)) { + std::vector permissions = resultData.GetStringArrayParam(PERMISSION_KEY); + std::vector grantedResult(permissions.size(), -1); + if (resultCode > 0) { + grantedResult = resultData.GetIntArrayParam(GRANTED_RESULT_KEY); + APP_LOGI("%{public}s Get user granted result.", __func__); + } + ability_->OnRequestPermissionsFromUserResult(requestCode, permissions, grantedResult); } else { ability_->OnAbilityResult(requestCode, resultCode, resultData); } @@ -820,19 +839,17 @@ void AbilityImpl::ScheduleUpdateConfiguration(const Configuration &config) { APP_LOGI("%{public}s begin.", __func__); - // Update for the first time - if (!configuration_) { - configuration_ = std::make_shared(config); - APP_LOGI("AbilityImpl::Init the configuration"); - return; - } if (ability_ == nullptr) { APP_LOGE("AbilityImpl::ScheduleUpdateConfiguration ability_ is nullptr"); return; } - ability_->OnConfigurationUpdatedNotify(config); + if (lifecycleState_ != AAFwk::ABILITY_STATE_INITIAL) { + APP_LOGI("ability name: [%{public}s]", ability_->GetAbilityName().c_str()); + ability_->OnConfigurationUpdatedNotify(config); + } + APP_LOGI("%{public}s end.", __func__); } @@ -860,7 +877,7 @@ void AbilityImpl::InputEventConsumerImpl::OnInputEvent(std::shared_ptrGetCompatibleVersion() < TARGET_VERSION_THRESHOLDS) { + if (!ability_->GetAbilityInfo()->isStageBasedModel) { auto window = ability_->GetWindow(); if (window) { std::shared_ptr inputEventListener = diff --git a/frameworks/kits/ability/native/src/ability_impl_factory.cpp b/frameworks/kits/ability/native/src/ability_impl_factory.cpp index 5e8064154f54aec638a9ef1d7941174edbff670b..0db5e6c59bf968c80c3a499f1bd87ee87da5ca00 100644 --- a/frameworks/kits/ability/native/src/ability_impl_factory.cpp +++ b/frameworks/kits/ability/native/src/ability_impl_factory.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace AppExecFwk { -const int TARGET_VERSION_THRESHOLDS = 8; /** * * default constructor @@ -55,11 +54,11 @@ std::shared_ptr AbilityImplFactory::MakeAbilityImplObject(const std } std::shared_ptr abilityImpl = nullptr; - APP_LOGI("AbilityImplFactory::MakeAbilityImplObject type:%{public}d, compatibleVersion:%{public}d", info->type, - compatibleVersion); + APP_LOGI("AbilityImplFactory::MakeAbilityImplObject type:%{public}d, isStageBasedModel:%{public}d", info->type, + info->isStageBasedModel); switch (info->type) { case AppExecFwk::AbilityType::PAGE: - if (compatibleVersion >= TARGET_VERSION_THRESHOLDS) { + if (info->isStageBasedModel) { abilityImpl = std::make_shared(); } else { abilityImpl = std::make_shared(); diff --git a/frameworks/kits/ability/native/src/ability_lifecycle.cpp b/frameworks/kits/ability/native/src/ability_lifecycle.cpp index f8d39c937543c746303c9817cfed5d2db1090fab..28c7ee112f80ae7611011219eacbb124305ea801 100644 --- a/frameworks/kits/ability/native/src/ability_lifecycle.cpp +++ b/frameworks/kits/ability/native/src/ability_lifecycle.cpp @@ -61,8 +61,7 @@ void LifeCycle::AddObserver(const std::shared_ptr &observer) */ void LifeCycle::DispatchLifecycle(const LifeCycle::Event &event, const Want &want) { - APP_LOGI("LifeCycle::DispatchLifecycle: called"); - + APP_LOGI("LifeCycle::DispatchLifecycle: event:%{public}d", event); if ((event != LifeCycle::Event::ON_FOREGROUND) && (event != LifeCycle::Event::ON_START)) { APP_LOGE("event value error: event is %{public}d", event); return; @@ -101,8 +100,7 @@ void LifeCycle::DispatchLifecycle(const LifeCycle::Event &event, const Want &wan */ void LifeCycle::DispatchLifecycle(const LifeCycle::Event &event) { - APP_LOGI("LifeCycle::DispatchLifecycle: called"); - + APP_LOGI("LifeCycle::DispatchLifecycle: event:%{public}d", event); if ((event != LifeCycle::Event::ON_ACTIVE) && (event != LifeCycle::Event::ON_BACKGROUND) && (event != LifeCycle::Event::ON_INACTIVE) && (event != LifeCycle::Event::ON_STOP)) { APP_LOGE("event value error: event is %{public}d", event); diff --git a/frameworks/kits/ability/native/src/ability_process.cpp b/frameworks/kits/ability/native/src/ability_process.cpp index 615be602ccb1f45d96f540cf63c63d1ac658bdb7..d0cc200cd811c93b769a137953c570ae4dbc1866 100644 --- a/frameworks/kits/ability/native/src/ability_process.cpp +++ b/frameworks/kits/ability/native/src/ability_process.cpp @@ -21,7 +21,11 @@ namespace OHOS { namespace AppExecFwk { static void *g_handle = nullptr; +#ifdef _ARM64_ +constexpr char SHARED_LIBRARY_FEATURE_ABILITY[] = "/system/lib64/module/ability/libfeatureability.z.so"; +#else constexpr char SHARED_LIBRARY_FEATURE_ABILITY[] = "/system/lib/module/ability/libfeatureability.z.so"; +#endif constexpr char FUNC_CALL_ON_ABILITY_RESULT[] = "CallOnAbilityResult"; using NAPICallOnAbilityResult = void (*)(int requestCode, int resultCode, const Want &resultData, CallbackInfo cb); constexpr char FUNC_CALL_ON_REQUEST_PERMISSIONS_FROM_USERRESULT[] = "CallOnRequestPermissionsFromUserResult"; @@ -49,21 +53,23 @@ AbilityProcess::AbilityProcess() AbilityProcess::~AbilityProcess() {} -void AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, CallbackInfo callback) +ErrCode AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, CallbackInfo callback) { APP_LOGI("AbilityProcess::StartAbility begin"); if (ability == nullptr) { APP_LOGE("AbilityProcess::StartAbility ability is nullptr"); - return; + return ERR_NULL_OBJECT; } + ErrCode err = ERR_OK; + if (param.forResultOption == true) { if (param.setting == nullptr) { APP_LOGI("%{public}s param.setting == nullptr call StartAbilityForResult.", __func__); - ability->StartAbilityForResult(param.want, param.requestCode); + err = ability->StartAbilityForResult(param.want, param.requestCode); } else { APP_LOGI("%{public}s param.setting != nullptr call StartAbilityForResult.", __func__); - ability->StartAbilityForResult(param.want, param.requestCode, *(param.setting)); + err = ability->StartAbilityForResult(param.want, param.requestCode, *(param.setting)); } std::lock_guard lock_l(mutex_); @@ -82,13 +88,14 @@ void AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, Call } else { if (param.setting == nullptr) { APP_LOGI("%{public}s param.setting == nullptr call StartAbility.", __func__); - ability->StartAbility(param.want); + err = ability->StartAbility(param.want); } else { APP_LOGI("%{public}s param.setting != nullptr call StartAbility.", __func__); - ability->StartAbility(param.want, *(param.setting)); + err = ability->StartAbility(param.want, *(param.setting)); } } APP_LOGI("AbilityProcess::StartAbility end"); + return err; } void AbilityProcess::OnAbilityResult(Ability *ability, int requestCode, int resultCode, const Want &resultData) diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp old mode 100644 new mode 100755 index 8341a2f764b5863201ff56b24848bf652d62ddb5..314e95709ee42ba4ac6d5801cec23dfb606238d5 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp @@ -13,15 +13,19 @@ * limitations under the License. */ #include +#include "system_ability_definition.h" +#include "if_system_ability_manager.h" #include "ability_runtime/js_ability.h" #include "ability_runtime/js_ability_context.h" #include "ability_runtime/js_window_stage.h" #include "ability_start_setting.h" +#include "connection_manager.h" #include "hilog_wrapper.h" #include "js_data_struct_converter.h" #include "js_runtime.h" #include "js_runtime_utils.h" +#include "napi_common_configuration.h" #include "napi_common_want.h" #include "napi_remote_object.h" #include "string_wrapper.h" @@ -30,12 +34,13 @@ namespace OHOS { namespace AbilityRuntime { const std::string PAGE_STACK_PROPERTY_NAME = "pageStack"; -Ability* JsAbility::Create(const std::unique_ptr& runtime) +Ability *JsAbility::Create(const std::unique_ptr &runtime) { - return new JsAbility(static_cast(*runtime)); + return new JsAbility(static_cast(*runtime)); } -JsAbility::JsAbility(JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} +JsAbility::JsAbility(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) +{} JsAbility::~JsAbility() = default; void JsAbility::Init(const std::shared_ptr &abilityInfo, @@ -50,33 +55,63 @@ void JsAbility::Init(const std::shared_ptr &abilityInfo, } std::string srcPath(abilityInfo->package); - srcPath.append("/assets/js/"); - if (!abilityInfo->srcPath.empty()) { - srcPath.append(abilityInfo->srcPath); + if (!abilityInfo->isModuleJson) { + /* temporary compatibility api8 + config.json */ + srcPath.append("/assets/js/"); + if (!abilityInfo->srcPath.empty()) { + srcPath.append(abilityInfo->srcPath); + } + srcPath.append("/").append(abilityInfo->name).append(".abc"); + } else { + if (abilityInfo->srcEntrance.empty()) { + HILOG_ERROR("abilityInfo srcEntrance is empty"); + return; + } + srcPath.append("/"); + srcPath.append(abilityInfo->srcEntrance); + srcPath.erase(srcPath.rfind(".")); + srcPath.append(".abc"); + HILOG_INFO("JsAbility srcPath is %{public}s", srcPath.c_str()); } - srcPath.append("/").append(abilityInfo->name).append(".abc"); std::string moduleName(abilityInfo->moduleName); moduleName.append("::").append(abilityInfo->name); HandleScope handleScope(jsRuntime_); - auto& engine = jsRuntime_.GetNativeEngine(); + auto &engine = jsRuntime_.GetNativeEngine(); jsAbilityObj_ = jsRuntime_.LoadModule(moduleName, srcPath); - NativeObject* obj = ConvertNativeValueTo(jsAbilityObj_->Get()); + NativeObject *obj = ConvertNativeValueTo(jsAbilityObj_->Get()); if (obj == nullptr) { HILOG_ERROR("Failed to get AbilityStage object"); return; } auto context = GetAbilityContext(); - NativeValue* contextObj = CreateJsAbilityContext(engine, context); - auto shellContextRef = jsRuntime_.LoadSystemModule("application.AbilityContext", &contextObj, 1); - contextObj = shellContextRef->Get(); + NativeValue *contextObj = CreateJsAbilityContext(engine, context); + shellContextRef_ = std::shared_ptr( + jsRuntime_.LoadSystemModule("application.AbilityContext", &contextObj, 1).release()); + contextObj = shellContextRef_->Get(); - context->Bind(jsRuntime_, shellContextRef.release()); + context->Bind(jsRuntime_, shellContextRef_.get()); obj->SetProperty("context", contextObj); + + auto nativeObj = ConvertNativeValueTo(contextObj); + if (nativeObj == nullptr) { + HILOG_ERROR("Failed to get ability native object"); + return; + } + + HILOG_INFO("Set ability context pointer: %{public}p", context.get()); + + nativeObj->SetNativePointer( + new std::weak_ptr(context), + [](NativeEngine *, void *data, void *) { + HILOG_INFO("Finalizer for weak_ptr ability context is called"); + delete static_cast *>(data); + }, + nullptr); } void JsAbility::OnStart(const Want &want) @@ -89,22 +124,22 @@ void JsAbility::OnStart(const Want &want) } HandleScope handleScope(jsRuntime_); - auto& nativeEngine = jsRuntime_.GetNativeEngine(); + auto &nativeEngine = jsRuntime_.GetNativeEngine(); - NativeValue* value = jsAbilityObj_->Get(); - NativeObject* obj = ConvertNativeValueTo(value); + NativeValue *value = jsAbilityObj_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); if (obj == nullptr) { HILOG_ERROR("Failed to get Ability object"); return; } napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(&nativeEngine), want); - NativeValue* jsWant = reinterpret_cast(napiWant); + NativeValue *jsWant = reinterpret_cast(napiWant); obj->SetProperty("launchWant", jsWant); obj->SetProperty("lastRequestWant", jsWant); - NativeValue* argv[] = { + NativeValue *argv[] = { jsWant, CreateJsLaunchParam(nativeEngine, GetLaunchParam()), }; @@ -116,6 +151,10 @@ void JsAbility::OnStop() Ability::OnStop(); CallObjectMethod("onDestroy"); + bool ret = ConnectionManager::GetInstance().DisconnectCaller(AbilityContext::token_); + if (ret) { + HILOG_INFO("The service connection is not disconnected."); + } } void JsAbility::OnSceneCreated() @@ -127,7 +166,7 @@ void JsAbility::OnSceneCreated() HILOG_ERROR("Failed to create jsAppWindowStage object by LoadSystemModule"); return; } - NativeValue* argv[] = {jsAppWindowStage->Get()}; + NativeValue *argv[] = {jsAppWindowStage->Get()}; CallObjectMethod("onWindowStageCreate", argv, ArraySize(argv)); } @@ -140,7 +179,7 @@ void JsAbility::OnSceneRestored() HILOG_ERROR("Failed to create jsAppWindowStage object by LoadSystemModule"); return; } - NativeValue* argv[] = {jsAppWindowStage->Get()}; + NativeValue *argv[] = {jsAppWindowStage->Get()}; CallObjectMethod("onWindowStageRestore", argv, ArraySize(argv)); } @@ -156,17 +195,17 @@ void JsAbility::OnForeground(const Want &want) Ability::OnForeground(want); HandleScope handleScope(jsRuntime_); - auto& nativeEngine = jsRuntime_.GetNativeEngine(); + auto &nativeEngine = jsRuntime_.GetNativeEngine(); - NativeValue* value = jsAbilityObj_->Get(); - NativeObject* obj = ConvertNativeValueTo(value); + NativeValue *value = jsAbilityObj_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); if (obj == nullptr) { HILOG_ERROR("Failed to get Ability object"); return; } napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(&nativeEngine), want); - NativeValue* jsWant = reinterpret_cast(napiWant); + NativeValue *jsWant = reinterpret_cast(napiWant); obj->SetProperty("lastRequestWant", jsWant); @@ -180,6 +219,78 @@ void JsAbility::OnBackground() CallObjectMethod("onBackground"); } +bool JsAbility::OnContinue(WantParams &wantParams) +{ + HandleScope handleScope(jsRuntime_); + auto &nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue *value = jsAbilityObj_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get Ability object"); + return false; + } + + NativeValue *methodOnCreate = obj->GetProperty("onContinue"); + if (methodOnCreate == nullptr) { + HILOG_ERROR("Failed to get 'onContinue' from Ability object"); + return false; + } + + napi_value napiWantParams = OHOS::AppExecFwk::WrapWantParams(reinterpret_cast(&nativeEngine), wantParams); + NativeValue *jsWantParams = reinterpret_cast(napiWantParams); + + NativeValue *result = nativeEngine.CallFunction(value, methodOnCreate, &jsWantParams, 1); + + napi_value new_napiWantParams = reinterpret_cast(jsWantParams); + OHOS::AppExecFwk::UnwrapWantParams(reinterpret_cast(&nativeEngine), new_napiWantParams, wantParams); + + NativeBoolean *boolResult = ConvertNativeValueTo(result); + if (boolResult == nullptr) { + return false; + } + + return *boolResult; +} + +void JsAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + Ability::OnConfigurationUpdated(configuration); + HILOG_INFO("%{public}s called.", __func__); + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + JsAbilityContext::ConfigurationUpdated(&nativeEngine, shellContextRef_, GetAbilityContext()->GetConfiguration()); + napi_value napiConfiguration = OHOS::AppExecFwk::WrapConfiguration( + reinterpret_cast(&nativeEngine), configuration); + NativeValue* jsConfiguration = reinterpret_cast(napiConfiguration); + CallObjectMethod("onConfigurationUpdated", &jsConfiguration, 1); +} + +void JsAbility::OnNewWant(const Want &want) +{ + HILOG_INFO("%{public}s begin.", __func__); + Ability::OnNewWant(want); + + HandleScope handleScope(jsRuntime_); + auto &nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue *value = jsAbilityObj_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get Ability object"); + return; + } + + napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(&nativeEngine), want); + NativeValue *jsWant = reinterpret_cast(napiWant); + + obj->SetProperty("lastRequestWant", jsWant); + + CallObjectMethod("onNewWant", &jsWant, 1); + HILOG_INFO("%{public}s end.", __func__); +} + void JsAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) { HILOG_INFO("%{public}s begin.", __func__); @@ -193,13 +304,64 @@ void JsAbility::OnAbilityResult(int requestCode, int resultCode, const Want &res HILOG_INFO("%{public}s end.", __func__); } -void JsAbility::OnRequestPermissionsFromUserResult(int requestCode, const std::vector &permissions, - const std::vector &grantResults) +sptr JsAbility::CallRequest() +{ + HILOG_INFO("JsAbility::CallRequest begin."); + if (jsAbilityObj_ == nullptr) { + HILOG_WARN("JsAbility::CallRequest Obj is nullptr"); + return nullptr; + } + HandleScope handleScope(jsRuntime_); + HILOG_DEBUG("JsAbility::CallRequest set runtime scope."); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + auto value = jsAbilityObj_->Get(); + if (value == nullptr) { + HILOG_ERROR("JsAbility::CallRequest value is nullptr"); + return nullptr; + } + + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("JsAbility::CallRequest obj is nullptr"); + return nullptr; + } + + auto method = obj->GetProperty("onCallRequest"); + if (method == nullptr || !method->IsCallable()) { + HILOG_ERROR("JsAbility::CallRequest method is %{public}s", method == nullptr ? "nullptr" : "not func"); + return nullptr; + } + + auto remoteJsObj = nativeEngine.CallFunction(value, method, nullptr, 0); + if (remoteJsObj == nullptr) { + HILOG_ERROR("JsAbility::CallRequest JsObj is nullptr"); + return nullptr; + } + + auto remoteObj = NAPI_ohos_rpc_getNativeRemoteObject( + reinterpret_cast(&nativeEngine), reinterpret_cast(remoteJsObj)); + if (remoteObj == nullptr) { + HILOG_ERROR("JsAbility::CallRequest obj is nullptr"); + } + + HILOG_INFO("JsAbility::CallRequest end."); + return remoteObj; +} + +void JsAbility::OnRequestPermissionsFromUserResult( + int requestCode, const std::vector &permissions, const std::vector &grantResults) { HILOG_INFO("%{public}s called.", __func__); + std::shared_ptr context = GetAbilityContext(); + if (context == nullptr) { + HILOG_WARN("JsAbility not attached to any runtime context!"); + return; + } + context->OnRequestPermissionsFromUserResult(requestCode, permissions, grantResults); + HILOG_INFO("%{public}s end.", __func__); } -void JsAbility::CallObjectMethod(const char* name, NativeValue* const* argv, size_t argc) +void JsAbility::CallObjectMethod(const char *name, NativeValue *const *argv, size_t argc) { HILOG_INFO("JsAbility::CallObjectMethod(%{public}s", name); @@ -209,16 +371,16 @@ void JsAbility::CallObjectMethod(const char* name, NativeValue* const* argv, siz } HandleScope handleScope(jsRuntime_); - auto& nativeEngine = jsRuntime_.GetNativeEngine(); + auto &nativeEngine = jsRuntime_.GetNativeEngine(); - NativeValue* value = jsAbilityObj_->Get(); - NativeObject* obj = ConvertNativeValueTo(value); + NativeValue *value = jsAbilityObj_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); if (obj == nullptr) { HILOG_ERROR("Failed to get Ability object"); return; } - NativeValue* methodOnCreate = obj->GetProperty(name); + NativeValue *methodOnCreate = obj->GetProperty(name); if (methodOnCreate == nullptr) { HILOG_ERROR("Failed to get '%{public}s' from Ability object", name); return; @@ -229,8 +391,8 @@ void JsAbility::CallObjectMethod(const char* name, NativeValue* const* argv, siz std::unique_ptr JsAbility::CreateAppWindowStage() { HandleScope handleScope(jsRuntime_); - auto& engine = jsRuntime_.GetNativeEngine(); - NativeValue* jsWindowStage = CreateJsWindowStage(engine, GetScene()); + auto &engine = jsRuntime_.GetNativeEngine(); + NativeValue *jsWindowStage = CreateJsWindowStage(engine, GetScene()); if (jsWindowStage == nullptr) { HILOG_ERROR("Failed to create jsWindowSatge object"); return nullptr; @@ -238,7 +400,15 @@ std::unique_ptr JsAbility::CreateAppWindowStage() return jsRuntime_.LoadSystemModule("application.WindowStage", &jsWindowStage, 1); } -void JsAbility::DoOnForeground(const Want& want) +void JsAbility::GetPageStackFromWant(const Want &want, std::string &pageStack) +{ + auto stringObj = AAFwk::IString::Query(want.GetParams().GetParam(PAGE_STACK_PROPERTY_NAME)); + if (stringObj != nullptr) { + pageStack = AAFwk::String::Unbox(stringObj); + } +} + +void JsAbility::DoOnForeground(const Want &want) { if (scene_ == nullptr) { if ((abilityContext_ == nullptr) || (sceneListener_ == nullptr)) { @@ -250,38 +420,37 @@ void JsAbility::DoOnForeground(const Want& want) HILOG_ERROR("%{public}s error. failed to create WindowScene instance!", __func__); return; } - int32_t displayId = Rosen::WindowScene::DEFAULT_DISPLAY_ID; if (setting_ != nullptr) { - std::string strDisplayId = setting_->GetProperty( - OHOS::AppExecFwk::AbilityStartSetting::WINDOW_DISPLAY_ID_KEY); + std::string strDisplayId = + setting_->GetProperty(OHOS::AppExecFwk::AbilityStartSetting::WINDOW_DISPLAY_ID_KEY); std::regex formatRegex("[0-9]{0,9}$"); std::smatch sm; bool flag = std::regex_match(strDisplayId, sm, formatRegex); - if (flag) { + if (flag && !strDisplayId.empty()) { displayId = std::stoi(strDisplayId); HILOG_INFO("%{public}s success. displayId is %{public}d", __func__, displayId); } else { - HILOG_INFO("%{public}s error. failed to formatRegex str", __func__); + HILOG_INFO("%{public}s failed to formatRegex:[%{public}s]", __func__, strDisplayId.c_str()); } } auto option = GetWindowOption(want); - Rosen::WMError ret = scene_->Init(displayId, abilityContext_, sceneListener_); + Rosen::WMError ret = scene_->Init(displayId, abilityContext_, sceneListener_, option); if (ret != Rosen::WMError::WM_OK) { HILOG_ERROR("%{public}s error. failed to init window scene!", __func__); return; } - // multi-instance ability continuation - HILOG_INFO("lauch reason = %{public}d, contentStorage = %{public}p", launchParam_.launchReason, + HILOG_INFO("lauch reason = %{public}d, contentStorage = %{public}p", + launchParam_.launchReason, abilityContext_->GetContentStorage()); if (IsRestoredInContinuation()) { - std::string pageStack = AAFwk::String::Unbox( - AAFwk::IString::Query(want.GetParams().GetParam(PAGE_STACK_PROPERTY_NAME))); + std::string pageStack; + GetPageStackFromWant(want, pageStack); HandleScope handleScope(jsRuntime_); - auto& engine = jsRuntime_.GetNativeEngine(); - scene_->GetMainWindow()->SetUIContent(abilityContext_, pageStack, &engine, - static_cast(abilityContext_->GetContentStorage())); + auto &engine = jsRuntime_.GetNativeEngine(); + scene_->GetMainWindow()->SetUIContent( + pageStack, &engine, static_cast(abilityContext_->GetContentStorage()), true); OnSceneRestored(); NotityContinuationResult(want, true); } else { diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp old mode 100644 new mode 100755 index 52a8a8bc64ec7b0a5d1600b84796e6ef79023841..404dd116c9bb4eb047c73268843a44b3e66f410e --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp @@ -21,17 +21,19 @@ #include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_data_struct_converter.h" -#include "js_runtime.h" #include "js_runtime_utils.h" +#include "ability_runtime/js_caller_complex.h" #include "napi_common_start_options.h" #include "napi_common_util.h" #include "napi_common_want.h" #include "napi_remote_object.h" #include "start_options.h" #include "want.h" +#include "event_handler.h" namespace OHOS { namespace AbilityRuntime { +constexpr int32_t INDEX_TWO = 2; constexpr size_t ARGC_ZERO = 0; constexpr size_t ARGC_ONE = 1; constexpr size_t ARGC_TWO = 2; @@ -51,18 +53,42 @@ NativeValue* JsAbilityContext::StartAbility(NativeEngine* engine, NativeCallback return (me != nullptr) ? me->OnStartAbility(*engine, *info) : nullptr; } +NativeValue* JsAbilityContext::StartAbilityWithAccount(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsAbilityContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnStartAbilityWithAccount(*engine, *info) : nullptr; +} + +NativeValue* JsAbilityContext::StartAbilityByCall(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsAbilityContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnStartAbilityByCall(*engine, *info) : nullptr; +} + NativeValue* JsAbilityContext::StartAbilityForResult(NativeEngine* engine, NativeCallbackInfo* info) { JsAbilityContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnStartAbilityForResult(*engine, *info) : nullptr; } +NativeValue* JsAbilityContext::StartAbilityForResultWithAccount(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsAbilityContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnStartAbilityForResultWithAccount(*engine, *info) : nullptr; +} + NativeValue* JsAbilityContext::ConnectAbility(NativeEngine* engine, NativeCallbackInfo* info) { JsAbilityContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnConnectAbility(*engine, *info) : nullptr; } +NativeValue* JsAbilityContext::ConnectAbilityWithAccount(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsAbilityContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnConnectAbilityWithAccount(*engine, *info) : nullptr; +} + NativeValue* JsAbilityContext::DisconnectAbility(NativeEngine* engine, NativeCallbackInfo* info) { JsAbilityContext* me = CheckParamsAndGetThis(engine, info); @@ -93,6 +119,12 @@ NativeValue* JsAbilityContext::RestoreWindowStage(NativeEngine* engine, NativeCa return (me != nullptr) ? me->OnRestoreWindowStage(*engine, *info) : nullptr; } +NativeValue* JsAbilityContext::SetMissionLabel(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsAbilityContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnSetMissionLabel(*engine, *info) : nullptr; +} + NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnStartAbility is called"); @@ -104,7 +136,8 @@ NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallba AAFwk::Want want; OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), reinterpret_cast(info.argv[0]), want); decltype(info.argc) unwrapArgc = 1; - + + HILOG_INFO("abilityName=%{public}s", want.GetElement().GetAbilityName().c_str()); AAFwk::StartOptions startOptions; if (info.argc > ARGC_ONE && info.argv[1]->TypeOf() == NATIVE_OBJECT) { HILOG_INFO("OnStartAbility start options is used."); @@ -138,6 +171,111 @@ NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallba return result; } +NativeValue* JsAbilityContext::OnStartAbilityWithAccount(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("OnStartAbilityWithAccount is called"); + if (info.argc == ARGC_ZERO) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), reinterpret_cast(info.argv[0]), want); + decltype(info.argc) unwrapArgc = 1; + HILOG_INFO("abilityName=%{public}s", want.GetElement().GetAbilityName().c_str()); + int32_t accountId = 0; + if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), + reinterpret_cast(info.argv[1]), accountId)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return engine.CreateUndefined(); + } + unwrapArgc++; + AAFwk::StartOptions startOptions; + if (info.argc > ARGC_TWO && info.argv[INDEX_TWO]->TypeOf() == NATIVE_OBJECT) { + HILOG_INFO("OnStartAbilityWithAccount start options is used."); + AppExecFwk::UnwrapStartOptions(reinterpret_cast(&engine), + reinterpret_cast(info.argv[ARGC_TWO]), startOptions); + unwrapArgc++; + } + + AsyncTask::CompleteCallback complete = + [weak = context_, want, accountId, startOptions, unwrapArgc]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released"); + task.Reject(engine, CreateJsError(engine, 1, "Context is released")); + return; + } + + auto errcode = (unwrapArgc == INDEX_TWO) ? + context->StartAbilityWithAccount(want, accountId, -1) : context->StartAbilityWithAccount( + want, accountId, startOptions, -1); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed.")); + } + }; + + NativeValue* lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue* JsAbilityContext::OnStartAbilityByCall(NativeEngine& engine, NativeCallbackInfo& info) +{ + int errCode = 0; + sptr remoteCallee; + if (info.argc != ARGC_ONE || info.argv[0]->TypeOf() != NATIVE_OBJECT) { + HILOG_ERROR("int put params count error"); + return engine.CreateUndefined(); + } + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), + reinterpret_cast(info.argv[0]), want); + NativeValue* callerComplex = nullptr; + std::mutex mutexlock; + std::condition_variable condition; + auto callBackDone = [&mutexlock, &condition, &remoteCallee](const sptr &obj) { + std::unique_lock lock(mutexlock); + remoteCallee = obj; + condition.notify_all(); + HILOG_INFO("OnStartAbilityByCall callBackDone is called"); + }; + auto releaseListen = [](const std::string &str) { + HILOG_INFO("OnStartAbilityByCall releaseListen is called %{public}s", str.c_str()); + }; + auto context = context_.lock(); + constexpr int CALLER_TIME_OUT = 5; // 5s + if (!context) { + HILOG_ERROR("context is released"); + errCode = -1; + return engine.CreateUndefined(); + } + std::shared_ptr callerCallBack = std::make_shared(); + callerCallBack->SetCallBack(callBackDone); + callerCallBack->SetOnRelease(releaseListen); + HILOG_INFO("OnStartAbilityByCall execute is StartAbility"); + errCode = context->StartAbility(want, callerCallBack); + if (remoteCallee == nullptr) { + HILOG_INFO("OnStartAbilityByCall lock mutexlock Done"); + std::unique_lock lock(mutexlock); + HILOG_INFO("OnStartAbilityByCall lock waiting callBackDone"); + if (condition.wait_for(lock, std::chrono::seconds(CALLER_TIME_OUT)) == std::cv_status::timeout) { + remoteCallee = nullptr; + errCode = -1; + HILOG_ERROR("Waiting callee timeout"); + return engine.CreateUndefined(); + } + } else { + HILOG_INFO("OnStartAbilityByCall remoteCallee isn~t nullptr"); + } + callerComplex = CreateJsCallerComplex(engine, context, remoteCallee, callerCallBack); + return callerComplex; +} + NativeValue* JsAbilityContext::OnStartAbilityForResult(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnStartAbilityForResult is called"); @@ -152,8 +290,16 @@ NativeValue* JsAbilityContext::OnStartAbilityForResult(NativeEngine& engine, Nat HILOG_ERROR("%s Failed to parse want!", __func__); return engine.CreateUndefined(); } + decltype(info.argc) unwrapArgc = 1; + AAFwk::StartOptions startOptions; + if (info.argc > ARGC_ONE && info.argv[1]->TypeOf() == NATIVE_OBJECT) { + HILOG_INFO("OnStartAbilityForResult start options is used."); + AppExecFwk::UnwrapStartOptions(reinterpret_cast(&engine), + reinterpret_cast(info.argv[1]), startOptions); + unwrapArgc++; + } - NativeValue* lastParam = info.argc == 1 ? nullptr : info.argv[1]; + NativeValue* lastParam = info.argc == unwrapArgc ? nullptr : info.argv[unwrapArgc]; NativeValue* result = nullptr; std::unique_ptr uasyncTask = CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, nullptr, &result); @@ -175,12 +321,70 @@ NativeValue* JsAbilityContext::OnStartAbilityForResult(NativeEngine& engine, Nat asyncTask->Reject(engine, CreateJsError(engine, 1, "context is released!")); } else { curRequestCode_ = (curRequestCode_ == INT_MAX) ? 0 : (curRequestCode_ + 1); - context->StartAbilityForResult(want, curRequestCode_, std::move(task)); + (unwrapArgc == 1) ? context->StartAbilityForResult(want, curRequestCode_, std::move(task)) : + context->StartAbilityForResult(want, startOptions, curRequestCode_, std::move(task)); } HILOG_INFO("OnStartAbilityForResult is called end"); return result; } +NativeValue* JsAbilityContext::OnStartAbilityForResultWithAccount(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("OnStartAbilityForResultWithAccount is called"); + if (info.argc == ARGC_ZERO) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + AAFwk::Want want; + if (!JsAbilityContext::UnWrapWant(engine, info.argv[0], want)) { + HILOG_ERROR("%s Failed to parse want!", __func__); + return engine.CreateUndefined(); + } + decltype(info.argc) unwrapArgc = 1; + int32_t accountId = 0; + if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), + reinterpret_cast(info.argv[1]), accountId)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return engine.CreateUndefined(); + } + unwrapArgc++; + AAFwk::StartOptions startOptions; + if (info.argc > ARGC_TWO && info.argv[INDEX_TWO]->TypeOf() == NATIVE_OBJECT) { + HILOG_INFO("OnStartAbilityForResultWithAccount start options is used."); + AppExecFwk::UnwrapStartOptions(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_TWO]), startOptions); + unwrapArgc++; + } + NativeValue* lastParam = info.argc == unwrapArgc ? nullptr : info.argv[unwrapArgc]; + NativeValue* result = nullptr; + std::unique_ptr uasyncTask = + CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, nullptr, &result); + std::shared_ptr asyncTask = std::move(uasyncTask); + RuntimeTask task = [&engine, asyncTask](int resultCode, const AAFwk::Want& want) { + HILOG_INFO("OnStartAbilityForResultWithAccount async callback is called"); + NativeValue* abilityResult = JsAbilityContext::WrapAbilityResult(engine, resultCode, want); + if (abilityResult == nullptr) { + HILOG_WARN("wrap abilityResult failed"); + asyncTask->Reject(engine, CreateJsError(engine, 1, "failed to get result data!")); + } else { + asyncTask->Resolve(engine, abilityResult); + } + HILOG_INFO("OnStartAbilityForResultWithAccount async callback is called end"); + }; + auto context = context_.lock(); + if (context == nullptr) { + HILOG_WARN("context is released"); + asyncTask->Reject(engine, CreateJsError(engine, 1, "context is released!")); + } else { + curRequestCode_ = (curRequestCode_ == INT_MAX) ? 0 : (curRequestCode_ + 1); + (unwrapArgc == INDEX_TWO) ? context->StartAbilityForResultWithAccount( + want, accountId, curRequestCode_, std::move(task)) : context->StartAbilityForResultWithAccount( + want, accountId, startOptions, curRequestCode_, std::move(task)); + } + HILOG_INFO("OnStartAbilityForResultWithAccount is called end"); + return result; +} + NativeValue* JsAbilityContext::OnTerminateSelfWithResult(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnTerminateSelfWithResult is called"); @@ -237,7 +441,7 @@ NativeValue* JsAbilityContext::OnConnectAbility(NativeEngine& engine, NativeCall want.GetElement().GetAbilityName().c_str()); // unwarp connection - std::shared_ptr connection = std::make_shared(&engine); + sptr connection = new JSAbilityConnection(engine); connection->SetJsConnectionObject(info.argv[1]); int64_t connectId = g_serialNumber; ConnectionKey key; @@ -249,7 +453,7 @@ NativeValue* JsAbilityContext::OnConnectAbility(NativeEngine& engine, NativeCall } else { g_serialNumber = 0; } - HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, connection.get()); + HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr()); AsyncTask::CompleteCallback complete = [weak = context_, want, connection, connectId](NativeEngine& engine, AsyncTask& task, int32_t status) { HILOG_INFO("OnConnectAbility begin"); @@ -271,6 +475,67 @@ NativeValue* JsAbilityContext::OnConnectAbility(NativeEngine& engine, NativeCall return engine.CreateNumber(connectId); } +NativeValue* JsAbilityContext::OnConnectAbilityWithAccount(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("OnConnectAbility is called"); + // only support three params + if (info.argc != ARGC_THREE) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + // unwrap want + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), + reinterpret_cast(info.argv[0]), want); + HILOG_INFO("%{public}s bundlename:%{public}s abilityname:%{public}s", + __func__, + want.GetBundle().c_str(), + want.GetElement().GetAbilityName().c_str()); + + int32_t accountId = 0; + if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), + reinterpret_cast(info.argv[1]), accountId)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return engine.CreateUndefined(); + } + + // unwarp connection + sptr connection = new JSAbilityConnection(engine); + connection->SetJsConnectionObject(info.argv[INDEX_TWO]); + int64_t connectId = g_serialNumber; + ConnectionKey key; + key.id = g_serialNumber; + key.want = want; + abilityConnects_.emplace(key, connection); + if (g_serialNumber < INT64_MAX) { + g_serialNumber++; + } else { + g_serialNumber = 0; + } + HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr()); + AsyncTask::CompleteCallback complete = + [weak = context_, want, accountId, connection, connectId]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("OnConnectAbilityWithAccount begin"); + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released"); + task.Reject(engine, CreateJsError(engine, 1, "Context is released")); + return; + } + HILOG_INFO("context->ConnectAbilityWithAccount connection:%{public}d", (int32_t)connectId); + if (!context->ConnectAbilityWithAccount(want, accountId, connection)) { + connection->CallJsFailed(ERROR_CODE_ONE); + } + task.Resolve(engine, engine.CreateUndefined()); + }; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result)); + return engine.CreateNumber(connectId); +} + NativeValue* JsAbilityContext::OnDisconnectAbility(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnDisconnectAbility is called"); @@ -284,20 +549,20 @@ NativeValue* JsAbilityContext::OnDisconnectAbility(NativeEngine& engine, NativeC AAFwk::Want want; // unwrap connectId int64_t connectId = -1; - std::shared_ptr connection = nullptr; + sptr connection = nullptr; napi_get_value_int64(reinterpret_cast(&engine), reinterpret_cast(info.argv[0]), &connectId); HILOG_INFO("OnDisconnectAbility connection:%{public}d", (int32_t)connectId); auto item = std::find_if(abilityConnects_.begin(), abilityConnects_.end(), - [&connectId](const std::map>::value_type &obj) { + [&connectId](const std::map>::value_type &obj) { return connectId == obj.first.id; }); if (item != abilityConnects_.end()) { // match id want = item->first.want; connection = item->second; - HILOG_INFO("%{public}s find conn ability:%{public}p exist", __func__, item->second.get()); + HILOG_INFO("%{public}s find conn ability:%{public}p exist", __func__, item->second.GetRefPtr()); } else { HILOG_INFO("%{public}s not find conn exist.", __func__); } @@ -366,7 +631,7 @@ NativeValue* JsAbilityContext::OnRequestPermissionsFromUser(NativeEngine& engine { HILOG_INFO("OnRequestPermissionsFromUser is called"); - if (info.argc != ARGC_TWO && info.argc != ARGC_THREE) { + if (info.argc != ARGC_ONE && info.argc != ARGC_TWO) { HILOG_ERROR("Not enough params"); return engine.CreateUndefined(); } @@ -374,42 +639,39 @@ NativeValue* JsAbilityContext::OnRequestPermissionsFromUser(NativeEngine& engine std::vector permissionList; if (!OHOS::AppExecFwk::UnwrapArrayStringFromJS(reinterpret_cast(&engine), reinterpret_cast(info.argv[0]), permissionList)) { - HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); + HILOG_ERROR("%{public}s called, the first parameter is invalid.", __func__); return engine.CreateUndefined(); } - int32_t requestCode = 0; - if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), - reinterpret_cast(info.argv[1]), requestCode)) { - HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); - return engine.CreateUndefined(); + if (permissionList.size() == 0) { + HILOG_ERROR("%{public}s called, params do not meet specification.", __func__); } - AsyncTask::CompleteCallback complete = - [weak = context_, permissionList, requestCode](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto context = weak.lock(); - if (!context) { - HILOG_WARN("context is released"); - task.Reject(engine, CreateJsError(engine, 1, "Context is released")); - return; - } - - HILOG_INFO("RequestPermissionsFromUser is called"); - context->RequestPermissionsFromUser(permissionList, requestCode); - - NativeValue* objValue = engine.CreateObject(); - NativeObject* object = ConvertNativeValueTo(objValue); - object->SetProperty("requestCode", CreateJsValue(engine, requestCode)); - object->SetProperty("permissions", CreateNativeArray(engine, permissionList)); - std::vector grantResults(permissionList.size()); - object->SetProperty("authResults", CreateNativeArray(engine, grantResults)); - task.Resolve(engine, objValue); - }; - - NativeValue* lastParam = (info.argc == ARGC_TWO) ? nullptr : info.argv[ARGC_TWO]; + NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[ARGC_ONE]; NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + auto uasyncTask = CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, nullptr, &result); + std::shared_ptr asyncTask = std::move(uasyncTask); + PermissionRequestTask task = + [&engine, asyncTask](const std::vector &permissions, const std::vector &grantResults) { + HILOG_INFO("OnRequestPermissionsFromUser async callback is called"); + NativeValue* requestResult = JsAbilityContext::WrapPermissionRequestResult(engine, permissions, grantResults); + if (requestResult == nullptr) { + HILOG_WARN("wrap requestResult failed"); + asyncTask->Reject(engine, CreateJsError(engine, 1, "failed to get granted result data!")); + } else { + asyncTask->Resolve(engine, requestResult); + } + HILOG_INFO("OnRequestPermissionsFromUser async callback is called end"); + }; + auto context = context_.lock(); + if (context == nullptr) { + HILOG_WARN("context is released"); + asyncTask->Reject(engine, CreateJsError(engine, 1, "context is released!")); + } else { + curRequestCode_ = (curRequestCode_ == INT_MAX) ? 0 : (curRequestCode_ + 1); + context->RequestPermissionsFromUser(permissionList, curRequestCode_, std::move(task)); + } + HILOG_INFO("OnRequestPermissionsFromUser is called end"); return result; } @@ -432,6 +694,45 @@ NativeValue* JsAbilityContext::OnRestoreWindowStage(NativeEngine& engine, Native return engine.CreateUndefined(); } +NativeValue* JsAbilityContext::OnSetMissionLabel(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("OnSetMissionLabel is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE) { + HILOG_ERROR("OnSetMissionLabel, Not enough params"); + return engine.CreateUndefined(); + } + + std::string label; + if (!ConvertFromJsValue(engine, info.argv[0], label)) { + HILOG_ERROR("OnSetMissionLabel, parse label failed."); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = + [weak = context_, label](NativeEngine& engine, AsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released"); + task.Reject(engine, CreateJsError(engine, 1, "Context is released")); + return; + } + + auto errcode = context->SetMissionLabel(label); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "SetMissionLabel failed.")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + bool JsAbilityContext::UnWrapWant(NativeEngine& engine, NativeValue* argv, AAFwk::Want& want) { if (argv == nullptr) { @@ -488,6 +789,44 @@ NativeValue* JsAbilityContext::WrapAbilityResult(NativeEngine& engine, const int return jAbilityResult; } +NativeValue* JsAbilityContext::WrapPermissionRequestResult(NativeEngine& engine, + const std::vector &permissions, const std::vector &grantResults) +{ + NativeValue* jsPermissionRequestResult = engine.CreateObject(); + NativeObject* permissionRequestResult = ConvertNativeValueTo(jsPermissionRequestResult); + permissionRequestResult->SetProperty("permissions", CreateNativeArray(engine, permissions)); + permissionRequestResult->SetProperty("authResults", CreateNativeArray(engine, grantResults)); + return jsPermissionRequestResult; +} + +void JsAbilityContext::ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, + const std::shared_ptr &config) +{ + HILOG_INFO("ConfigurationUpdated begin."); + if (jsContext == nullptr || config == nullptr) { + HILOG_INFO("jsContext is nullptr."); + return; + } + + NativeValue* value = jsContext->Get(); + NativeObject* object = ConvertNativeValueTo(value); + if (object == nullptr) { + HILOG_INFO("object is nullptr."); + return; + } + + NativeValue* method = object->GetProperty("onUpdateConfiguration"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onUpdateConfiguration from object"); + return; + } + HILOG_INFO("JSAbilityConnection::CallFunction onUpdateConfiguration, success"); + + HILOG_INFO("OnAbilityConnectDone begin NAPI_ohos_rpc_CreateJsRemoteObject"); + NativeValue* argv[] = {CreateJsConfiguration(*engine, *config)}; + engine->CallFunction(value, method, argv, ARGC_ONE); +} + NativeValue* CreateJsAbilityContext(NativeEngine& engine, std::shared_ptr context) { NativeValue* objValue = CreateJsBaseContext(engine, context); @@ -503,18 +842,29 @@ NativeValue* CreateJsAbilityContext(NativeEngine& engine, std::shared_ptrSetProperty("abilityInfo", CreateJsAbilityInfo(engine, *abilityInfo)); } + auto configuration = context->GetConfiguration(); + if (configuration != nullptr) { + object->SetProperty("configuration", CreateJsConfiguration(engine, *configuration)); + } + BindNativeFunction(engine, *object, "startAbility", JsAbilityContext::StartAbility); + BindNativeFunction(engine, *object, "startAbilityWithAccount", JsAbilityContext::StartAbilityWithAccount); + BindNativeFunction(engine, *object, "startAbilityByCall", JsAbilityContext::StartAbilityByCall); BindNativeFunction(engine, *object, "startAbilityForResult", JsAbilityContext::StartAbilityForResult); + BindNativeFunction(engine, *object, "startAbilityForResultWithAccount", + JsAbilityContext::StartAbilityForResultWithAccount); BindNativeFunction(engine, *object, "connectAbility", JsAbilityContext::ConnectAbility); + BindNativeFunction(engine, *object, "connectAbilityWithAccount", JsAbilityContext::ConnectAbilityWithAccount); BindNativeFunction(engine, *object, "disconnectAbility", JsAbilityContext::DisconnectAbility); BindNativeFunction(engine, *object, "terminateSelf", JsAbilityContext::TerminateSelf); BindNativeFunction(engine, *object, "terminateSelfWithResult", JsAbilityContext::TerminateSelfWithResult); BindNativeFunction(engine, *object, "requestPermissionsFromUser", JsAbilityContext::RequestPermissionsFromUser); BindNativeFunction(engine, *object, "restoreWindowStage", JsAbilityContext::RestoreWindowStage); + BindNativeFunction(engine, *object, "setMissionLabel", JsAbilityContext::SetMissionLabel); return objValue; } -JSAbilityConnection::JSAbilityConnection(NativeEngine* engine) : engine_(engine) {} +JSAbilityConnection::JSAbilityConnection(NativeEngine& engine) : engine_(engine) {} JSAbilityConnection::~JSAbilityConnection() = default; @@ -559,18 +909,14 @@ void JSAbilityConnection::HandleOnAbilityConnectDone(const AppExecFwk::ElementNa return; } HILOG_INFO("JSAbilityConnection::CallFunction onConnect, success"); - // two params - if (engine_ == nullptr) { - HILOG_ERROR("engine_ nullptr"); - return; - } + // wrap RemoteObject HILOG_INFO("OnAbilityConnectDone begin NAPI_ohos_rpc_CreateJsRemoteObject"); napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( - reinterpret_cast(engine_.get()), remoteObject); + reinterpret_cast(&engine_), remoteObject); NativeValue* nativeRemoteObject = reinterpret_cast(napiRemoteObject); NativeValue* argv[] = { ConvertElement(element), nativeRemoteObject }; - engine_->CallFunction(value, methodOnConnect, argv, ARGC_TWO); + engine_.CallFunction(value, methodOnConnect, argv, ARGC_TWO); HILOG_INFO("OnAbilityConnectDone end"); } @@ -621,7 +967,7 @@ void JSAbilityConnection::HandleOnAbilityDisconnectDone(const AppExecFwk::Elemen std::string abilityName = element.GetAbilityName(); auto item = std::find_if(abilityConnects_.begin(), abilityConnects_.end(), [bundleName, abilityName] ( - const std::map>::value_type &obj) { + const std::map>::value_type &obj) { return (bundleName == obj.first.want.GetBundle()) && (abilityName == obj.first.want.GetElement().GetAbilityName()); }); @@ -630,14 +976,10 @@ void JSAbilityConnection::HandleOnAbilityDisconnectDone(const AppExecFwk::Elemen abilityConnects_.erase(item); HILOG_INFO("OnAbilityDisconnectDone erase abilityConnects_.size:%{public}zu", abilityConnects_.size()); } - // one params - if (engine_ == nullptr) { - HILOG_ERROR("engine_ nullptr"); - return; - } + NativeValue* argv[] = { ConvertElement(element) }; HILOG_INFO("OnAbilityDisconnectDone CallFunction success"); - engine_->CallFunction(value, method, argv, ARGC_ONE); + engine_.CallFunction(value, method, argv, ARGC_ONE); } void JSAbilityConnection::CallJsFailed(int32_t errorCode) @@ -659,25 +1001,22 @@ void JSAbilityConnection::CallJsFailed(int32_t errorCode) HILOG_ERROR("Failed to get onFailed from object"); return; } - if (engine_ == nullptr) { - HILOG_ERROR("engine_ nullptr"); - return; - } - NativeValue* argv[] = {engine_->CreateNumber(errorCode)}; + + NativeValue* argv[] = {engine_.CreateNumber(errorCode)}; HILOG_INFO("CallJsFailed CallFunction success"); - engine_->CallFunction(value, method, argv, ARGC_ONE); + engine_.CallFunction(value, method, argv, ARGC_ONE); HILOG_INFO("CallJsFailed end"); } NativeValue* JSAbilityConnection::ConvertElement(const AppExecFwk::ElementName &element) { - napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast(engine_.get()), element); + napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast(&engine_), element); return reinterpret_cast(napiElementName); } void JSAbilityConnection::SetJsConnectionObject(NativeValue* jsConnectionObject) { - jsConnectionObject_ = std::unique_ptr(engine_->CreateReference(jsConnectionObject, 1)); + jsConnectionObject_ = std::unique_ptr(engine_.CreateReference(jsConnectionObject, 1)); } } // namespace AbilityRuntime -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb553457003aa3e85fcf3ba3ce53745eba92e499 --- /dev/null +++ b/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "hilog_wrapper.h" +#include "js_context_utils.h" +#include "js_data_struct_converter.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" +#include "ability_runtime/js_caller_complex.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { // nameless +static std::map logcast = { + { NATIVE_UNDEFINED, std::string("NATIVE_UNDEFINED") }, + { NATIVE_NULL, std::string("NATIVE_NULL") }, + { NATIVE_BOOLEAN, std::string("NATIVE_BOOLEAN") }, + { NATIVE_NUMBER, std::string("NATIVE_NUMBER") }, + { NATIVE_STRING, std::string("NATIVE_STRING") }, + { NATIVE_SYMBOL, std::string("NATIVE_SYMBOL") }, + { NATIVE_OBJECT, std::string("NATIVE_OBJECT") }, + { NATIVE_FUNCTION, std::string("NATIVE_FUNCTION") }, + { NATIVE_EXTERNAL, std::string("NATIVE_EXTERNAL") }, + { NATIVE_BIGINT, std::string("NATIVE_BIGINT") }, +}; + +class JsCallerComplex { +public: + explicit JsCallerComplex( + NativeEngine& engine, std::shared_ptr context, sptr callee, + std::shared_ptr callerCallBack) : context_(context), callee_(callee), + releaseCallBackEngine_(engine), callerCallBackObj_(callerCallBack), jsreleaseCallBackObj_(nullptr) + { + handler_ = std::make_shared(AppExecFwk::EventRunner::GetMainEventRunner()); + }; + virtual~JsCallerComplex() {}; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + if (data == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s is called, but input parameters is nullptr", __func__); + return; + } + std::unique_ptr(static_cast(data)); + } + + static NativeValue* JsRelease(NativeEngine* engine, NativeCallbackInfo* info) + { + if (engine == nullptr || info == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s is called, but input parameters %{public}s is nullptr", + __func__, + ((engine == nullptr) ? "engine" : "info")); + return nullptr; + } + + auto object = CheckParamsAndGetThis(engine, info); + if (object == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s is called, CheckParamsAndGetThis return nullptr", __func__); + return nullptr; + } + + return object->ReleaseInner(*engine, *info); + } + + static NativeValue* JsSetOnReleaseCallBack(NativeEngine* engine, NativeCallbackInfo* info) + { + if (engine == nullptr || info == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s is called, but input parameters %{public}s is nullptr", + __func__, + ((engine == nullptr) ? "engine" : "info")); + return nullptr; + } + + auto object = CheckParamsAndGetThis(engine, info); + if (object == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s is called, CheckParamsAndGetThis return nullptr", __func__); + return nullptr; + } + + return object->SetOnReleaseCallBackInner(*engine, *info); + } + + sptr GetRemoteObject() + { + return callee_; + } + +private: + + void OnReleaseNotify(const std::string &str) + { + HILOG_DEBUG("OnReleaseNotify begin"); + if (handler_ == nullptr) { + HILOG_ERROR(""); + return; + } + + auto task = [notify = this, &str] () { notify->OnReleaseNotifyTask(str); }; + handler_->PostTask(task, "OnReleaseNotify"); + HILOG_DEBUG("OnReleaseNotify end"); + } + + void OnReleaseNotifyTask(const std::string &str) + { + HILOG_DEBUG("OnReleaseNotifyTask begin"); + if (jsreleaseCallBackObj_ == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, jsreleaseObj is nullptr", __func__); + return; + } + + NativeValue* value = jsreleaseCallBackObj_->Get(); + NativeValue* callback = jsreleaseCallBackObj_->Get(); + NativeValue* args[] = { CreateJsValue(releaseCallBackEngine_, str) }; + releaseCallBackEngine_.CallFunction(value, callback, args, 1); + HILOG_DEBUG("OnReleaseNotifyTask end"); + } + + NativeValue* ReleaseInner(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_DEBUG("JsCallerComplex::%{public}s, called", __func__); + constexpr size_t ARGC_ZERO = 0; + constexpr size_t ARGC_ONE = 1; + int errCode = 0; + AsyncTask::ExecuteCallback execute = + [weak = context_, callback = callerCallBackObj_, &errCode] (NativeEngine& engine, AsyncTask& task) { + auto context = weak.lock(); + if (context == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, context is nullptr", "ReleaseInner::ExecuteCallback"); + errCode = -1; + return; + } + + errCode = context->ReleaseAbility(callback); + HILOG_DEBUG("JsCallerComplex::%{public}s %{public}d, end", "ReleaseInner::ExecuteCallback", errCode); + }; + AsyncTask::CompleteCallback complete = + [errCode] (NativeEngine& engine, AsyncTask& task, int32_t status) { + if (errCode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errCode, "CallerComplex Release Failed.")); + } + HILOG_DEBUG("JsCallerComplex::%{public}s, end", "ReleaseInner::CompleteCallback"); + }; + + NativeValue* lastParam = ((info.argc == ARGC_ONE) ? info.argv[ARGC_ZERO] : nullptr); + NativeValue* retsult = nullptr; + AsyncTask::Schedule( + engine, + CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &retsult)); + + return retsult; + } + + NativeValue* SetOnReleaseCallBackInner(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_DEBUG("JsCallerComplex::%{public}s, begin", __func__); + constexpr size_t ARGC_ONE = 1; + constexpr size_t ARGC_TWO = 2; + bool errCode = true; + if (info.argc >= ARGC_TWO) { + HILOG_ERROR("JsCallerComplex::%{public}s, Invalid input params", __func__); + return engine.CreateUndefined(); + } + if (!info.argv[0]->IsCallable()) { + HILOG_ERROR("JsCallerComplex::%{public}s, IsCallable is %{public}s.", + __func__, ((info.argv[0]->IsCallable()) ? "true" : "false")); + return engine.CreateUndefined(); + } + while (errCode) { + if (callerCallBackObj_ == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__); + errCode = false; + break; + } + auto param1 = info.argv[0]; + if (param1 == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__); + errCode = false; + break; + } + jsreleaseCallBackObj_ = + std::unique_ptr(releaseCallBackEngine_.CreateReference(param1, 1)); + auto task = [notify = this] (const std::string &str) { notify->OnReleaseNotify(str); }; + callerCallBackObj_->SetOnRelease(task); + break; + } + AsyncTask::CompleteCallback complete = + [errCode] (NativeEngine& engine, AsyncTask& task, int32_t status) { + if (errCode) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, -1, "CallerComplex On Release CallBack Failed.")); + } + HILOG_DEBUG("JsCallerComplex::%{public}s, %{public}s end", "ReleaseInner::CompleteCallback", + (errCode ? "true" : "false")); + }; + NativeValue* lastParam = ((info.argc == ARGC_TWO) ? info.argv[ARGC_ONE] : nullptr); + NativeValue* retsult = nullptr; + AsyncTask::Schedule(engine, + CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &retsult)); + HILOG_DEBUG("JsCallerComplex::%{public}s, end", __func__); + return retsult; + } + +private: + std::weak_ptr context_; + sptr callee_; + NativeEngine& releaseCallBackEngine_; + std::shared_ptr callerCallBackObj_; + std::unique_ptr jsreleaseCallBackObj_; + std::shared_ptr handler_; +}; +} // nameless + +NativeValue* CreateJsCallerComplex( + NativeEngine& engine, std::shared_ptr context, sptr callee, + std::shared_ptr callerCallBack) +{ + HILOG_DEBUG("JsCallerComplex::%{public}s, begin", __func__); + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + auto jsCaller = std::make_unique(engine, context, callee, callerCallBack); + if (jsCaller == nullptr) { + HILOG_ERROR("%{public}s is called, but make_unique is nullptr", __func__); + return engine.CreateUndefined(); + } + + auto remoteObj = jsCaller->GetRemoteObject(); + if (remoteObj == nullptr) { + HILOG_ERROR("%{public}s is called,remoteObj is nullptr", __func__); + return engine.CreateUndefined(); + } + + object->SetNativePointer(jsCaller.release(), JsCallerComplex::Finalizer, nullptr); + object->SetProperty("callee", CreateJsCalleeRemoteObject(engine, remoteObj)); + BindNativeFunction(engine, *object, "release", JsCallerComplex::JsRelease); + BindNativeFunction(engine, *object, "onRelease", JsCallerComplex::JsSetOnReleaseCallBack); + + HILOG_DEBUG("JsCallerComplex::%{public}s, end", __func__); + return objValue; +} + +NativeValue* CreateJsCalleeRemoteObject(NativeEngine& engine, sptr callee) +{ + napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( + reinterpret_cast(&engine), callee); + NativeValue* nativeRemoteObject = reinterpret_cast(napiRemoteObject); + + if (nativeRemoteObject == nullptr) { + HILOG_ERROR("%{public}s is called, but remoteObj is nullptr", __func__); + } + + return nativeRemoteObject; +} +} // AbilityRuntime +} // OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_window_stage.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_window_stage.cpp index 6c13f06591426cb0cfc14c2c0669bb9a56cc6cb9..4f50cf344b5a0a8dada3c0628f65c2cec12c1998 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/js_window_stage.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_window_stage.cpp @@ -23,6 +23,14 @@ namespace OHOS { namespace AbilityRuntime { +namespace { +const int CONTENT_STORAGE_ARG = 2; +constexpr size_t ARGC_TWO = 2; +constexpr size_t ARGC_THREE = 3; +constexpr size_t INDEX_ONE = 1; +constexpr size_t INDEX_TWO = 2; +} // namespace + void JsWindowStage::Finalizer(NativeEngine* engine, void* data, void* hint) { HILOG_INFO("JsWindowStage::Finalizer is called"); @@ -57,6 +65,20 @@ NativeValue* JsWindowStage::Off(NativeEngine* engine, NativeCallbackInfo* info) return (me != nullptr) ? me->OffEvent(*engine, *info) : nullptr; } +NativeValue* JsWindowStage::LoadContent(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsWindowStage::LoadContent is called"); + JsWindowStage* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnLoadContent(*engine, *info) : nullptr; +} + +NativeValue* JsWindowStage::GetWindowMode(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsWindowStage::GetWindowMode is called"); + JsWindowStage* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetWindowMode(*engine, *info) : nullptr; +} + void JsWindowStage::AfterForeground() { LifeCycleCallBack(WindowStageEventType::VISIBLE); @@ -111,18 +133,14 @@ NativeValue* JsWindowStage::OnSetUIContent(NativeEngine& engine, NativeCallbackI HILOG_ERROR("JsWindowStage::OnSetUIContent info->argv[0] InValid"); return engine.CreateUndefined(); } - auto contentValue = objContext->GetProperty("__context_impl__"); - auto contentObj = AbilityRuntime::ConvertNativeValueTo(contentValue); - if (contentObj == nullptr) { - HILOG_ERROR("JsWindowStage::OnSetUIContent contentObj is nullptr"); - return engine.CreateUndefined(); - } - auto jsContext = static_cast(contentObj->GetNativePointer()); - if (jsContext == nullptr) { - HILOG_ERROR("JsWindowStage::OnSetUIContent jsContext is nullptr"); + + auto context = static_cast*>(objContext->GetNativePointer()); + auto abilityContext = Context::ConvertTo(context->lock()); + if (abilityContext == nullptr) { + HILOG_ERROR("JsWindowStage::OnSetUIContent context is nullptr"); return engine.CreateUndefined(); } - std::shared_ptr abilityContext = jsContext->GetAbilityContext(); + HILOG_INFO("JsWindowStage::OnSetUIContent Get context: %{public}p", abilityContext.get()); // Parse info->argv[1] as url @@ -133,7 +151,7 @@ NativeValue* JsWindowStage::OnSetUIContent(NativeEngine& engine, NativeCallbackI } HILOG_INFO("JsWindowStage::OnSetUIContent Get url: %{public}s", contextUrl.c_str()); - windowScene_->GetMainWindow()->SetUIContent(abilityContext, contextUrl, &engine, nullptr); + windowScene_->GetMainWindow()->SetUIContent(contextUrl, &engine, info.argv[CONTENT_STORAGE_ARG]); return engine.CreateUndefined(); } @@ -149,11 +167,11 @@ NativeValue* JsWindowStage::OnGetMainWindow(NativeEngine& engine, NativeCallback [this](NativeEngine& engine, AsyncTask& task, int32_t status) { auto window = windowScene_->GetMainWindow(); if (window != nullptr) { - task.Resolve(engine, CreateJsWindowObject(engine, window)); + task.Resolve(engine, OHOS::Rosen::CreateJsWindowObject(engine, window)); HILOG_INFO("JsWindowStage::OnGetMainWindow success"); } else { task.Reject(engine, CreateJsError(engine, - static_cast(WMError::WM_ERROR_NULLPTR), + static_cast(Rosen::WMError::WM_ERROR_NULLPTR), "JsWindowStage::OnGetMainWindow failed.")); } }; @@ -273,6 +291,79 @@ NativeValue* JsWindowStage::OffEvent(NativeEngine& engine, NativeCallbackInfo& i return engine.CreateUndefined(); } +NativeValue* JsWindowStage::OnLoadContent(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("JsWindowStage::OnLoadContent is called"); + if (info.argc <= 0 || windowScene_ == nullptr) { + HILOG_ERROR("JsWindowStage param not match or windowScene_ is nullptr"); + return engine.CreateUndefined(); + } + std::string contextUrl; + if (!ConvertFromJsValue(engine, info.argv[0], contextUrl)) { + HILOG_ERROR("Failed to convert parameter to context url"); + return engine.CreateUndefined(); + } + NativeValue* storage = nullptr; + NativeValue* callBack = nullptr; + if (info.argc == ARGC_TWO) { + NativeValue* value = info.argv[INDEX_ONE]; + if (value->TypeOf() == NATIVE_FUNCTION) { + callBack = info.argv[INDEX_ONE]; + } else { + storage = info.argv[INDEX_ONE]; + } + } else if (info.argc == ARGC_THREE) { + storage = info.argv[INDEX_ONE]; + callBack = info.argv[INDEX_TWO]; + } + contentStorage_ = static_cast(storage); + AsyncTask::CompleteCallback complete = + [this, contextUrl](NativeEngine& engine, AsyncTask& task, int32_t status) { + auto win = windowScene_->GetMainWindow(); + if (win == nullptr) { + task.Reject(engine, + CreateJsError(engine, static_cast(Rosen::WMError::WM_ERROR_NULLPTR), + "JsWindowStage::OnLoadContent failed.")); + } + Rosen::WMError ret = win->SetUIContent(contextUrl, &engine, + static_cast(contentStorage_), false); + if (ret == Rosen::WMError::WM_OK) { + task.Resolve(engine, engine.CreateUndefined()); + HILOG_INFO("JsWindowStage::OnLoadContent success"); + } else { + task.Reject(engine, + CreateJsError(engine, static_cast(ret), "JsWindowStage::OnLoadContent failed.")); + } + }; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, callBack, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue* JsWindowStage::OnGetWindowMode(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("JsWindowStage::OnGetWindowMode is called"); + AsyncTask::CompleteCallback complete = + [this](NativeEngine& engine, AsyncTask& task, int32_t status) { + auto window = windowScene_->GetMainWindow(); + if (window == nullptr) { + task.Reject(engine, CreateJsError(engine, static_cast(Rosen::WMError::WM_ERROR_NULLPTR), + "JsWindowStage::OnGetWindowMode failed.")); + HILOG_ERROR("JsWindowStage window is nullptr"); + return; + } + Rosen::WindowMode mode = window->GetMode(); + task.Resolve(engine, CreateJsValue(engine, mode)); + HILOG_INFO("JsWindowStage OnGetWindowMode success"); + }; + + NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} NativeValue* CreateJsWindowStage(NativeEngine& engine, std::shared_ptr windowScene) @@ -287,8 +378,12 @@ NativeValue* CreateJsWindowStage(NativeEngine& engine, AbilityRuntime::BindNativeFunction(engine, *object, "setUIContent", JsWindowStage::SetUIContent); + AbilityRuntime::BindNativeFunction(engine, + *object, "loadContent", JsWindowStage::LoadContent); AbilityRuntime::BindNativeFunction(engine, *object, "getMainWindow", JsWindowStage::GetMainWindow); + AbilityRuntime::BindNativeFunction(engine, + *object, "getWindowMode", JsWindowStage::GetWindowMode); AbilityRuntime::BindNativeFunction(engine, *object, "on", JsWindowStage::On); AbilityRuntime::BindNativeFunction(engine, *object, "off", JsWindowStage::Off); diff --git a/frameworks/kits/ability/native/src/ability_runtime/window/js_window.cpp b/frameworks/kits/ability/native/src/ability_runtime/window/js_window.cpp deleted file mode 100644 index a369266342fa7640b38d8d6307ba0b9bcf19dc75..0000000000000000000000000000000000000000 --- a/frameworks/kits/ability/native/src/ability_runtime/window/js_window.cpp +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "js_window.h" -#include "window.h" -#include "window_manager_hilog.h" -#include "window_option.h" - -using namespace OHOS::Rosen; - -namespace OHOS { -namespace AbilityRuntime { -using namespace AbilityRuntime; -namespace { - constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0, "JsWindow"}; -} - -void JsWindow::Finalizer(NativeEngine* engine, void* data, void* hint) -{ - WLOGFI("JsWindow::Finalizer is called"); - std::unique_ptr(static_cast(data)); -} - -NativeValue* JsWindow::Show(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::Show is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnShow(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::Destroy(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::Destroy is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnDestroy(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::Hide(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::Hide is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnHide(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::MoveTo(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::MoveTo is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnMoveTo(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::Resize(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::Resize is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnResize(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::SetWindowType(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::SetWindowType is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnSetWindowType(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::SetWindowMode(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::SetWindowMode is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnSetWindowMode(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::GetProperties(NativeEngine* engine, NativeCallbackInfo* info) -{ - WLOGFI("JsWindow::GetProperties is called"); - JsWindow* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnGetProperties(*engine, *info) : nullptr; -} - -NativeValue* JsWindow::OnShow(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnShow is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = - [this](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto ret = windowToken_->Show(); - if (ret == OHOS::Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - WLOGFI("JsWindow::OnShow success"); - } else { - task.Reject(engine, CreateJsError(engine, static_cast(ret), "ShowWindow failed.")); - } - }; - - NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return engine.CreateUndefined(); -} - -NativeValue* JsWindow::OnDestroy(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnDestroy is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = - [this](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto ret = windowToken_->Destroy(); - windowToken_ = nullptr; - if (ret == OHOS::Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - WLOGFI("JsWindow::OnDestroy success"); - } else { - task.Reject(engine, CreateJsError(engine, static_cast(ret), "JsWindow::OnDestroy failed.")); - } - }; - - NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return engine.CreateUndefined(); -} - -NativeValue* JsWindow::OnHide(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnHide is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = - [this](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto ret = windowToken_->Hide(); - if (ret == OHOS::Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - WLOGFI("JsWindow::OnHide success"); - } else { - task.Reject(engine, CreateJsError(engine, static_cast(ret), "JsWindow::OnHide failed.")); - } - }; - - NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return engine.CreateUndefined(); -} - -NativeValue* JsWindow::OnMoveTo(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnMoveTo is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - int32_t x; - if (!ConvertFromJsValue(engine, info.argv[0], x)) { - WLOGFE("Failed to convert parameter to x"); - return engine.CreateUndefined(); - } - - int32_t y; - if (!ConvertFromJsValue(engine, info.argv[1], y)) { - WLOGFE("Failed to convert parameter to y"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = - [this, x, y](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto ret = windowToken_->MoveTo(x, y); - if (ret == OHOS::Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - WLOGFI("JsWindow::OnMoveTo success"); - } else { - task.Reject(engine, CreateJsError(engine, static_cast(ret), "JsWindow::OnMoveTo failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_TWO) ? nullptr : info.argv[INDEX_TWO]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return engine.CreateUndefined(); -} - -NativeValue* JsWindow::OnResize(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnResize is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - uint32_t width; - if (!ConvertFromJsValue(engine, info.argv[0], width)) { - WLOGFE("Failed to convert parameter to width"); - return engine.CreateUndefined(); - } - - uint32_t height; - if (!ConvertFromJsValue(engine, info.argv[1], height)) { - WLOGFE("Failed to convert parameter to height"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = - [this, width, height](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto ret = windowToken_->Resize(width, height); - if (ret == OHOS::Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - WLOGFI("JsWindow::OnResize success"); - } else { - task.Reject(engine, CreateJsError(engine, static_cast(ret), "JsWindow::OnResize failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_TWO) ? nullptr : info.argv[INDEX_TWO]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return engine.CreateUndefined(); -} - -NativeValue* JsWindow::OnSetWindowType(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnSetWindowType is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - NativeNumber* nativeType = ConvertNativeValueTo(info.argv[0]); - if (nativeType == nullptr) { - WLOGFE("Failed to convert parameter to windowType"); - return engine.CreateUndefined(); - } - WindowType winType = static_cast(static_cast(*nativeType)); - AsyncTask::CompleteCallback complete = - [this, winType](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto ret = windowToken_->SetWindowType(winType); - if (ret == OHOS::Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - WLOGFI("JsWindow::OnSetWindowType success"); - } else { - task.Reject(engine, CreateJsError(engine, - static_cast(ret), "JsWindow::OnSetWindowType failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[INDEX_ONE]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return engine.CreateUndefined(); -} - -NativeValue* JsWindow::OnSetWindowMode(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnSetWindowMode is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - NativeNumber* nativeMode = ConvertNativeValueTo(info.argv[0]); - if (nativeMode == nullptr) { - WLOGFE("Failed to convert parameter to windowMode"); - return engine.CreateUndefined(); - } - WindowMode winMode = static_cast(static_cast(*nativeMode)); - AsyncTask::CompleteCallback complete = - [this, winMode](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto ret = windowToken_->SetWindowMode(winMode); - if (ret == OHOS::Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - WLOGFI("JsWindow::OnSetWindowMode success"); - } else { - task.Reject(engine, - CreateJsError(engine, static_cast(ret), "JsWindow::OnSetWindowMode failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[INDEX_ONE]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return engine.CreateUndefined(); -} - -NativeValue* JsWindow::OnGetProperties(NativeEngine& engine, NativeCallbackInfo& info) -{ - WLOGFI("JsWindow::OnGetProperties is called"); - if (windowToken_ == nullptr) { - WLOGFE("JsWindow windowToken_ is nullptr"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = - [this](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto objValue = CreateJsWindowPropertiesObject(engine, windowToken_); - WLOGFI("JsWindow::OnGetProperties objValue %{public}p", objValue); - if (objValue != nullptr) { - task.Resolve(engine, objValue); - WLOGFI("JsWindow::OnGetProperties success"); - } else { - task.Reject(engine, CreateJsError(engine, - static_cast(OHOS::Rosen::WMError::WM_ERROR_NULLPTR), "JsWindow::OnGetProperties failed.")); - } - }; - - NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; -} - -NativeValue* CreateJsWindowObject(NativeEngine& engine, sptr& window) -{ - WLOGFI("JsWindow::CreateJsWindow is called"); - NativeValue* objValue = engine.CreateObject(); - NativeObject* object = ConvertNativeValueTo(objValue); - - std::unique_ptr jsWindow = std::make_unique(window); - object->SetNativePointer(jsWindow.release(), JsWindow::Finalizer, nullptr); - - BindNativeFunction(engine, *object, "show", JsWindow::Show); - BindNativeFunction(engine, *object, "destroy", JsWindow::Destroy); - BindNativeFunction(engine, *object, "hide", JsWindow::Hide); - BindNativeFunction(engine, *object, "moveTo", JsWindow::MoveTo); - BindNativeFunction(engine, *object, "resetSize", JsWindow::Resize); - BindNativeFunction(engine, *object, "setWindowType", JsWindow::SetWindowType); - BindNativeFunction(engine, *object, "setWindowMode", JsWindow::SetWindowMode); - BindNativeFunction(engine, *object, "getProperties", JsWindow::GetProperties); - return objValue; -} -} // namespace AbilityRuntime -} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_manager.cpp b/frameworks/kits/ability/native/src/ability_runtime/window/js_window_manager.cpp deleted file mode 100644 index 24156ae1dd140f3164987927339d80ed4dd90ed4..0000000000000000000000000000000000000000 --- a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_manager.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "js_window_manager.h" -#include "js_runtime_utils.h" -#include "js_window.h" -#include "js_window_utils.h" -#include "native_engine/native_reference.h" -#include "window_manager_hilog.h" -#include "window_option.h" - -using namespace OHOS::Rosen; - -namespace OHOS { -namespace AbilityRuntime { -using namespace AbilityRuntime; -namespace { - constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0, "JsWindowManager"}; -} - -class JsWindowManager { -public: - JsWindowManager() = default; - ~JsWindowManager() = default; - - static void Finalizer(NativeEngine* engine, void* data, void* hint) - { - WLOGFI("JsWindowManager::Finalizer is called"); - std::unique_ptr(static_cast(data)); - } - - static NativeValue* CreateWindow(NativeEngine* engine, NativeCallbackInfo* info) - { - JsWindowManager* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnCreateWindow(*engine, *info) : nullptr; - } - - static NativeValue* FindWindow(NativeEngine* engine, NativeCallbackInfo* info) - { - JsWindowManager* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnFindWindow(*engine, *info) : nullptr; - } - -private: - - NativeValue* OnCreateWindow(NativeEngine& engine, NativeCallbackInfo& info) - { - WLOGFI("JsOnCreateWindow is called"); - - if (info.argc < ARGC_TWO) { - WLOGFE("OnCreateWindow MUST set windowname"); - return engine.CreateUndefined(); - } - - std::string windowName; - if (!ConvertFromJsValue(engine, info.argv[0], windowName)) { - WLOGFE("Failed to convert parameter to windowName"); - return engine.CreateUndefined(); - } - - NativeNumber* nativeType = ConvertNativeValueTo(info.argv[1]); - if (nativeType == nullptr) { - WLOGFE("Failed to convert parameter to windowType"); - return engine.CreateUndefined(); - } - WindowType winType = static_cast(static_cast(*nativeType)); - sptr windowOption = new WindowOption(); - windowOption->SetWindowType(winType); - AsyncTask::CompleteCallback complete = - [windowName, &windowOption](NativeEngine& engine, AsyncTask& task, int32_t status) { - sptr window = Window::Create(windowName, windowOption); - if (window != nullptr) { - task.Resolve(engine, CreateJsWindowObject(engine, window)); - WLOGFI("JsWindowManager::OnCreateWindow success"); - } else { - task.Reject(engine, CreateJsError(engine, - static_cast(WMError::WM_ERROR_NULLPTR), "JsWindowManager::OnCreateWindow failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_TWO) ? nullptr : info.argv[INDEX_TWO]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; - } - - NativeValue* OnFindWindow(NativeEngine& engine, NativeCallbackInfo& info) - { - std::string windowName; - if (!ConvertFromJsValue(engine, info.argv[0], windowName)) { - WLOGFE("Failed to convert parameter to windowName"); - return engine.CreateUndefined(); - } - - AsyncTask::CompleteCallback complete = - [windowName](NativeEngine& engine, AsyncTask& task, int32_t status) { - sptr window = Window::Find(windowName); - if (window != nullptr) { - task.Resolve(engine, CreateJsWindowObject(engine, window)); - WLOGFI("JsWindowManager::OnFindWindow success"); - } else { - task.Reject(engine, CreateJsError(engine, - static_cast(WMError::WM_ERROR_NULLPTR), "JsWindow::OnFindWindow failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[INDEX_ONE]; - if (lastParam == nullptr) { - WLOGFI("JsWindowManager::OnFindWindow lastParam is nullptr"); - } - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; - } -}; - -NativeValue* JsWindowManagerInit(NativeEngine* engine, NativeValue* exportObj) -{ - WLOGFI("JsWindowManagerInit is called"); - - if (engine == nullptr || exportObj == nullptr) { - WLOGFE("JsWindowManagerInit engine or exportObj is nullptr"); - return nullptr; - } - - NativeObject* object = ConvertNativeValueTo(exportObj); - if (object == nullptr) { - WLOGFE("JsWindowManagerInit object is nullptr"); - return nullptr; - } - - std::unique_ptr jsWinManager = std::make_unique(); - object->SetNativePointer(jsWinManager.release(), JsWindowManager::Finalizer, nullptr); - - BindNativeFunction(*engine, *object, "create", JsWindowManager::CreateWindow); - BindNativeFunction(*engine, *object, "find", JsWindowManager::FindWindow); - - return engine->CreateUndefined(); -} -} // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_utils.cpp b/frameworks/kits/ability/native/src/ability_runtime/window/js_window_utils.cpp deleted file mode 100644 index 1506959eb0ac879435716b2e7b048689f1b154d4..0000000000000000000000000000000000000000 --- a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_utils.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "js_window_utils.h" -#include "js_runtime_utils.h" -#include "window_manager_hilog.h" - -using namespace OHOS::Rosen; - -namespace OHOS { -namespace AbilityRuntime { -using namespace AbilityRuntime; -namespace { - constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0, "JsWindowUtils"}; -} - -static NativeValue* GetRectAndConvertToJsValue(NativeEngine& engine, const OHOS::Rosen::Rect& rect) -{ - NativeValue* objValue = engine.CreateObject(); - NativeObject* object = ConvertNativeValueTo(objValue); - if (object == nullptr) { - WLOGFE("Failed to convert rect to jsObject"); - return engine.CreateUndefined(); - } - WLOGFI("JsWindow::CreateJsWindowPropertiesObject x:%{public}d, y:%{public}d,", rect.posX_, rect.posY_); - object->SetProperty("left", CreateJsValue(engine, rect.posX_)); - object->SetProperty("top", CreateJsValue(engine, rect.posY_)); - object->SetProperty("width", CreateJsValue(engine, rect.width_)); - object->SetProperty("height", CreateJsValue(engine, rect.height_)); - return objValue; -} - -NativeValue* CreateJsWindowPropertiesObject(NativeEngine& engine, sptr& window) -{ - WLOGFI("JsWindow::CreateJsWindowPropertiesObject is called"); - NativeValue* objValue = engine.CreateObject(); - NativeObject* object = ConvertNativeValueTo(objValue); - if (object == nullptr) { - WLOGFE("Failed to convert windowProperties to jsObject"); - return nullptr; - } - - OHOS::Rosen::Rect rect = window->GetRect(); - NativeValue* rectObj = GetRectAndConvertToJsValue(engine, rect); - if (rectObj == nullptr) { - WLOGFE("GetRect failed!"); - } - object->SetProperty("windowRect", rectObj); - object->SetProperty("type", CreateJsValue(engine, window->GetType())); - return objValue; -} -} // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_runtime/window_stage_api/@ohos.window_stage.d.ts b/frameworks/kits/ability/native/src/ability_runtime/window_stage_api/@ohos.window_stage.d.ts index aa67199915a78fb829512c38cd5a8b5c7340b7c3..20c3d44392163da41edfc317e391727cef727d9b 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/window_stage_api/@ohos.window_stage.d.ts +++ b/frameworks/kits/ability/native/src/ability_runtime/window_stage_api/@ohos.window_stage.d.ts @@ -34,6 +34,42 @@ declare namespace windowStage { * @since 8 */ getMainWindow(): Promise; + /** + * Loads content + * @param path path Path of the page to which the content will be loaded + * @param storage storage The data object shared within the content instance loaded by the window + * @devices tv, phone, tablet, wearable, car + * @since 8 + */ + loadContent(path: string, storage: ContenStorage, callback: AsyncCallback): void; + /** + * Loads content + * @param path path of the page to which the content will be loaded + * @devices tv, phone, tablet, wearable, car + * @since 8 + */ + loadContent(path: string, callback: AsyncCallback): void; + /** + * Loads content + * @param path path of the page to which the content will be loaded + * @devices tv, phone, tablet, wearable, car + * @since 8 + */ + loadContent(path: string, storage?: ContenStorage): Promise; + /** + * get the windowmode of current window + * @devices tv, phone, tablet, wearable, car + * @systemapi + * @since 8 + */ + getWindowMode(callback: AsyncCallback): void; + /** + * get the windowmode of current window + * @devices tv, phone, tablet, wearable, car + * @systemapi + * @since 8 + */ + getWindowMode(): Promise; /** * window stage event callback on. * @since 8 diff --git a/frameworks/kits/ability/native/src/ability_thread.cpp b/frameworks/kits/ability/native/src/ability_thread.cpp index cee7f5e6f31afb6fe0111db5ec035a21b57c82fa..f7315491023ea6f02af03db769407ddaed5035b5 100644 --- a/frameworks/kits/ability/native/src/ability_thread.cpp +++ b/frameworks/kits/ability/native/src/ability_thread.cpp @@ -43,7 +43,7 @@ constexpr static char ACE_DATA_ABILITY_NAME[] = "AceDataAbility"; constexpr static char ACE_FORM_ABILITY_NAME[] = "AceFormAbility"; constexpr static char BASE_SERVICE_EXTENSION[] = "ServiceExtension"; constexpr static char FORM_EXTENSION[] = "FormExtension"; -constexpr int TARGET_VERSION_THRESHOLDS = 8; +constexpr static char STATIC_SUBSCRIBER_EXTENSION[] = "StaticSubscriberExtension"; /** * @brief Default constructor used to create a AbilityThread instance. @@ -83,30 +83,34 @@ std::string AbilityThread::CreateAbilityName(const std::shared_ptrtype); APP_LOGI("AbilityThread::ability attach the ability is Native %{public}d", abilityInfo->isNativeAbility); - if (abilityInfo->isNativeAbility == false) { - if (abilityInfo->type == AbilityType::PAGE) { - if (abilityRecord->GetCompatibleVersion() >= TARGET_VERSION_THRESHOLDS) { - abilityName = ABILITY_NAME; - } else { - abilityName = ACE_ABILITY_NAME; - } - } else if (abilityInfo->type == AbilityType::SERVICE) { - if (abilityInfo->formEnabled == true) { - abilityName = ACE_FORM_ABILITY_NAME; - } else { - abilityName = ACE_SERVICE_ABILITY_NAME; - } - } else if (abilityInfo->type == AbilityType::DATA) { - abilityName = ACE_DATA_ABILITY_NAME; - } else if (abilityInfo->type == AbilityType::EXTENSION) { - abilityName = BASE_SERVICE_EXTENSION; - if (abilityInfo->formEnabled == true) { - abilityName = FORM_EXTENSION; - } - APP_LOGI("CreateAbilityName extension type, abilityName:%{public}s", abilityName.c_str()); + if (abilityInfo->isNativeAbility) { + APP_LOGI("AbilityThread::CreateAbilityName end, create native ability."); + return abilityInfo->name; + } + + if (abilityInfo->type == AbilityType::PAGE) { + if (abilityInfo->isStageBasedModel) { + abilityName = ABILITY_NAME; + } else { + abilityName = ACE_ABILITY_NAME; + } + } else if (abilityInfo->type == AbilityType::SERVICE) { + if (abilityInfo->formEnabled == true) { + abilityName = ACE_FORM_ABILITY_NAME; } else { - abilityName = abilityInfo->name; + abilityName = ACE_SERVICE_ABILITY_NAME; } + } else if (abilityInfo->type == AbilityType::DATA) { + abilityName = ACE_DATA_ABILITY_NAME; + } else if (abilityInfo->type == AbilityType::EXTENSION) { + abilityName = BASE_SERVICE_EXTENSION; + if (abilityInfo->formEnabled || abilityInfo->extensionAbilityType == ExtensionAbilityType::FORM) { + abilityName = FORM_EXTENSION; + } + if (abilityInfo->extensionAbilityType == ExtensionAbilityType::STATICSUBSCRIBER) { + abilityName = STATIC_SUBSCRIBER_EXTENSION; + } + APP_LOGI("CreateAbilityName extension type, abilityName:%{public}s", abilityName.c_str()); } else { abilityName = abilityInfo->name; } @@ -427,14 +431,12 @@ void AbilityThread::HandleAbilityTransaction(const Want &want, const LifeCycleSt return; } - APP_LOGI("AbilityThread::HandleAbilityTransaction before abilityImpl_->SetCallingContext"); + APP_LOGI("AbilityThread::HandleAbilityTransaction abilityImpl_->SetCallingContext"); abilityImpl_->SetCallingContext(lifeCycleStateInfo.caller.deviceId, lifeCycleStateInfo.caller.bundleName, lifeCycleStateInfo.caller.abilityName); - APP_LOGI("AbilityThread::HandleAbilityTransaction after abilityImpl_->SetCallingContext"); - APP_LOGI("AbilityThread::HandleAbilityTransaction before abilityImpl_->HandleAbilityTransaction"); + APP_LOGI("AbilityThread::HandleAbilityTransaction abilityImpl_->HandleAbilityTransaction"); abilityImpl_->HandleAbilityTransaction(want, lifeCycleStateInfo); - APP_LOGI("AbilityThread::HandleAbilityTransaction after abilityImpl_->HandleAbilityTransaction"); APP_LOGI("AbilityThread::HandleAbilityTransaction end"); } @@ -664,7 +666,15 @@ void AbilityThread::ScheduleUpdateConfiguration(const Configuration &config) return; } - auto task = [abilitThread = this, config]() { abilitThread->HandleUpdateConfiguration(config); }; + wptr weak = this; + auto task = [weak, config]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleUpdateConfiguration failed."); + return; + } + abilityThread->HandleUpdateConfiguration(config); + }; if (abilityHandler_ == nullptr) { APP_LOGE("AbilityThread::ScheduleUpdateConfiguration abilityHandler_ is nullptr"); @@ -713,13 +723,19 @@ void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycle APP_LOGE("ScheduleAbilityTransaction::failed, token_ nullptr"); return; } - auto task = [abilityThread = this, want, lifeCycleStateInfo]() { - if (abilityThread->isExtension_) { - abilityThread->HandleExtensionTransaction(want, lifeCycleStateInfo); - } else { - abilityThread->HandleAbilityTransaction(want, lifeCycleStateInfo); - } - }; + wptr weak = this; + auto task = [weak, want, lifeCycleStateInfo]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleAbilityTransaction failed."); + return; + } + if (abilityThread->isExtension_) { + abilityThread->HandleExtensionTransaction(want, lifeCycleStateInfo); + } else { + abilityThread->HandleAbilityTransaction(want, lifeCycleStateInfo); + } + }; if (abilityHandler_ == nullptr) { APP_LOGE("AbilityThread::ScheduleAbilityTransaction abilityHandler_ == nullptr"); @@ -740,13 +756,19 @@ void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycle void AbilityThread::ScheduleConnectAbility(const Want &want) { APP_LOGI("AbilityThread::ScheduleConnectAbility begin, isExtension_:%{public}d", isExtension_); - auto task = [abilityThread = this, want]() { - if (abilityThread->isExtension_) { - abilityThread->HandleConnectExtension(want); - } else { - abilityThread->HandleConnectAbility(want); - } - }; + wptr weak = this; + auto task = [weak, want]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleConnectAbility failed."); + return; + } + if (abilityThread->isExtension_) { + abilityThread->HandleConnectExtension(want); + } else { + abilityThread->HandleConnectAbility(want); + } + }; if (abilityHandler_ == nullptr) { APP_LOGE("AbilityThread::ScheduleConnectAbility abilityHandler_ == nullptr"); @@ -767,13 +789,19 @@ void AbilityThread::ScheduleConnectAbility(const Want &want) void AbilityThread::ScheduleDisconnectAbility(const Want &want) { APP_LOGI("AbilityThread::ScheduleDisconnectAbility begin, isExtension_:%{public}d", isExtension_); - auto task = [abilityThread = this, want]() { - if (abilityThread->isExtension_) { - abilityThread->HandleDisconnectExtension(want); - } else { - abilityThread->HandleDisconnectAbility(want); - } - }; + wptr weak = this; + auto task = [weak, want]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleDisconnectAbility failed."); + return; + } + if (abilityThread->isExtension_) { + abilityThread->HandleDisconnectExtension(want); + } else { + abilityThread->HandleDisconnectAbility(want); + } + }; if (abilityHandler_ == nullptr) { APP_LOGE("AbilityThread::ScheduleDisconnectAbility abilityHandler_ == nullptr"); @@ -802,13 +830,19 @@ void AbilityThread::ScheduleDisconnectAbility(const Want &want) void AbilityThread::ScheduleCommandAbility(const Want &want, bool restart, int startId) { APP_LOGI("AbilityThread::ScheduleCommandAbility begin. startId:%{public}d", startId); - auto task = [abilityThread = this, want, restart, startId]() { - if (abilityThread->isExtension_) { - abilityThread->HandleCommandExtension(want, restart, startId); - } else { - abilityThread->HandleCommandAbility(want, restart, startId); - } - }; + wptr weak = this; + auto task = [weak, want, restart, startId]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleCommandAbility failed."); + return; + } + if (abilityThread->isExtension_) { + abilityThread->HandleCommandExtension(want, restart, startId); + } else { + abilityThread->HandleCommandAbility(want, restart, startId); + } + }; if (abilityHandler_ == nullptr) { APP_LOGE("AbilityThread::ScheduleCommandAbility abilityHandler_ == nullptr"); @@ -840,11 +874,16 @@ void AbilityThread::SendResult(int requestCode, int resultCode, const Want &want APP_LOGE("AbilityThread::SendResult abilityImpl_ == nullptr"); return; } - - auto task = [this, requestCode, resultCode, want]() { + wptr weak = this; + auto task = [weak, requestCode, resultCode, want]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr || abilityThread->abilityImpl_ == nullptr) { + APP_LOGE("abilityThread or abilityImpl is nullptr, SendResult failed."); + return; + } if (requestCode != -1) { APP_LOGI("AbilityThread::SendResult before abilityImpl_->SendResult"); - abilityImpl_->SendResult(requestCode, resultCode, want); + abilityThread->abilityImpl_->SendResult(requestCode, resultCode, want); APP_LOGI("AbilityThread::SendResult after abilityImpl_->SendResult"); } }; @@ -859,7 +898,6 @@ void AbilityThread::SendResult(int requestCode, int resultCode, const Want &want APP_LOGE("AbilityThread::SendResult PostTask error"); } APP_LOGI("AbilityThread::SendResult end"); - } /** @@ -1384,13 +1422,18 @@ bool AbilityThread::CheckObsPermission() bool AbilityThread::ScheduleRegisterObserver(const Uri &uri, const sptr &dataObserver) { APP_LOGI("%{public}s called", __func__); - if (!CheckObsPermission()) { APP_LOGE("%{public}s CheckObsPermission() return false", __func__); return false; } - auto task = [abilityThread = this, uri, dataObserver]() { + wptr weak = this; + auto task = [weak, uri, dataObserver]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleRegisterObserver failed."); + return; + } abilityThread->HandleRegisterObserver(uri, dataObserver); }; @@ -1415,13 +1458,18 @@ bool AbilityThread::ScheduleRegisterObserver(const Uri &uri, const sptr &dataObserver) { APP_LOGI("%{public}s called", __func__); - if (!CheckObsPermission()) { APP_LOGE("%{public}s CheckObsPermission() return false", __func__); return false; } - auto task = [abilityThread = this, uri, dataObserver]() { + wptr weak = this; + auto task = [weak, uri, dataObserver]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleUnregisterObserver failed."); + return; + } abilityThread->HandleUnregisterObserver(uri, dataObserver); }; @@ -1445,13 +1493,20 @@ bool AbilityThread::ScheduleUnregisterObserver(const Uri &uri, const sptrHandleNotifyChange(uri); }; + wptr weak = this; + auto task = [weak, uri]() { + auto abilityThread = weak.promote(); + if (abilityThread == nullptr) { + APP_LOGE("abilityThread is nullptr, ScheduleNotifyChange failed."); + return; + } + abilityThread->HandleNotifyChange(uri); + }; if (abilityHandler_ == nullptr) { APP_LOGE("AbilityThread::ScheduleNotifyChange abilityHandler_ == nullptr"); @@ -1491,7 +1546,43 @@ std::shared_ptr AbilityThread::BuildAbilityConte abilityContextImpl->SetStageContext(stageContext); abilityContextImpl->SetToken(token); abilityContextImpl->SetAbilityInfo(abilityInfo); + abilityContextImpl->SetConfiguration(application->GetConfiguration()); return abilityContextImpl; } + +void AbilityThread::DumpAbilityInfo(std::vector &info) +{ + APP_LOGI("%{public}s begin.", __func__); + std::string dumpInfo = " event:"; + info.push_back(dumpInfo); + + if (!abilityHandler_) { + APP_LOGI("abilityHandler_ is nullptr."); + return; + } + auto runner = abilityHandler_->GetEventRunner(); + if (!runner) { + APP_LOGI("runner_ is nullptr."); + return; + } + + dumpInfo = ""; + runner->DumpRunnerInfo(dumpInfo); + info.push_back(dumpInfo); + + APP_LOGI("localCallContainer need to get calls info."); +} + +sptr AbilityThread::CallRequest() +{ + APP_LOGI("AbilityThread::CallRequest start"); + + if (!currentAbility_) { + APP_LOGI("ability is nullptr."); + return nullptr; + } + + return currentAbility_->CallRequest(); +} } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_window.cpp b/frameworks/kits/ability/native/src/ability_window.cpp index e3a7174ffbede9dd4e0b2067838fc771887b5a4a..25c1427e12a727c6e7f18b19feb7e9dd9a06ce3e 100644 --- a/frameworks/kits/ability/native/src/ability_window.cpp +++ b/frameworks/kits/ability/native/src/ability_window.cpp @@ -50,10 +50,10 @@ void AbilityWindow::Init(std::shared_ptr& handler, std::shared_p */ bool AbilityWindow::InitWindow(Rosen::WindowType winType, std::shared_ptr &abilityContext, - sptr &listener) + sptr &listener, int32_t displayId, sptr option) { APP_LOGI("%{public}s begin.", __func__); - auto ret = windowScene_->Init(Rosen::WindowScene::DEFAULT_DISPLAY_ID, abilityContext, listener); + auto ret = windowScene_->Init(displayId, abilityContext, listener, option); if (ret != OHOS::Rosen::WMError::WM_OK) { APP_LOGE("%{public}s error. failed to init window scene!", __func__); return false; @@ -195,7 +195,7 @@ void AbilityWindow::OnPostAbilityStop() if (windowScene_) { windowScene_ = nullptr; - APP_LOGI("AbilityWindow::widow:: windowScene_ release end."); + APP_LOGI("AbilityWindow::widow windowScene_ release end."); } isWindowAttached = false; @@ -215,4 +215,4 @@ const sptr AbilityWindow::GetWindow() return windowScene_ ? windowScene_->GetMainWindow() : nullptr; } } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp b/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp index d0e424c9219e410044ba6a2475418a9395a32bc4..b2accd0050fab29708613d3b0bab98a1aea1c3b8 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp @@ -16,14 +16,13 @@ #include "ability_manager_client.h" #include "app_log_wrapper.h" -#include "distributed_client.h" +#include "distributed_errors.h" #include "element_name.h" using OHOS::AAFwk::WantParams; namespace OHOS { namespace AppExecFwk { const std::string ContinuationHandler::ORIGINAL_DEVICE_ID("deviceId"); -const int32_t ABILITY_REJECTED = 29360197; ContinuationHandler::ContinuationHandler( std::weak_ptr &continuationManager, std::weak_ptr &ability) { @@ -52,14 +51,15 @@ bool ContinuationHandler::HandleStartContinuationWithStack(const sptrOnContinue(wantParams)) { - APP_LOGI("HandleStartContinuationWithStack: OnContinue failed, BundleName = %{public}s, ClassName= %{public}s", + int32_t status = continuationManagerTmp->OnContinue(wantParams); + if (status != ERR_OK) { + APP_LOGI("OnContinue failed, BundleName = %{public}s, ClassName= %{public}s, status: %{public}d", abilityInfo_->bundleName.c_str(), - abilityInfo_->name.c_str()); - status = ABILITY_REJECTED; + abilityInfo_->name.c_str(), + status); } Want want = SetWantParams(wantParams); diff --git a/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp b/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp index dcb69ac750f475aa8b08ba1e38bc320e5cc20a52..cb26a3056faad3fca07eabb702b6b31b870e919a 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp @@ -23,12 +23,18 @@ #include "distributed_client.h" #include "operation_builder.h" #include "string_ex.h" +#include "string_wrapper.h" #include "want.h" namespace OHOS { namespace AppExecFwk { const int ContinuationManager::TIMEOUT_MS_WAIT_DMS_NOTIFY_CONTINUATION_COMPLETE = 25000; const int ContinuationManager::TIMEOUT_MS_WAIT_REMOTE_NOTIFY_BACK = 6000; +const std::string PAGE_STACK_PROPERTY_NAME = "pageStack"; +const int32_t CONTINUE_ABILITY_REJECTED = 29360197; +const int32_t CONTINUE_SAVE_DATA_FAILED = 29360198; +const int32_t CONTINUE_ON_CONTINUE_FAILED = 29360199; +const int32_t CONTINUE_GET_CONTENT_FAILED = 29360200; ContinuationManager::ContinuationManager() { @@ -82,10 +88,6 @@ std::string ContinuationManager::GetOriginalDeviceId() void ContinuationManager::ContinueAbilityWithStack(const std::string &deviceId) { APP_LOGI("%{public}s called begin", __func__); - if (CheckContinuationIllegal()) { - APP_LOGE("ContinueAbilityWithStack failed. Ability not available to continueAbility."); - return; - } HandleContinueAbilityWithStack(deviceId); APP_LOGI("%{public}s called end", __func__); @@ -120,14 +122,94 @@ bool ContinuationManager::HandleContinueAbilityWithStack(const std::string &devi return true; } -bool ContinuationManager::OnContinue(WantParams &wantParams) +int32_t ContinuationManager::OnStartAndSaveData(WantParams &wantParams) { + APP_LOGI("%{public}s called begin", __func__); std::shared_ptr ability = nullptr; ability = ability_.lock(); if (ability == nullptr) { - APP_LOGE("ContinuationManager::CheckContinuationIllegal failed. ability is nullptr"); + APP_LOGE("ability is nullptr"); + return ERR_INVALID_VALUE; + } + + if (!ability->OnStartContinuation()) { + APP_LOGE("Ability rejected."); + return CONTINUE_ABILITY_REJECTED; + } + if (!ability->OnSaveData(wantParams)) { + APP_LOGE("SaveData failed."); + return CONTINUE_SAVE_DATA_FAILED; + } + APP_LOGI("%{public}s called end", __func__); + return ERR_OK; +} + +int32_t ContinuationManager::OnContinueAndGetContent(WantParams &wantParams) +{ + APP_LOGI("%{public}s called begin", __func__); + std::shared_ptr ability = nullptr; + ability = ability_.lock(); + if (ability == nullptr) { + APP_LOGE("ability is nullptr"); + return ERR_INVALID_VALUE; + } + + bool status; + APP_LOGI("OnContinue begin"); + status = ability->OnContinue(wantParams); + APP_LOGI("OnContinue end"); + if (!status) { + APP_LOGE("OnContinue failed."); + return CONTINUE_ON_CONTINUE_FAILED; + } + + status = GetContentInfo(wantParams); + if (!status) { + APP_LOGE("GetContentInfo failed."); + return CONTINUE_GET_CONTENT_FAILED; + } + APP_LOGI("%{public}s called end", __func__); + return ERR_OK; +} + +int32_t ContinuationManager::OnContinue(WantParams &wantParams) +{ + APP_LOGI("%{public}s called begin", __func__); + auto ability = ability_.lock(); + auto abilityInfo = abilityInfo_.lock(); + if (ability == nullptr || abilityInfo == nullptr) { + APP_LOGE("ability or abilityInfo is nullptr"); + return ERR_INVALID_VALUE; + } + + bool stageBased = abilityInfo->isStageBasedModel; + APP_LOGI("ability isStageBasedModel %{public}d", stageBased); + if (!stageBased) { + return OnStartAndSaveData(wantParams); + } else { + return OnContinueAndGetContent(wantParams); + } +} + +bool ContinuationManager::GetContentInfo(WantParams &wantParams) +{ + APP_LOGI("%{public}s called begin", __func__); + std::shared_ptr ability = nullptr; + ability = ability_.lock(); + if (ability == nullptr) { + APP_LOGE("ability is nullptr"); return false; } + + std::string pageStack = ability->GetContentInfo(); + if (pageStack.empty()) { + APP_LOGE("GetContentInfo failed."); + return false; + } + APP_LOGI("ability pageStack: %{public}s", pageStack.c_str()); + wantParams.SetParam(PAGE_STACK_PROPERTY_NAME, String::Box(pageStack)); + + APP_LOGI("%{public}s called end", __func__); return true; } diff --git a/frameworks/kits/ability/native/src/data_ability_helper.cpp b/frameworks/kits/ability/native/src/data_ability_helper.cpp index 89ad38d58a3abb0a1aca6fb9fae97bb6c2c3c8bb..4d1d99882b857148c1b67a65a9eb664852e4183b 100644 --- a/frameworks/kits/ability/native/src/data_ability_helper.cpp +++ b/frameworks/kits/ability/native/src/data_ability_helper.cpp @@ -289,7 +289,7 @@ bool DataAbilityHelper::Release() APP_LOGI("DataAbilityHelper::Release before ReleaseDataAbility."); int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); if (err != ERR_OK) { - APP_LOGE("DataAbilityHelper::GetFileTypes failed to ReleaseDataAbility err = %{public}d", err); + APP_LOGE("DataAbilityHelper::Release failed to ReleaseDataAbility err = %{public}d", err); return false; } APP_LOGI("DataAbilityHelper::Release after ReleaseDataAbility."); @@ -926,9 +926,14 @@ void DataAbilityHelper::UnregisterObserver(const Uri &uri, const sptrScheduleUnregisterObserver(uri, dataObserver); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("DataAbilityHelper::UnregisterObserver failed to ReleaseDataAbility err = %{public}d", err); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::UnregisterObserver before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::UnregisterObserver after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::UnregisterObserver failed to ReleaseDataAbility err = %{public}d", err); + } + dataAbilityProxy_ = nullptr; } registerMap_.erase(dataObserver); uriMap_.erase(dataObserver); diff --git a/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp b/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5cf8c6277f5046c95ee42b2ac43c3de5b79ec91f --- /dev/null +++ b/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp @@ -0,0 +1,350 @@ +/* + * Copyright (c) 2021-2022 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 "distributed_client.h" + +#include "distributed_parcel_helper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AAFwk { +namespace { +const std::u16string DMS_PROXY_INTERFACE_TOKEN = u"ohos.distributedschedule.accessToken"; +} +sptr DistributedClient::GetDmsProxy() +{ + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + HILOG_ERROR("fail to get samgr."); + return nullptr; + } + return samgrProxy->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); +} + +int32_t DistributedClient::StartRemoteAbility(const OHOS::AAFwk::Want& want, + int32_t callerUid, int32_t requestCode) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, Parcelable, &want); + PARCEL_WRITE_HELPER(data, Int32, callerUid); + PARCEL_WRITE_HELPER(data, Int32, requestCode); + MessageParcel reply; + PARCEL_TRANSACT_SYNC_RET_INT(remote, START_REMOTE_ABILITY, data, reply); +} + +int32_t DistributedClient::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid) +{ + HILOG_INFO("called"); + if (connect == nullptr) { + HILOG_ERROR("ConnectRemoteAbility connect is null"); + return ERR_NULL_OBJECT; + } + + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("ConnectRemoteAbility remote is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, Parcelable, &want); + PARCEL_WRITE_HELPER(data, RemoteObject, connect); + PARCEL_WRITE_HELPER(data, Int32, callerUid); + PARCEL_WRITE_HELPER(data, Int32, callerPid); + MessageParcel reply; + PARCEL_TRANSACT_SYNC_RET_INT(remote, CONNECT_REMOTE_ABILITY, data, reply); +} + +int32_t DistributedClient::DisconnectRemoteAbility(const sptr& connect) +{ + HILOG_INFO("called"); + if (connect == nullptr) { + HILOG_ERROR("DisconnectRemoteAbility connect is null"); + return ERR_NULL_OBJECT; + } + + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("DisconnectRemoteAbility remote is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, RemoteObject, connect); + MessageParcel reply; + PARCEL_TRANSACT_SYNC_RET_INT(remote, DISCONNECT_REMOTE_ABILITY, data, reply); +} + +int32_t DistributedClient::ContinueMission(const std::string& srcDeviceId, const std::string& dstDeviceId, + int32_t missionId, const sptr& callback, const OHOS::AAFwk::WantParams& wantParams) +{ + HILOG_INFO("called"); + if (callback == nullptr) { + HILOG_ERROR("ContinueMission callback null"); + return ERR_NULL_OBJECT; + } + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("ContinueMission remote service null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String, srcDeviceId); + PARCEL_WRITE_HELPER(data, String, dstDeviceId); + PARCEL_WRITE_HELPER(data, Int32, missionId); + PARCEL_WRITE_HELPER(data, RemoteObject, callback); + PARCEL_WRITE_HELPER(data, Parcelable, &wantParams); + MessageParcel reply; + PARCEL_TRANSACT_SYNC_RET_INT(remote, CONTINUE_MISSION, data, reply); +} + +int32_t DistributedClient::StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId, int32_t callerUid, + int32_t status) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("StartContinuation remote service null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, Parcelable, &want); + PARCEL_WRITE_HELPER(data, Int32, missionId); + PARCEL_WRITE_HELPER(data, Int32, callerUid); + PARCEL_WRITE_HELPER(data, Int32, status); + MessageParcel reply; + PARCEL_TRANSACT_SYNC_RET_INT(remote, START_CONTINUATION, data, reply); +} + +ErrCode DistributedClient::NotifyCompleteContinuation( + const std::u16string &devId, int32_t sessionId, bool isSuccess) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("NotifyCompleteContinuation remote service null"); + return ERR_NULL_OBJECT; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteString16(devId)) { + HILOG_ERROR("write deviceId error"); + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteInt32(sessionId)) { + HILOG_ERROR("write sessionId error"); + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteBool(isSuccess)) { + HILOG_ERROR("write result error"); + return ERR_FLATTEN_OBJECT; + } + MessageParcel reply; + MessageOption option; + int32_t result = remote->SendRequest(NOTIFY_COMPLETE_CONTINUATION, data, reply, option); + if (result != ERR_NONE) { + HILOG_ERROR("SendRequest failed, result = %{public}d", result); + return result; + } + return ERR_OK; +} + +int32_t DistributedClient::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("remote system abiity is null"); + return ERR_NULL_OBJECT; + } + + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String16, Str8ToStr16(devId)); + PARCEL_WRITE_HELPER(data, Bool, fixConflict); + PARCEL_WRITE_HELPER(data, Int64, tag); + PARCEL_TRANSACT_SYNC_RET_INT(remote, START_SYNC_MISSIONS, data, reply); +} + +int32_t DistributedClient::StopSyncRemoteMissions(const std::string& devId) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("remote system abiity is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String16, Str8ToStr16(devId)); + PARCEL_TRANSACT_SYNC_RET_INT(remote, STOP_SYNC_MISSIONS, data, reply); +} + +int32_t DistributedClient::RegisterMissionListener(const std::u16string& devId, + const sptr& obj) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("remote system ablity is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String16, devId); + PARCEL_WRITE_HELPER(data, RemoteObject, obj); + PARCEL_TRANSACT_SYNC_RET_INT(remote, REGISTER_MISSION_LISTENER, data, reply); +} + +int32_t DistributedClient::UnRegisterMissionListener(const std::u16string& devId, + const sptr& obj) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("remote system abiity is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String16, devId); + PARCEL_WRITE_HELPER(data, RemoteObject, obj); + PARCEL_TRANSACT_SYNC_RET_INT(remote, UNREGISTER_MISSION_LISTENER, data, reply); +} + +int32_t DistributedClient::GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos) +{ + HILOG_INFO("called"); + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("remote system abiity is null"); + return ERR_NULL_OBJECT; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String16, Str8ToStr16(deviceId)); + PARCEL_WRITE_HELPER(data, Int32, numMissions); + int32_t ret = remote->SendRequest(GET_MISSION_INFOS, data, reply, option); + if (ret != ERR_NONE) { + HILOG_WARN("sendRequest fail, error: %{public}d", ret); + return ret; + } + return ReadMissionInfosFromParcel(reply, missionInfos) ? ERR_NONE : ERR_FLATTEN_OBJECT; +} + +int32_t DistributedClient::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, + std::unique_ptr& missionSnapshot) +{ + if (deviceId.empty()) { + HILOG_ERROR("deviceId is null"); + return ERR_NULL_OBJECT; + } + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("remote is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String, deviceId); + PARCEL_WRITE_HELPER(data, Int32, missionId); + MessageParcel reply; + MessageOption option; + int32_t error = remote->SendRequest(GET_REMOTE_MISSION_SNAPSHOT_INFO, data, reply, option); + if (error != ERR_NONE) { + HILOG_ERROR("transact failed, error: %{public}d", error); + return error; + } + std::unique_ptr missionSnapshotPtr(reply.ReadParcelable()); + missionSnapshot = std::move(missionSnapshotPtr); + return ERR_NONE; +} + +bool DistributedClient::ReadMissionInfosFromParcel(Parcel& parcel, + std::vector& missionInfos) +{ + int32_t hasMissions = parcel.ReadInt32(); + if (hasMissions == 1) { + int32_t len = parcel.ReadInt32(); + HILOG_DEBUG("readLength is:%{public}d", len); + if (len < 0) { + return false; + } + size_t size = static_cast(len); + if ((size > parcel.GetReadableBytes()) || (missionInfos.max_size() < size)) { + HILOG_ERROR("Failed to read MissionInfo vector, size = %{public}zu", size); + return false; + } + missionInfos.clear(); + for (size_t i = 0; i < size; i++) { + AAFwk::MissionInfo *ptr = parcel.ReadParcelable(); + if (ptr == nullptr) { + HILOG_WARN("read MissionInfo failed"); + return false; + } + missionInfos.emplace_back(*ptr); + delete ptr; + } + } + HILOG_INFO("info size is:%{public}zu", missionInfos.size()); + return true; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/extension_module_loader.cpp b/frameworks/kits/ability/native/src/extension_module_loader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e70d7b6f990ee6ef0a245b210fe22b4353c5077 --- /dev/null +++ b/frameworks/kits/ability/native/src/extension_module_loader.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "extension_module_loader.h" + +#include + +#include "hilog_wrapper.h" + +namespace OHOS::AbilityRuntime { +namespace { +constexpr char EXTENSION_MODULE_ENTRY[] = "OHOS_EXTENSION_GetExtensionModule"; + +using DynamicEntry = void* (*)(); + +class DummyExtensionModuleLoader final : public ExtensionModuleLoader, public Singleton { + DECLARE_SINGLETON(DummyExtensionModuleLoader); + +public: + Extension* Create(const std::unique_ptr& runtime) const override + { + return nullptr; + } +}; + +DummyExtensionModuleLoader::DummyExtensionModuleLoader() = default; +DummyExtensionModuleLoader::~DummyExtensionModuleLoader() = default; + +ExtensionModuleLoader& GetExtensionModuleLoader(const char* sharedLibrary) +{ + if (sharedLibrary == nullptr) { + HILOG_ERROR("Name of shared extension library MUST NOT be null pointer"); + return DummyExtensionModuleLoader::GetInstance(); + } + + void* handle = dlopen(sharedLibrary, RTLD_LAZY); + if (handle == nullptr) { + HILOG_ERROR("Failed to open extension library %{public}s, reason: %{public}sn", sharedLibrary, dlerror()); + return DummyExtensionModuleLoader::GetInstance(); + } + + auto entry = reinterpret_cast(dlsym(handle, EXTENSION_MODULE_ENTRY)); + if (entry == nullptr) { + dlclose(handle); + HILOG_ERROR("Failed to get extension symbol %{public}s in %{public}s", EXTENSION_MODULE_ENTRY, sharedLibrary); + return DummyExtensionModuleLoader::GetInstance(); + } + + auto loader = reinterpret_cast(entry()); + if (loader == nullptr) { + dlclose(handle); + HILOG_ERROR("Failed to get extension module loader in %{public}s", sharedLibrary); + return DummyExtensionModuleLoader::GetInstance(); + } + + return *loader; +} +} // namespace + +ExtensionModuleLoader& ExtensionModuleLoader::GetLoader(const char* sharedLibrary) +{ + static ExtensionModuleLoader& instance = GetExtensionModuleLoader(sharedLibrary); + return instance; +} + +Extension *ExtensionModuleLoader::Create(const std::unique_ptr& runtime) const +{ + return nullptr; +} +} diff --git a/frameworks/kits/ability/native/src/form_extension.cpp b/frameworks/kits/ability/native/src/form_extension.cpp index 46d8cf38a7bff59fb337bf2a0640cb5093a37ca8..4761f4e06d8e891547212d37f0a7f3765304213c 100644 --- a/frameworks/kits/ability/native/src/form_extension.cpp +++ b/frameworks/kits/ability/native/src/form_extension.cpp @@ -16,7 +16,6 @@ #include "form_extension.h" #include "ability_loader.h" -#include "extension_base.cpp" #include "form_extension_context.h" #include "form_runtime/js_form_extension.h" #include "hilog_wrapper.h" diff --git a/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp b/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp index d8cb3dfbf8f3d2c62bd12689ba9139fa63dffd89..9e8cc7c6a1d5b152d55fc25b50c4e0790fb01805 100644 --- a/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp +++ b/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp @@ -88,6 +88,21 @@ void JsFormExtension::Init(const std::shared_ptr &record, context->Bind(jsRuntime_, shellContextRef.release()); HILOG_INFO("JsFormExtension::SetProperty."); obj->SetProperty("context", contextObj); + + auto nativeObj = ConvertNativeValueTo(contextObj); + if (nativeObj == nullptr) { + HILOG_ERROR("Failed to get form extension native object"); + return; + } + + HILOG_INFO("Set form extension context pointer: %{public}p", context.get()); + + nativeObj->SetNativePointer(new std::weak_ptr(context), + [](NativeEngine*, void* data, void*) { + HILOG_INFO("Finalizer for weak_ptr form extension context is called"); + delete static_cast*>(data); + }, nullptr); + HILOG_INFO("JsFormExtension::Init end."); } diff --git a/frameworks/kits/ability/native/src/js_service_extension.cpp b/frameworks/kits/ability/native/src/js_service_extension.cpp old mode 100644 new mode 100755 index 4437c35f9c474e0d0ad839094454a24db94d7a07..ae325209df9c54b4ec81aa1d5f579a2ae1fb25ca --- a/frameworks/kits/ability/native/src/js_service_extension.cpp +++ b/frameworks/kits/ability/native/src/js_service_extension.cpp @@ -42,22 +42,20 @@ JsServiceExtension::JsServiceExtension(JsRuntime& jsRuntime) : jsRuntime_(jsRunt JsServiceExtension::~JsServiceExtension() = default; void JsServiceExtension::Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, + const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) { ServiceExtension::Init(record, application, handler, token); - std::string srcPath(Extension::abilityInfo_->package); - srcPath.append("/assets/js/"); - if (!Extension::abilityInfo_->srcPath.empty()) { - srcPath.append(Extension::abilityInfo_->srcPath); + std::string srcPath = ""; + GetSrcPath(srcPath); + if (srcPath.empty()) { + HILOG_ERROR("Failed to get srcPath"); + return; } - srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); std::string moduleName(Extension::abilityInfo_->moduleName); moduleName.append("::").append(abilityInfo_->name); - HILOG_INFO("JsServiceExtension::Init moduleName:%{public}s,srcPath:%{public}s.", - moduleName.c_str(), srcPath.c_str()); + HILOG_INFO("JsServiceExtension::Init module:%{public}s,srcPath:%{public}s.", moduleName.c_str(), srcPath.c_str()); HandleScope handleScope(jsRuntime_); auto& engine = jsRuntime_.GetNativeEngine(); @@ -86,6 +84,21 @@ void JsServiceExtension::Init(const std::shared_ptr &record, context->Bind(jsRuntime_, shellContextRef.release()); HILOG_INFO("JsServiceExtension::SetProperty."); obj->SetProperty("context", contextObj); + + auto nativeObj = ConvertNativeValueTo(contextObj); + if (nativeObj == nullptr) { + HILOG_ERROR("Failed to get service extension native object"); + return; + } + + HILOG_INFO("Set service extension context pointer: %{public}p", context.get()); + + nativeObj->SetNativePointer(new std::weak_ptr(context), + [](NativeEngine*, void* data, void*) { + HILOG_INFO("Finalizer for weak_ptr service extension context is called"); + delete static_cast*>(data); + }, nullptr); + HILOG_INFO("JsServiceExtension::Init end."); } @@ -107,6 +120,10 @@ void JsServiceExtension::OnStop() ServiceExtension::OnStop(); HILOG_INFO("JsServiceExtension OnStop begin."); CallObjectMethod("onDestroy"); + bool ret = ConnectionManager::GetInstance().DisconnectCaller(GetContext()->GetToken()); + if (ret) { + HILOG_INFO("The service extension connection is not disconnected."); + } HILOG_INFO("%{public}s end.", __func__); } @@ -227,5 +244,26 @@ NativeValue* JsServiceExtension::CallObjectMethod(const char* name, NativeValue* HILOG_INFO("JsServiceExtension::CallFunction(%{public}s), success", name); return nativeEngine.CallFunction(value, method, argv, argc); } + +void JsServiceExtension::GetSrcPath(std::string &srcPath) +{ + if (!Extension::abilityInfo_->isModuleJson) { + /* temporary compatibility api8 + config.json */ + srcPath.append(Extension::abilityInfo_->package); + srcPath.append("/assets/js/"); + if (!Extension::abilityInfo_->srcPath.empty()) { + srcPath.append(Extension::abilityInfo_->srcPath); + } + srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); + return; + } + + if (!Extension::abilityInfo_->srcEntrance.empty()) { + srcPath.append(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + srcPath.erase(srcPath.rfind('.')); + srcPath.append(".abc"); + } +} +} } -} \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/js_service_extension_context.cpp b/frameworks/kits/ability/native/src/js_service_extension_context.cpp old mode 100644 new mode 100755 index 091db3037e318bce4b463b75488badfde0076e14..fdc124980ea35aca416b45de4adcf063f32b12e0 --- a/frameworks/kits/ability/native/src/js_service_extension_context.cpp +++ b/frameworks/kits/ability/native/src/js_service_extension_context.cpp @@ -19,10 +19,12 @@ #include "hilog_wrapper.h" #include "js_extension_context.h" +#include "js_data_struct_converter.h" #include "js_runtime.h" #include "js_runtime_utils.h" #include "napi/native_api.h" #include "napi_common_want.h" +#include "napi_common_util.h" #include "napi_remote_object.h" #include "napi_common_start_options.h" #include "start_options.h" @@ -32,11 +34,14 @@ namespace AbilityRuntime { namespace { constexpr int32_t INDEX_ZERO = 0; constexpr int32_t INDEX_ONE = 1; +constexpr int32_t INDEX_TWO = 2; constexpr int32_t ERROR_CODE_ONE = 1; constexpr int32_t ERROR_CODE_TWO = 2; constexpr size_t ARGC_ZERO = 0; constexpr size_t ARGC_ONE = 1; constexpr size_t ARGC_TWO = 2; +constexpr size_t ARGC_THREE = 3; +constexpr size_t ARGC_FOUR = 4; class JsServiceExtensionContext final { public: @@ -55,6 +60,18 @@ public: return (me != nullptr) ? me->OnStartAbility(*engine, *info) : nullptr; } + static NativeValue* StartAbilityWithAccount(NativeEngine* engine, NativeCallbackInfo* info) + { + JsServiceExtensionContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnStartAbilityWithAccount(*engine, *info) : nullptr; + } + + static NativeValue* ConnectAbilityWithAccount(NativeEngine* engine, NativeCallbackInfo* info) + { + JsServiceExtensionContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnConnectAbilityWithAccount(*engine, *info) : nullptr; + } + static NativeValue* TerminateAbility(NativeEngine* engine, NativeCallbackInfo* info) { JsServiceExtensionContext* me = CheckParamsAndGetThis(engine, info); @@ -78,8 +95,8 @@ private: NativeValue* OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnStartAbility is called"); - // only support one or two params - if (info.argc != ARGC_ONE && info.argc != ARGC_TWO) { + // only support one or two or three params + if (info.argc != ARGC_ONE && info.argc != ARGC_TWO && info.argc != ARGC_THREE) { HILOG_ERROR("Not enough params"); return engine.CreateUndefined(); } @@ -112,8 +129,14 @@ private: return; } - (unwrapArgc == 1) ? context->StartAbility(want) : context->StartAbility(want, startOptions); - task.Resolve(engine, engine.CreateUndefined()); + ErrCode errcode = ERR_OK; + (unwrapArgc == 1) ? errcode = context->StartAbility(want) : + errcode = context->StartAbility(want, startOptions); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed.")); + } }; NativeValue* lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc]; @@ -123,6 +146,70 @@ private: return result; } + NativeValue* OnStartAbilityWithAccount(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("OnStartAbilityWithAccount is called"); + // only support two or three or four params + if (info.argc != ARGC_TWO && info.argc != ARGC_THREE && info.argc != ARGC_FOUR) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + decltype(info.argc) unwrapArgc = 0; + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ZERO]), want); + HILOG_INFO("%{public}s bundlename:%{public}s abilityname:%{public}s", + __func__, + want.GetBundle().c_str(), + want.GetElement().GetAbilityName().c_str()); + unwrapArgc++; + + int32_t accountId = 0; + if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ONE]), accountId)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return engine.CreateUndefined(); + } + HILOG_INFO("%{public}d accountId:", accountId); + unwrapArgc++; + + AAFwk::StartOptions startOptions; + if (info.argc > ARGC_TWO && info.argv[INDEX_TWO]->TypeOf() == NATIVE_OBJECT) { + HILOG_INFO("OnStartAbilityWithAccount start options is used."); + AppExecFwk::UnwrapStartOptions(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_TWO]), startOptions); + unwrapArgc++; + } + + AsyncTask::CompleteCallback complete = + [weak = context_, want, accountId, startOptions, unwrapArgc]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("startAbility begin"); + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released")); + return; + } + + ErrCode errcode = ERR_OK; + (unwrapArgc == ARGC_TWO) ? errcode = context->StartAbilityWithAccount(want, accountId) : + errcode = context->StartAbilityWithAccount(want, accountId, startOptions); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed.")); + } + }; + + NativeValue* lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + NativeValue* OnTerminateAbility(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnTerminateAbility is called"); @@ -142,8 +229,12 @@ private: return; } - context->TerminateAbility(); - task.Resolve(engine, engine.CreateUndefined()); + auto errcode = context->TerminateAbility(); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Terminate Ability failed.")); + } }; NativeValue* lastParam = (info.argc == ARGC_ZERO) ? nullptr : info.argv[INDEX_ZERO]; @@ -171,8 +262,7 @@ private: want.GetBundle().c_str(), want.GetElement().GetAbilityName().c_str()); // unwarp connection - std::shared_ptr connection = std::make_shared(); - connection->SetNativeEngine(&engine); + sptr connection = new JSServiceExtensionConnection(engine); connection->SetJsConnectionObject(info.argv[1]); int64_t connectId = serialNumber_; ConnecttionKey key; @@ -184,7 +274,7 @@ private: } else { serialNumber_ = 0; } - HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, connection.get()); + HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr()); AsyncTask::CompleteCallback complete = [weak = context_, want, connection, connectId](NativeEngine& engine, AsyncTask& task, int32_t status) { HILOG_INFO("OnConnectAbility begin"); @@ -206,6 +296,67 @@ private: return engine.CreateNumber(connectId); } + NativeValue* OnConnectAbilityWithAccount(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("OnConnectAbilityWithAccount is called"); + // only support three params + if (info.argc != ARGC_THREE) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + // unwrap want + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ZERO]), want); + HILOG_INFO("%{public}s bundlename:%{public}s abilityname:%{public}s", + __func__, + want.GetBundle().c_str(), + want.GetElement().GetAbilityName().c_str()); + + int32_t accountId = 0; + if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ONE]), accountId)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return engine.CreateUndefined(); + } + + // unwarp connection + sptr connection = new JSServiceExtensionConnection(engine); + connection->SetJsConnectionObject(info.argv[1]); + int64_t connectId = serialNumber_; + ConnecttionKey key; + key.id = serialNumber_; + key.want = want; + connects_.emplace(key, connection); + if (serialNumber_ < INT64_MAX) { + serialNumber_++; + } else { + serialNumber_ = 0; + } + HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, connection.GetRefPtr()); + AsyncTask::CompleteCallback complete = + [weak = context_, want, accountId, connection, connectId]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("OnConnectAbilityWithAccount begin"); + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released")); + return; + } + HILOG_INFO("context->ConnectAbilityWithAccount connection:%{public}d", (int32_t)connectId); + if (!context->ConnectAbilityWithAccount(want, accountId, connection)) { + connection->CallJsFailed(ERROR_CODE_ONE); + } + task.Resolve(engine, engine.CreateUndefined()); + }; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result)); + return engine.CreateNumber(connectId); + } + NativeValue* OnDisconnectAbility(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnDisconnectAbility is called"); @@ -219,20 +370,20 @@ private: AAFwk::Want want; // unwrap connectId int64_t connectId = -1; - std::shared_ptr connection = nullptr; + sptr connection = nullptr; napi_get_value_int64(reinterpret_cast(&engine), reinterpret_cast(info.argv[INDEX_ZERO]), &connectId); HILOG_INFO("OnDisconnectAbility connection:%{public}d", (int32_t)connectId); auto item = std::find_if(connects_.begin(), connects_.end(), [&connectId]( - const std::map>::value_type &obj) { + const std::map>::value_type &obj) { return connectId == obj.first.id; }); if (item != connects_.end()) { // match id want = item->first.want; connection = item->second; - HILOG_INFO("%{public}s find conn ability:%{public}p exist", __func__, item->second.get()); + HILOG_INFO("%{public}s find conn ability:%{public}p exist", __func__, item->second.GetRefPtr()); } else { HILOG_INFO("%{public}s not find conn exist.", __func__); } @@ -253,8 +404,9 @@ private: return; } HILOG_INFO("context->DisconnectAbility"); - context->DisconnectAbility(want, connection); - task.Resolve(engine, engine.CreateUndefined()); + auto errcode = context->DisconnectAbility(want, connection); + errcode == 0 ? task.Resolve(engine, engine.CreateUndefined()) : + task.Reject(engine, CreateJsError(engine, errcode, "Disconnect Ability failed.")); }; NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[INDEX_ONE]; @@ -266,6 +418,60 @@ private: }; } // namespace +NativeValue* CreateJsMetadata(NativeEngine& engine, const AppExecFwk::Metadata &Info) +{ + HILOG_INFO("CreateJsMetadata"); + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + object->SetProperty("name", CreateJsValue(engine, Info.name)); + object->SetProperty("value", CreateJsValue(engine, Info.value)); + object->SetProperty("resource", CreateJsValue(engine, Info.resource)); + return objValue; +} + +NativeValue* CreateJsMetadataArray(NativeEngine& engine, const std::vector &info) +{ + HILOG_INFO("CreateJsMetadataArray"); + NativeValue* arrayValue = engine.CreateArray(info.size()); + NativeArray* array = ConvertNativeValueTo(arrayValue); + uint32_t index = 0; + for (const auto& item : info) { + array->SetElement(index++, CreateJsMetadata(engine, item)); + } + return arrayValue; +} + +NativeValue* CreateJsExtensionAbilityInfo(NativeEngine& engine, const AppExecFwk::ExtensionAbilityInfo& info) +{ + HILOG_INFO("CreateJsExtensionAbilityInfo"); + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + object->SetProperty("bundleName", CreateJsValue(engine, info.bundleName)); + object->SetProperty("moduleName", CreateJsValue(engine, info.moduleName)); + object->SetProperty("name", CreateJsValue(engine, info.name)); + object->SetProperty("labelId", CreateJsValue(engine, info.labelId)); + object->SetProperty("descriptionId", CreateJsValue(engine, info.descriptionId)); + object->SetProperty("iconId", CreateJsValue(engine, info.iconId)); + object->SetProperty("isVisible", CreateJsValue(engine, info.visible)); + object->SetProperty("extensionAbilityType", CreateJsValue(engine, info.type)); + NativeValue *permissionArrayValue = engine.CreateArray(info.permissions.size()); + NativeArray *permissionArray = ConvertNativeValueTo(permissionArrayValue); + if (permissionArray != nullptr) { + int index = 0; + for (auto permission : info.permissions) { + permissionArray->SetElement(index++, CreateJsValue(engine, permission)); + } + } + object->SetProperty("permissions", permissionArrayValue); + object->SetProperty("applicationInfo", CreateJsApplicationInfo(engine, info.applicationInfo)); + object->SetProperty("metadata", CreateJsMetadataArray(engine, info.metadata)); + object->SetProperty("enabled", CreateJsValue(engine, info.enabled)); + object->SetProperty("readPermission", CreateJsValue(engine, info.readPermission)); + object->SetProperty("writePermission", CreateJsValue(engine, info.writePermission)); + return objValue; +} + NativeValue* CreateJsServiceExtensionContext(NativeEngine& engine, std::shared_ptr context) { HILOG_INFO("CreateJsServiceExtensionContext begin"); @@ -282,10 +488,36 @@ NativeValue* CreateJsServiceExtensionContext(NativeEngine& engine, std::shared_p BindNativeFunction(engine, *object, "terminateSelf", JsServiceExtensionContext::TerminateAbility); BindNativeFunction(engine, *object, "connectAbility", JsServiceExtensionContext::ConnectAbility); BindNativeFunction(engine, *object, "disconnectAbility", JsServiceExtensionContext::DisconnectAbility); + BindNativeFunction(engine, *object, "startAbilityWithAccount", JsServiceExtensionContext::StartAbilityWithAccount); + BindNativeFunction( + engine, *object, "connectAbilityWithAccount", JsServiceExtensionContext::ConnectAbilityWithAccount); + + if (context) { + HILOG_INFO("Set ExtensionAbilityInfo Property"); + auto abilityInfo = context->GetAbilityInfo(); + auto hapModuleInfo = context->GetHapModuleInfo(); + if (abilityInfo && hapModuleInfo) { + auto isExist = [&abilityInfo](const AppExecFwk::ExtensionAbilityInfo &info) { + HILOG_INFO("%{public}s, %{public}s", info.bundleName.c_str(), info.name.c_str()); + return info.bundleName == abilityInfo->bundleName && info.name == abilityInfo->name; + }; + auto infoIter = std::find_if( + hapModuleInfo->extensionInfos.begin(), hapModuleInfo->extensionInfos.end(), isExist); + if (infoIter == hapModuleInfo->extensionInfos.end()) { + HILOG_INFO("Get target fail."); + return objValue; + } + object->SetProperty("extensionAbilityInfo", CreateJsExtensionAbilityInfo(engine, *infoIter)); + } + } return objValue; } +JSServiceExtensionConnection::JSServiceExtensionConnection(NativeEngine& engine) : engine_(engine) {} + +JSServiceExtensionConnection::~JSServiceExtensionConnection() = default; + void JSServiceExtensionConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { @@ -311,13 +543,13 @@ void JSServiceExtensionConnection::HandleOnAbilityConnectDone(const AppExecFwk:: { HILOG_INFO("HandleOnAbilityConnectDone begin, resultCode:%{public}d", resultCode); // wrap ElementName - napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast(engine_), element); + napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast(&engine_), element); NativeValue* nativeElementName = reinterpret_cast(napiElementName); // wrap RemoteObject HILOG_INFO("OnAbilityConnectDone begin NAPI_ohos_rpc_CreateJsRemoteObject"); napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( - reinterpret_cast(engine_), remoteObject); + reinterpret_cast(&engine_), remoteObject); NativeValue* nativeRemoteObject = reinterpret_cast(napiRemoteObject); NativeValue* argv[] = {nativeElementName, nativeRemoteObject}; if (jsConnectionObject_ == nullptr) { @@ -336,12 +568,7 @@ void JSServiceExtensionConnection::HandleOnAbilityConnectDone(const AppExecFwk:: return; } HILOG_INFO("JSServiceExtensionConnection::CallFunction onConnect, success"); - // two params - if (engine_ == nullptr) { - HILOG_ERROR("engine_ nullptr"); - return; - } - engine_->CallFunction(value, methodOnConnect, argv, ARGC_TWO); + engine_.CallFunction(value, methodOnConnect, argv, ARGC_TWO); HILOG_INFO("OnAbilityConnectDone end"); } @@ -368,7 +595,7 @@ void JSServiceExtensionConnection::HandleOnAbilityDisconnectDone(const AppExecFw int resultCode) { HILOG_INFO("HandleOnAbilityDisconnectDone begin, resultCode:%{public}d", resultCode); - napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast(engine_), element); + napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(reinterpret_cast(&engine_), element); NativeValue* nativeElementName = reinterpret_cast(napiElementName); NativeValue* argv[] = {nativeElementName}; if (jsConnectionObject_ == nullptr) { @@ -395,7 +622,7 @@ void JSServiceExtensionConnection::HandleOnAbilityDisconnectDone(const AppExecFw auto item = std::find_if(connects_.begin(), connects_.end(), [bundleName, abilityName]( - const std::map>::value_type &obj) { + const std::map>::value_type &obj) { return (bundleName == obj.first.want.GetBundle()) && (abilityName == obj.first.want.GetElement().GetAbilityName()); }); @@ -404,23 +631,13 @@ void JSServiceExtensionConnection::HandleOnAbilityDisconnectDone(const AppExecFw connects_.erase(item); HILOG_INFO("OnAbilityDisconnectDone erase connects_.size:%{public}zu", connects_.size()); } - // one params - if (engine_ == nullptr) { - HILOG_ERROR("engine_ nullptr"); - return; - } HILOG_INFO("OnAbilityDisconnectDone CallFunction success"); - engine_->CallFunction(value, method, argv, ARGC_ONE); -} - -void JSServiceExtensionConnection::SetNativeEngine(NativeEngine* engine) -{ - engine_ = engine; + engine_.CallFunction(value, method, argv, ARGC_ONE); } void JSServiceExtensionConnection::SetJsConnectionObject(NativeValue* jsConnectionObject) { - jsConnectionObject_ = std::unique_ptr(engine_->CreateReference(jsConnectionObject, 1)); + jsConnectionObject_ = std::unique_ptr(engine_.CreateReference(jsConnectionObject, 1)); } void JSServiceExtensionConnection::CallJsFailed(int32_t errorCode) @@ -442,14 +659,10 @@ void JSServiceExtensionConnection::CallJsFailed(int32_t errorCode) HILOG_ERROR("Failed to get onFailed from object"); return; } - if (engine_ == nullptr) { - HILOG_ERROR("engine_ nullptr"); - return; - } - NativeValue* argv[] = {engine_->CreateNumber(errorCode)}; + NativeValue* argv[] = {engine_.CreateNumber(errorCode)}; HILOG_INFO("CallJsFailed CallFunction success"); - engine_->CallFunction(value, method, argv, ARGC_ONE); + engine_.CallFunction(value, method, argv, ARGC_ONE); HILOG_INFO("CallJsFailed end"); } } // namespace AbilityRuntime -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/js_static_subscriber_extension.cpp b/frameworks/kits/ability/native/src/js_static_subscriber_extension.cpp new file mode 100644 index 0000000000000000000000000000000000000000..deb65e1278c547cf571bc95fe9d40afab85deaeb --- /dev/null +++ b/frameworks/kits/ability/native/src/js_static_subscriber_extension.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2022 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 "js_static_subscriber_extension.h" + +#include "ability_info.h" +#include "hilog_wrapper.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "js_static_subscriber_extension_context.h" +#include "napi_common_want.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "napi_remote_object.h" +#include "static_subscriber_stub_imp.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr size_t ARGC_ONE = 1; +} + +using namespace OHOS::AppExecFwk; +JsStaticSubscriberExtension* JsStaticSubscriberExtension::Create(const std::unique_ptr& runtime) +{ + return new JsStaticSubscriberExtension(static_cast(*runtime)); +} + +JsStaticSubscriberExtension::JsStaticSubscriberExtension(JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} +JsStaticSubscriberExtension::~JsStaticSubscriberExtension() = default; + +void JsStaticSubscriberExtension::Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) +{ + StaticSubscriberExtension::Init(record, application, handler, token); + if (Extension::abilityInfo_->srcEntrance.empty()) { + HILOG_ERROR("%{public}s abilityInfo srcEntrance is empty", __func__); + return; + } + std::string srcPath(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + srcPath.erase(srcPath.rfind('.')); + srcPath.append(".abc"); + + std::string moduleName(Extension::abilityInfo_->moduleName); + moduleName.append("::").append(abilityInfo_->name); + HILOG_INFO("JsStaticSubscriberExtension::Init moduleName:%{public}s,srcPath:%{public}s.", + moduleName.c_str(), srcPath.c_str()); + HandleScope handleScope(jsRuntime_); + auto& engine = jsRuntime_.GetNativeEngine(); + + jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath); + if (jsObj_ == nullptr) { + HILOG_ERROR("Failed to get jsObj_"); + return; + } + HILOG_INFO("JsStaticSubscriberExtension::Init ConvertNativeValueTo."); + NativeObject* obj = ConvertNativeValueTo(jsObj_->Get()); + if (obj == nullptr) { + HILOG_ERROR("Failed to get JsStaticSubscriberExtension object"); + return; + } + + auto context = GetContext(); + if (context == nullptr) { + HILOG_ERROR("Failed to get context"); + return; + } + HILOG_INFO("JsStaticSubscriberExtension::Init CreateJsStaticSubscriberExtensionContext."); + NativeValue* contextObj = CreateJsStaticSubscriberExtensionContext(engine, context); + auto shellContextRef = jsRuntime_.LoadSystemModule("application.StaticSubscriberExtensionContext", + &contextObj, ARGC_ONE); + contextObj = shellContextRef->Get(); + HILOG_INFO("JsStaticSubscriberExtension::Init Bind."); + context->Bind(jsRuntime_, shellContextRef.release()); + HILOG_INFO("JsStaticSubscriberExtension::SetProperty."); + obj->SetProperty("context", contextObj); + HILOG_INFO("JsStaticSubscriberExtension::Init end."); +} + +void JsStaticSubscriberExtension::OnStart(const AAFwk::Want& want) +{ + Extension::OnStart(want); + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); +} + +void JsStaticSubscriberExtension::OnStop() +{ + Extension::OnStop(); + HILOG_INFO("%{public}s end.", __func__); +} + +sptr JsStaticSubscriberExtension::OnConnect(const AAFwk::Want& want) +{ + Extension::OnConnect(want); + HILOG_INFO("%{public}s begin.", __func__); + sptr remoteObject = new (std::nothrow) StaticSubscriberStubImp( + std::static_pointer_cast(shared_from_this())); + HILOG_INFO("%{public}s end. ", __func__); + return remoteObject->AsObject(); +} + +void JsStaticSubscriberExtension::OnDisconnect(const AAFwk::Want& want) +{ + Extension::OnDisconnect(want); + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); +} + +void JsStaticSubscriberExtension::OnCommonEventTriggered(EventFwk::CommonEventData* data) +{ + StaticSubscriberExtension::OnCommonEventTriggered(data); + HILOG_INFO("%{public}s begin.", __func__); + if (data == nullptr) { + HILOG_ERROR("%{public}s common event data == nullptr", __func__); + return; + } + + HandleScope handleScope(jsRuntime_); + NativeEngine& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* jCommonEventData = nativeEngine.CreateObject(); + NativeObject* commonEventData = ConvertNativeValueTo(jCommonEventData); + Want want = data->GetWant(); + commonEventData->SetProperty("event", nativeEngine.CreateString(want.GetAction().c_str(), want.GetAction().size())); + commonEventData->SetProperty("bundleName", nativeEngine.CreateString(want.GetBundle().c_str(), + want.GetBundle().size())); + commonEventData->SetProperty("code", nativeEngine.CreateNumber(data->GetCode())); + commonEventData->SetProperty("data", nativeEngine.CreateString(data->GetData().c_str(), data->GetData().size())); + napi_value napiParams = AppExecFwk::WrapWantParams(reinterpret_cast(&nativeEngine), want.GetParams()); + NativeValue* nativeParams = reinterpret_cast(napiParams); + commonEventData->SetProperty("parameters", nativeParams); + + NativeValue* argv[] = {jCommonEventData}; + if (!jsObj_) { + HILOG_WARN("Not found StaticSubscriberExtension.js"); + return; + } + + NativeValue* value = jsObj_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get StaticSubscriberExtension object"); + return; + } + + NativeValue* method = obj->GetProperty("onCommonEventTriggered"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onCommonEventTriggered from StaticSubscriberExtension object"); + return; + } + nativeEngine.CallFunction(value, method, argv, ARGC_ONE); + HILOG_INFO("%{public}s end.", __func__); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_runtime/window/js_window.h b/frameworks/kits/ability/native/src/js_static_subscriber_extension_context.cpp similarity index 30% rename from frameworks/kits/ability/native/src/ability_runtime/window/js_window.h rename to frameworks/kits/ability/native/src/js_static_subscriber_extension_context.cpp index 29b5065160a4eb56fba33550b33ac27545298ee1..e350c9ee335f11ae3cf3e955ab0ac320daf533d3 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/window/js_window.h +++ b/frameworks/kits/ability/native/src/js_static_subscriber_extension_context.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 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,43 +13,47 @@ * limitations under the License. */ -#ifndef OHOS_JS_WINDOW_H -#define OHOS_JS_WINDOW_H +#include "js_static_subscriber_extension_context.h" + +#include "hilog_wrapper.h" + +#include "js_extension_context.h" +#include "js_runtime.h" #include "js_runtime_utils.h" -#include "js_window_utils.h" -#include "native_engine/native_engine.h" -#include "native_engine/native_value.h" -#include "window.h" +#include "napi/native_api.h" +#include "napi_common_want.h" + namespace OHOS { namespace AbilityRuntime { -NativeValue* CreateJsWindowObject(NativeEngine& engine, sptr& window); - -class JsWindow final { +namespace { +class JsStaticSubscriberExtensionContext final { public: - explicit JsWindow(const sptr& window) : windowToken_(window) {} - ~JsWindow() = default; - static void Finalizer(NativeEngine* engine, void* data, void* hint); - static NativeValue* Show(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* Destroy(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* Hide(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* MoveTo(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* Resize(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* SetWindowType(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* SetWindowMode(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* GetProperties(NativeEngine* engine, NativeCallbackInfo* info); + explicit JsStaticSubscriberExtensionContext(const std::shared_ptr& context) + : context_(context) {} + ~JsStaticSubscriberExtensionContext() = default; + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsStaticSubscriberExtensionContext::Finalizer is called"); + std::unique_ptr( + static_cast(data)); + } private: - NativeValue* OnShow(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnDestroy(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnHide(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnMoveTo(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnResize(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnSetWindowType(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnSetWindowMode(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnGetProperties(NativeEngine& engine, NativeCallbackInfo& info); - - sptr windowToken_ = nullptr; + std::weak_ptr context_; }; +} // namespace + +NativeValue* CreateJsStaticSubscriberExtensionContext(NativeEngine& engine, + std::shared_ptr context) +{ + HILOG_INFO("CreateJsStaticSubscriberExtensionContext begin"); + NativeValue *objValue = CreateJsExtensionContext(engine, context); + NativeObject *object = ConvertNativeValueTo(objValue); + + std::unique_ptr jsContext = + std::make_unique(context); + object->SetNativePointer(jsContext.release(), JsStaticSubscriberExtensionContext::Finalizer, nullptr); + return objValue; +} } // namespace AbilityRuntime } // namespace OHOS -#endif \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/new_ability_impl.cpp b/frameworks/kits/ability/native/src/new_ability_impl.cpp index ccb869ee2c4b462f53fb6bbf72349b2d13a6f77e..55638e5532d00a31bfabd569e41334c3487e1467 100644 --- a/frameworks/kits/ability/native/src/new_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/new_ability_impl.cpp @@ -80,6 +80,9 @@ bool NewAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycle break; } case AAFwk::ABILITY_STATE_FOREGROUND_NEW: { + if (targetState.isNewWant) { + NewWant(want); + } Foreground(want); ret = false; break; @@ -99,4 +102,4 @@ bool NewAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycle return ret; } } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/page_ability_impl.cpp b/frameworks/kits/ability/native/src/page_ability_impl.cpp index 5828ad80424faa338554d284c1774dedebb3d241..34db10aae3b5d87250210e49ca8d738de7e9fdb5 100644 --- a/frameworks/kits/ability/native/src/page_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/page_ability_impl.cpp @@ -147,7 +147,8 @@ bool PageAbilityImpl::AbilityTransactionNew(const Want &want, const AAFwk::LifeC break; } case AAFwk::ABILITY_STATE_FOREGROUND_NEW: { - if (lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND_NEW) { + if (lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND_NEW || + lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND) { Foreground(want); } if (targetState.isNewWant) { diff --git a/frameworks/kits/ability/native/src/service_extension.cpp b/frameworks/kits/ability/native/src/service_extension.cpp old mode 100644 new mode 100755 index f360b81668a29d88e99831aa1ef00314839530e6..d3da9018ee706555a7a5f68ab702bef30f64fe12 --- a/frameworks/kits/ability/native/src/service_extension.cpp +++ b/frameworks/kits/ability/native/src/service_extension.cpp @@ -17,7 +17,6 @@ #include "ability_loader.h" #include "connection_manager.h" -#include "extension_base.cpp" #include "hilog_wrapper.h" #include "js_service_extension.h" #include "runtime.h" @@ -58,21 +57,11 @@ std::shared_ptr ServiceExtension::CreateAndInitContext( { std::shared_ptr context = ExtensionBase::CreateAndInitContext(record, application, handler, token); - if (record == nullptr) { - HILOG_ERROR("ServiceExtension::CreateAndInitContext record is nullptr"); + if (context == nullptr) { + HILOG_ERROR("ServiceExtension::CreateAndInitContext context is nullptr"); return context; } - context->SetAbilityInfo(record->GetAbilityInfo()); return context; } - -void ServiceExtension::OnStop() -{ - Extension::OnStop(); - bool ret = ConnectionManager::GetInstance().DisconnectCaller(GetContext()->GetToken()); - if (ret) { - HILOG_INFO("The service connection is not disconnected."); - } -} } } \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/service_extension_module_loader.cpp b/frameworks/kits/ability/native/src/service_extension_module_loader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7992f786a888965268167f1c4413821042a1a82 --- /dev/null +++ b/frameworks/kits/ability/native/src/service_extension_module_loader.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "service_extension_module_loader.h" +#include "service_extension.h" + +namespace OHOS::AbilityRuntime { +ServiceExtensionModuleLoader::ServiceExtensionModuleLoader() = default; +ServiceExtensionModuleLoader::~ServiceExtensionModuleLoader() = default; + +Extension *ServiceExtensionModuleLoader::Create(const std::unique_ptr& runtime) const +{ + return ServiceExtension::Create(runtime); +} + +extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule() +{ + return &ServiceExtensionModuleLoader::GetInstance(); +} +} // namespace OHOS::AbilityRuntime \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/static_subscriber_extension.cpp b/frameworks/kits/ability/native/src/static_subscriber_extension.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f563ceb96e74a25709eb200a5e7e88d82c59a5c --- /dev/null +++ b/frameworks/kits/ability/native/src/static_subscriber_extension.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "static_subscriber_extension.h" + +#include "ability_loader.h" +#include "hilog_wrapper.h" +#include "js_static_subscriber_extension.h" +#include "runtime.h" +#include "static_subscriber_extension_context.h" + +namespace OHOS { +namespace AbilityRuntime { +using namespace OHOS::AppExecFwk; +StaticSubscriberExtension* StaticSubscriberExtension::Create(const std::unique_ptr& runtime) +{ + if (!runtime) { + return new StaticSubscriberExtension(); + } + HILOG_INFO("StaticSubscriberExtension::Create runtime"); + switch (runtime->GetLanguage()) { + case Runtime::Language::JS: + return JsStaticSubscriberExtension::Create(runtime); + + default: + return new StaticSubscriberExtension(); + } +} + +void StaticSubscriberExtension::Init(const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) +{ + HILOG_INFO("StaticSubscriberExtension begin init"); + ExtensionBase::Init(record, application, handler, token); +} + +std::shared_ptr StaticSubscriberExtension::CreateAndInitContext( + const std::shared_ptr& record, + const std::shared_ptr& application, + std::shared_ptr& handler, + const sptr& token) +{ + std::shared_ptr context = + ExtensionBase::CreateAndInitContext(record, application, handler, token); + if (record == nullptr) { + HILOG_ERROR("StaticSubscriberExtension::CreateAndInitContext record is nullptr"); + return context; + } + return context; +} + +void StaticSubscriberExtension::OnCommonEventTriggered(EventFwk::CommonEventData* data) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/static_subscriber_proxy.cpp b/frameworks/kits/ability/native/src/static_subscriber_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d25387d32e93a14f1366da9fb78cd225602f513 --- /dev/null +++ b/frameworks/kits/ability/native/src/static_subscriber_proxy.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 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 "static_subscriber_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +ErrCode StaticSubscriberProxy::OnCommonEventTriggered(CommonEventData* inData) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + + data.WriteParcelable(inData); + + int32_t st = Remote()->SendRequest(COMMAND_ON_COMMON_EVENT_TRIGGERED, data, reply, option); + if (st != ERR_NONE) { + return st; + } + + ErrCode ec = reply.ReadInt32(); + if (FAILED(ec)) { + return ec; + } + + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/static_subscriber_stub.cpp b/frameworks/kits/ability/native/src/static_subscriber_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16c617ed2f20ab29dee2d465810f1217ddcc46e1 --- /dev/null +++ b/frameworks/kits/ability/native/src/static_subscriber_stub.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 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 "static_subscriber_stub.h" + +namespace OHOS { +namespace AppExecFwk { +int StaticSubscriberStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + switch (code) { + case COMMAND_ON_COMMON_EVENT_TRIGGERED: { + CommonEventData* inData = data.ReadParcelable(); + ErrCode ec = OnCommonEventTriggered(inData); + reply.WriteInt32(ec); + return ERR_NONE; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + + return ERR_TRANSACTION_FAILED; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/static_subscriber_stub_imp.cpp b/frameworks/kits/ability/native/src/static_subscriber_stub_imp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98c2bd561c710df5abf89dd9b616067e1d2661c1 --- /dev/null +++ b/frameworks/kits/ability/native/src/static_subscriber_stub_imp.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 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 "static_subscriber_stub_imp.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +ErrCode StaticSubscriberStubImp::OnCommonEventTriggered(CommonEventData* data) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension != nullptr) { + extension->OnCommonEventTriggered(data); + HILOG_INFO("%{public}s end successfully.", __func__); + return 0; + } + HILOG_INFO("%{public}s end failed.", __func__); + return -1; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/test/BUILD.gn b/frameworks/kits/ability/native/test/BUILD.gn index 117b7ac3c912c09595fd972966fa2b1f1a92b5b1..308908f88963a3bdf5e0cced6d715db3581f0010 100644 --- a/frameworks/kits/ability/native/test/BUILD.gn +++ b/frameworks/kits/ability/native/test/BUILD.gn @@ -13,7 +13,7 @@ import("//build/test.gni") -module_output_path = "aafwk_standard/ability_test" +module_output_path = "ability_runtime/ability_test" INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits" @@ -22,19 +22,19 @@ config("module_private_config") { visibility = [ ":*" ] include_dirs = [ "//base/global/i18n_standard/frameworks/intl/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", "//EOSP/communication/libsoftbus/../../../foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", - "//foundation/appexecfwk/standard/kits/appkit/native/test/mock/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/test/mock/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//utils/system/safwk/native/include", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", @@ -43,10 +43,10 @@ config("module_private_config") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", "//foundation/aafwk/standard/services/common/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/dispatcher", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/task", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/threading", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include/task", + "//foundation/aafwk/standard/common/task_dispatcher/include/dispatcher", + "//foundation/aafwk/standard/common/task_dispatcher/include/task", + "//foundation/aafwk/standard/common/task_dispatcher/include/threading", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include/task", ] cflags = [] if (target_cpu == "arm") { @@ -61,16 +61,16 @@ config("module_private_config") { config("module_ability_context_config") { visibility = [ ":*" ] include_dirs = [ - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "//EOSP/communication/libsoftbus/../../../foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", - "//foundation/appexecfwk/standard/kits/appkit/native/test/mock/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/test/mock/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//third_party/googletest/googlemock/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", "//foundation/aafwk/standard/interfaces/innerkits/base/include", @@ -91,9 +91,11 @@ config("module_ability_context_config") { ohos_unittest("ability_test") { module_out_path = module_output_path sources = [ - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ability_record_mgr.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", "unittest/ability_test.cpp", ] @@ -103,16 +105,15 @@ ohos_unittest("ability_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", @@ -122,7 +123,7 @@ ohos_unittest("ability_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -146,13 +147,13 @@ ohos_unittest("ability_lifecycle_test") { "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", "//utils/native/base:utils", @@ -178,13 +179,13 @@ ohos_unittest("ability_lifecycle_executor_test") { "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", "//utils/native/base:utils", @@ -208,14 +209,14 @@ ohos_unittest("ability_context_for_task_dispacher_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -244,11 +245,11 @@ ohos_unittest("ability_context_interface_test") { "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -282,12 +283,12 @@ ohos_unittest("ability_context_test") { deps = [ "${INNERKITS_PATH}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -315,13 +316,13 @@ ohos_unittest("page_ability_impl_test") { "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-common", "//third_party/googletest:gtest_main", @@ -348,13 +349,13 @@ ohos_unittest("service_ability_impl_test") { "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", "//utils/native/base:utils", @@ -380,13 +381,13 @@ ohos_unittest("scene_created_test") { "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", "//utils/native/base:utils", @@ -412,9 +413,9 @@ ohos_unittest("data_ability_helper_test") { "${INNERKITS_PATH}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -442,12 +443,12 @@ ohos_unittest("data_ability_operation_test") { "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", @@ -468,9 +469,9 @@ ohos_unittest("data_ability_operation_test") { ohos_unittest("ability_impl_active_test") { module_out_path = module_output_path sources = [ - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", "unittest/ability_impl_active_test.cpp", ] @@ -479,15 +480,15 @@ ohos_unittest("ability_impl_active_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", @@ -495,7 +496,7 @@ ohos_unittest("ability_impl_active_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -505,9 +506,9 @@ ohos_unittest("ability_impl_active_test") { ohos_unittest("ability_impl_test") { module_out_path = module_output_path sources = [ - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", "unittest/ability_impl_test.cpp", ] @@ -517,17 +518,17 @@ ohos_unittest("ability_impl_test") { "${INNERKITS_PATH}/want:want", "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-common", @@ -536,7 +537,7 @@ ohos_unittest("ability_impl_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -550,12 +551,13 @@ ohos_unittest("ability_thread_test") { module_out_path = module_output_path sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_data_ability_impl.cpp", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_deal.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h", "mock/include/mock_ability_manager_client.cpp", "mock/include/sys_mgr_client_mock.cpp", @@ -567,17 +569,16 @@ ohos_unittest("ability_thread_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", @@ -586,7 +587,7 @@ ohos_unittest("ability_thread_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -615,14 +616,15 @@ ohos_unittest("form_provider_client_test") { "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", "//third_party/googletest:gtest_main", @@ -630,6 +632,7 @@ ohos_unittest("form_provider_client_test") { ] external_deps = [ + "form_runtime:form_manager", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -640,12 +643,13 @@ ohos_unittest("data_ability_impl_test") { module_out_path = module_output_path sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_deal.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h", "unittest/data_ability_impl_test.cpp", ] @@ -656,16 +660,15 @@ ohos_unittest("data_ability_impl_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", @@ -674,7 +677,7 @@ ohos_unittest("data_ability_impl_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -688,12 +691,13 @@ ohos_unittest("data_ability_impl_file_secondpart_test") { module_out_path = module_output_path sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_deal.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h", "unittest/data_ability_impl_file_secondpart_test.cpp", ] @@ -704,16 +708,15 @@ ohos_unittest("data_ability_impl_file_secondpart_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", @@ -722,7 +725,7 @@ ohos_unittest("data_ability_impl_file_secondpart_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -736,12 +739,13 @@ ohos_unittest("data_ability_impl_file_test") { module_out_path = module_output_path sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_deal.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h", "unittest/data_ability_impl_file_test.cpp", ] @@ -752,16 +756,15 @@ ohos_unittest("data_ability_impl_file_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", @@ -770,7 +773,7 @@ ohos_unittest("data_ability_impl_file_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -784,12 +787,13 @@ ohos_unittest("ability_thread_dataability_test") { module_out_path = module_output_path sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_data_ability_impl.cpp", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_deal.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h", "mock/include/mock_ability_manager_client.cpp", "mock/include/sys_mgr_client_mock.cpp", @@ -801,17 +805,16 @@ ohos_unittest("ability_thread_dataability_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", @@ -820,7 +823,7 @@ ohos_unittest("ability_thread_dataability_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -858,11 +861,11 @@ ohos_unittest("data_uri_utils_test") { ] deps = [ + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", "//utils/native/base:utils", @@ -912,11 +915,11 @@ ohos_unittest("ability_permission_test") { "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -960,12 +963,12 @@ ohos_unittest("ability_thread_for_ability_on_configuration_update") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -1000,10 +1003,12 @@ ohos_unittest("data_ability_result_test") { ohos_unittest("form_host_client_test") { module_out_path = module_output_path sources = [ + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ability_record_mgr.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_start_setting.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", "mock/include/mock_bundle_manager_form.cpp", "unittest/form_host_client_test.cpp", ] @@ -1013,16 +1018,16 @@ ohos_unittest("form_host_client_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/graphic/standard:libwmclient", "//third_party/googletest:gmock_main", @@ -1031,8 +1036,9 @@ ohos_unittest("form_host_client_test") { ] external_deps = [ - "aafwk_standard:runtime", - "appexecfwk_standard:fmskit_native", + "ability_runtime:runtime", + "form_runtime:fmskit_native", + "form_runtime:form_manager", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", @@ -1042,9 +1048,10 @@ ohos_unittest("form_host_client_test") { ohos_unittest("continuation_test") { module_out_path = module_output_path sources = [ - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/application_context.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", "unittest/continuation_test.cpp", ] @@ -1053,16 +1060,15 @@ ohos_unittest("continuation_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//foundation/appexecfwk/standard/kits:app_context", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", @@ -1070,7 +1076,7 @@ ohos_unittest("continuation_test") { ] external_deps = [ - "aafwk_standard:runtime", + "ability_runtime:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimodalinput_base:libmmi-client", diff --git a/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h b/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h index cea500ac69bb2dedbb04eb31d7f2fa83bac59fef..9404f4d2f6379b87dc337270965931a9b53cab5a 100644 --- a/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h +++ b/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h @@ -27,6 +27,7 @@ #include "ohos/aafwk/content/want.h" #include "permission_def.h" #include "module_usage_record.h" +#include "distributed_bundle_info.h" using OHOS::AAFwk::Want; @@ -228,6 +229,9 @@ public: virtual bool RemoveClonedBundle(const std::string &bundleName, const int32_t uid) = 0; virtual bool BundleClone(const std::string &bundleName) = 0; virtual bool CheckBundleNameInAllowList(const std::string &bundleName) = 0; + virtual bool GetDistributedBundleInfo( + const std::string &networkId, int32_t userId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) = 0; enum class Message { GET_APPLICATION_INFO, diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.cpp b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.cpp index d3fd61a890a3216b00f9c2a3a33f2ccbe40b93f9..f5ca8e02ca2af3aeb69033de18492d8f3f27bafa 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.cpp @@ -74,7 +74,7 @@ void AbilityManagerClient::AddWindowInfo(const sptr &token, int32 return; } -ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode) +ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode, int32_t userId) { return -1; } @@ -96,7 +96,7 @@ ErrCode AbilityManagerClient::TerminateAbilityResult(const sptr & } ErrCode AbilityManagerClient::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { return -1; } diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h index b26d91d8ad95c44934dc998c2386aa299b11a9d1..3c1fda6d1d2cf024ffd8e193479025671469f4a6 100755 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h @@ -127,6 +127,11 @@ public: }; virtual void NotifyContinuationResult(const int32_t result) {}; virtual void ContinueAbility(const std::string& deviceId) {}; + virtual void DumpAbilityInfo(std::vector &info) {}; + virtual sptr CallRequest() + { + return sptr(nullptr); + }; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_clientex.cpp b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_clientex.cpp index 943662e9e0ac81e1b6ea7f75f06e8b154c9ff13a..23233df9b286212d03a2ae623f2b0ee33dea4fea 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_clientex.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_clientex.cpp @@ -105,7 +105,7 @@ void AbilityManagerClient::AddWindowInfo(const sptr &token, int32 abms->AddWindowInfo(token, windowToken); } -ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode) +ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode, int32_t userId) { if (remoteObject_ == nullptr) { return ABILITY_SERVICE_NOT_CONNECTED; @@ -137,7 +137,7 @@ ErrCode AbilityManagerClient::TerminateAbility(const sptr &caller } ErrCode AbilityManagerClient::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { if (remoteObject_ == nullptr) { remoteObject_ = diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.cpp b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.cpp index bca339167087dcf8ba223e448c5ee83071e223da..afac3de2feb90e046efe6ee7b2dca1100bb4d7c0 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.cpp @@ -33,7 +33,7 @@ MockAbilityManagerService::MockAbilityManagerService() : abilityScheduler_(nullp MockAbilityManagerService::~MockAbilityManagerService() {} -int MockAbilityManagerService::StartAbility(const Want &want, int requestCode) +int MockAbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode) { AbilityLifeCycleState state = AbilityLifeCycleState::ABILITY_STATE_INITIAL; switch (requestCode) { @@ -89,7 +89,7 @@ int MockAbilityManagerService::TerminateAbility( } int MockAbilityManagerService::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { GTEST_LOG_(INFO) << "MockAbilityManagerService::ConnectAbility"; return ERR_OK; @@ -112,6 +112,10 @@ int MockAbilityManagerService::AttachAbilityThread( void MockAbilityManagerService::DumpState(const std::string &args, std::vector &info) {} +void MockAbilityManagerService::DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) +{} + int MockAbilityManagerService::AbilityTransitionDone( const sptr &token, int state, const PacMap &saveData) { @@ -143,7 +147,7 @@ int MockAbilityManagerService::TerminateAbilityResult(const sptr return ERR_OK; } -int MockAbilityManagerService::StopServiceAbility(const Want &want) +int MockAbilityManagerService::StopServiceAbility(const Want &want, int32_t userId) { GTEST_LOG_(INFO) << "MockAbilityManagerService::StopServiceAbility"; return ERR_OK; @@ -184,7 +188,8 @@ bool MockAbilityManagerService::IsFirstInMission(const sptr &toke return true; } -int MockAbilityManagerService::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) +int MockAbilityManagerService::CompelVerifyPermission( + const std::string &permission, int pid, int uid, std::string &message) { return 0; } @@ -197,6 +202,5 @@ int MockAbilityManagerService::PowerOn() { return 0; } - } // namespace AAFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h old mode 100755 new mode 100644 index 572bf7c4d0f2b6ed27da3ce50fdd8fb1b02bab40..85518ef2b421aa6702e375fcef5d600917239e7d --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h @@ -34,11 +34,23 @@ class MockAbilityManagerService : public AbilityManagerStub { public: MockAbilityManagerService(); ~MockAbilityManagerService(); - int StartAbility(const Want &want, int requestCode = -1) override; - int StartAbility(const Want &want, const sptr &callerToken, int requestCode = -1) override + int StartAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) override; + int StartAbility(const Want &want, const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) override { return 0; } + + int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override + { + return 0; + } + int TerminateAbility( const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; int MinimizeAbility(const sptr &token) override @@ -46,7 +58,11 @@ public: return 0; } int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) override; + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) override; + int DisconnectAbility(const sptr &connect) override; void AddWindowInfo(const sptr &token, int32_t windowToken) override; @@ -60,8 +76,11 @@ public: void DumpState(const std::string &args, std::vector &info) override; + void DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) override; + int TerminateAbilityResult(const sptr &token, int startId) override; - int StopServiceAbility(const Want &want) override; + int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) override; int PowerOff() override; int PowerOn() override; @@ -104,8 +123,8 @@ public: MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); - MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode)); + MOCK_METHOD5(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int32_t userId, int requestCode)); MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); MOCK_METHOD2(MoveMissionToSplitScreenStack, int(const MissionOption &primary, const MissionOption &secondary)); MOCK_METHOD2( @@ -133,10 +152,16 @@ public: MOCK_METHOD3(GetMissionInfo, int(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo)); MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); - + MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr &, const sptr &)); + int RemoveMission(int id) override; int RemoveStack(int id) override; @@ -219,6 +244,62 @@ public: { return 0; } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + + virtual int ReleaseAbility( + const sptr &connect, const AppExecFwk::ElementName &element) override + { + return 0; + } + + virtual bool SendANRProcessID(int pid) override + { + return true; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } enum RequestCode { E_STATE_INITIAL = 0, diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h index 5ebbf94d590ad7f4d320bc634d8b26b95154e59c..a638facadc4d357173aa3f0ea53da3967a595c11 100755 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h @@ -60,6 +60,12 @@ public: MOCK_METHOD1(ExecuteBatch, std::vector>(const std::vector> &operation)); MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); + + virtual sptr CallRequest() + { + return sptr(nullptr); + }; }; } // namespace AppExecFwk diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h index 96c88016bae01b31fde8dabdbf10b031ebf5a352..8ab2ec5c246b517bcab686cdde0d5621e5ce1a0e 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h @@ -98,7 +98,8 @@ public: const int32_t number, std::vector &moduleUsageRecords) override; virtual sptr GetBundleInstaller() override; virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) override; + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) + override; }; class BundleMgrStub : public IRemoteStub { @@ -174,7 +175,8 @@ public: const int32_t number, std::vector &moduleUsageRecords) override; virtual sptr GetBundleInstaller() override; virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) override; + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) + override; virtual bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) override { return true; @@ -205,6 +207,12 @@ public: { return true; } + virtual bool GetDistributedBundleInfo( + const std::string &networkId, int32_t userId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) override + { + return true; + } }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp index 78551e8bc7863eaaa114caefb96562b2f8c7bc68..9b6ccd0ef951cddd879cee9721437efcb17e17cc 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp @@ -53,8 +53,8 @@ bool BundleMgrProxy::GetFormsInfoByApp(const std::string &bundleName, std::vecto return true; } bool BundleMgrProxy::GetFormsInfoByModule( - const std::string &bundleName, - const std::string &moduleName, + const std::string &bundleName, + const std::string &moduleName, std::vector &formInfo) { return true; @@ -124,7 +124,7 @@ bool BundleMgrService::GetAllFormsInfo(std::vector &formInfo) form.name = PARAM_FORM_NAME; form.updateEnabled = true; form.updateDuration = 1; - form.scheduledUpateTime = "06:06"; + form.scheduledUpdateTime = "06:06"; form.jsComponentName = FORM_JS_COMPOMENT_NAME; form.formVisibleNotify = true; form.supportDimensions = {1, 2}; @@ -141,7 +141,7 @@ bool BundleMgrService::GetFormsInfoByApp(const std::string &bundleName, std::vec form.name = PARAM_FORM_NAME; form.updateEnabled = true; form.updateDuration = 1; - form.scheduledUpateTime = "06:06"; + form.scheduledUpdateTime = "06:06"; form.jsComponentName = FORM_JS_COMPOMENT_NAME; form.formVisibleNotify = true; form.supportDimensions = {1, 2}; @@ -150,8 +150,8 @@ bool BundleMgrService::GetFormsInfoByApp(const std::string &bundleName, std::vec return true; } bool BundleMgrService::GetFormsInfoByModule( - const std::string &bundleName, - const std::string &moduleName, + const std::string &bundleName, + const std::string &moduleName, std::vector &formInfo) { FormInfo form; @@ -161,7 +161,7 @@ bool BundleMgrService::GetFormsInfoByModule( form.name = PARAM_FORM_NAME; form.updateEnabled = true; form.updateDuration = 1; - form.scheduledUpateTime = "06:06"; + form.scheduledUpdateTime = "06:06"; form.jsComponentName = FORM_JS_COMPOMENT_NAME; form.formVisibleNotify = true; form.supportDimensions = {1, 2}; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h index a00e7c19e76c4b23e52e2fe7d0c68aa9768fd6b2..40b7dab2c9ec2a6a27fb48de841669cca6fb2868 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h @@ -184,7 +184,7 @@ public: }; /** - * @brief Obtains information about the shortcuts of the application. + * @brief Obtains information about the shortcuts of the application. * @param bundleName Indicates the name of the bundle to shortcut. * @param form Indicates the callback a list to shortcutinfo. * @return Returns true if shortcutinfo get success @@ -396,7 +396,7 @@ public: }; /** - * @brief Obtains information about the shortcuts of the application. + * @brief Obtains information about the shortcuts of the application. * @param bundleName Indicates the name of the bundle to shortcut. * @param form Indicates the callback a list to shortcutinfo. * @return Returns true if shortcutinfo get success diff --git a/frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h b/frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h index 748b2c4208ea35331d0e94fecfb0b304b8f905f2..af854af336df2ba63612b948bba1085929d8b10c 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h @@ -130,8 +130,8 @@ public: * @return Returns ERR_OK on success, others on failure. */ int NotifyWhetherVisibleForms( - const std::vector &formIds, - const sptr &callerToken, + const std::vector &formIds, + const sptr &callerToken, const int32_t formVisibleType) { if (formIds.size() == 1) { @@ -139,7 +139,7 @@ public: } return 1; } - + /** * @brief temp form to normal form. * @param formId The Id of the form. @@ -196,7 +196,7 @@ public: return ERR_OK; } else { return ERR_INVALID_VALUE; - } + } } /** @@ -207,8 +207,8 @@ public: * @return Returns ERR_OK on success, others on failure. */ int LifecycleUpdate( - const std::vector &formIds, - const sptr &callerToken, + const std::vector &formIds, + const sptr &callerToken, const int32_t updateType) { if (formIds.size() == 0) { diff --git a/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.h b/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.h index 4c1b5198dfe316ccc50f845b26bc857539573fbd..d21007196b3db157367ad970aec9c19a9ed54265 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.h @@ -48,7 +48,7 @@ public: private: static std::mutex mutex; static sptr instance; - + DISALLOW_COPY_AND_MOVE(MockFormSupplyCallback); }; } // namespace AppExecFwk diff --git a/frameworks/kits/ability/native/test/unittest/ability_context_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_context_test.cpp index d05f973acea85b0ef1b60f2a2a40e312e38eb24b..c705e2aa06c220649113ca9b4ce9c0fe8e972458 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_context_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_context_test.cpp @@ -54,7 +54,7 @@ void AbilityContextTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase start"; OHOS::sptr bundleObject = new (std::nothrow) BundleMgrService(); - OHOS::sptr abilityObject = new (std::nothrow) OHOS::AAFwk::MockAbilityManagerService(); + OHOS::sptr abilityObject = new (std::nothrow) AAFwk::MockAbilityManagerService(); GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase bundleObject->" << bundleObject.GetRefPtr(); GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase abilityObject->" << abilityObject.GetRefPtr(); diff --git a/frameworks/kits/ability/native/test/unittest/ability_lifecycle_executor_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_lifecycle_executor_test.cpp index 029a332446c067468007513182c3fce4cd0bb8c2..69fe2d829b7393472c713a52fc364f34eca5cc12 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_lifecycle_executor_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_lifecycle_executor_test.cpp @@ -55,7 +55,7 @@ void AbilityLifecycleExecutorTest::TearDown(void) /** * @tc.number: AaFwk_AbilityLifecycleExecutor_GetState_0100 * @tc.name: GetState - * @tc.desc: Verify that the return value of getstate is UNINITIALIZED. + * @tc.desc: Verify that the return value of getstate is UNINITIALIZED. */ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_GetState_0100, Function | MediumTest | Level1) { @@ -71,8 +71,8 @@ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_GetState_0 /** * @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0100 * @tc.name: DispatchLifecycleState - * @tc.desc: Test whether attachbasecontext is called normally, - * and verify whether the return value of getdatabasedir is ACTIVE. + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getdatabasedir is ACTIVE. */ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0100, Function | MediumTest | Level1) { @@ -90,8 +90,8 @@ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLi /** * @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0200 * @tc.name: DispatchLifecycleState - * @tc.desc: Test whether attachbasecontext is called normally, - * and verify whether the return value of getdatabasedir is BACKGROUND. + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getdatabasedir is BACKGROUND. */ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0200, Function | MediumTest | Level1) { @@ -109,8 +109,8 @@ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLi /** * @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0300 * @tc.name: DispatchLifecycleState - * @tc.desc: Test whether attachbasecontext is called normally, - * and verify whether the return value of getdatabasedir is INACTIVE. + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getdatabasedir is INACTIVE. */ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0300, Function | MediumTest | Level1) { @@ -128,8 +128,8 @@ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLi /** * @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0400 * @tc.name: DispatchLifecycleState - * @tc.desc: Test whether attachbasecontext is called normally, - * and verify whether the return value of getdatabasedir is INITIAL. + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getdatabasedir is INITIAL. */ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0400, Function | MediumTest | Level1) { @@ -147,8 +147,8 @@ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLi /** * @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0500 * @tc.name: DispatchLifecycleState - * @tc.desc: Test whether attachbasecontext is called normally, - * and verify whether the return value of getdatabasedir is UNINITIALIZED. + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getdatabasedir is UNINITIALIZED. */ HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0500, Function | MediumTest | Level1) { diff --git a/frameworks/kits/ability/native/test/unittest/ability_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_test.cpp index b3252756dbc35ec76e8e4c3389f474a390bdcc0a..7bd0af5b4b43dd43a554dc39474d479194fe2e2a 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_test.cpp @@ -34,7 +34,6 @@ using namespace testing::ext; using namespace OHOS; using namespace OHOS::AppExecFwk; using OHOS::Parcel; -const int TARGET_VERSION_THRESHOLDS = 8; class AbilityBaseTest : public testing::Test { public: @@ -686,11 +685,11 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnForeground_0300, Function | MediumTest std::shared_ptr abilityInfo = std::make_shared(); AbilityType type = AbilityType::PAGE; abilityInfo->type = type; + abilityInfo->isStageBasedModel = true; std::shared_ptr application = nullptr; std::shared_ptr handler = nullptr; sptr token = nullptr; ability_->Init(abilityInfo, application, handler, token); - ability_->SetCompatibleVersion(TARGET_VERSION_THRESHOLDS); Want want; ability_->OnForeground(want); @@ -766,11 +765,11 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0300, Function | MediumTest std::shared_ptr abilityInfo = std::make_shared(); AbilityType type = AbilityType::PAGE; abilityInfo->type = type; + abilityInfo->isStageBasedModel = true; std::shared_ptr application = nullptr; std::shared_ptr handler = nullptr; sptr token = nullptr; ability_->Init(abilityInfo, application, handler, token); - ability_->SetCompatibleVersion(TARGET_VERSION_THRESHOLDS); ability_->OnBackground(); AbilityLifecycleExecutor::LifecycleState state = ability_->GetState(); diff --git a/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp b/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp index dd227924b8eb1185454b86c3621adf4651e4d375..5767493533f83a53367591d302bf48e801fe7c51 100644 --- a/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp @@ -67,7 +67,7 @@ void DataAbilityHelperForObserverTest::TearDown(void) HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetFileTypes_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -100,7 +100,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetFileTypes_ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetFileTypes_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -133,7 +133,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetFileTypes_ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenFile_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -163,7 +163,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenFile_0100 HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenFile_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -193,7 +193,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenFile_0200 HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Insert_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -224,7 +224,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Insert_0100, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Insert_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -255,7 +255,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Insert_0200, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Update_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -287,7 +287,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Update_0100, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Update_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -319,7 +319,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Update_0200, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Delete_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -349,7 +349,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Delete_0100, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Delete_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -379,7 +379,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Delete_0200, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Query_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -411,7 +411,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Query_0100, F HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Query_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -443,7 +443,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Query_0200, F HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetType_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -472,7 +472,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetType_0100, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetType_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -501,7 +501,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetType_0200, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenRawFile_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -531,7 +531,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenRawFile_0 HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenRawFile_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -561,7 +561,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenRawFile_0 HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Reload_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -588,7 +588,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Reload_0100, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Reload_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -615,7 +615,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Reload_0200, HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_BatchInsert_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -642,7 +642,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_BatchInsert_0 HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_BatchInsert_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -669,7 +669,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_BatchInsert_0 HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -677,7 +677,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_ std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); // Test to AbilityThread interface - auto returnNormalizeUri = [&](const Uri &uri) { + auto returnNormalizeUri = [&](const Uri &uri) { Uri uriValue("dataability://device_id/com.domainname.dataability."); return uriValue; }; @@ -686,7 +686,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_ .WillOnce(testing::Invoke(returnNormalizeUri)); dataAbilityHelper->NormalizeUri(*uri); - + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_0100 end"; } @@ -698,7 +698,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_0200, Function | MediumTest | Level3) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -706,7 +706,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_ std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); // Test to AbilityThread interface - auto returnNormalizeUri = [&](const Uri &uri) { + auto returnNormalizeUri = [&](const Uri &uri) { Uri uriValue("dataability://device_id/com.domainname.dataability."); return uriValue; }; @@ -727,7 +727,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_DenormalizeUri_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_0100 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -735,7 +735,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_DenormalizeUr std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); // Test to AbilityThread interface - auto returnDenormalizeUri = [&](const Uri &uri) { + auto returnDenormalizeUri = [&](const Uri &uri) { Uri uriValue("dataability://device_id/com.domainname.dataability."); return uriValue; }; @@ -756,7 +756,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_DenormalizeUr HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_DenormalizeUri_0200, Function | MediumTest | Level3) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_0200 start"; - + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); mockTools->SetMockStatus(true); std::shared_ptr context = std::make_shared(); @@ -764,7 +764,7 @@ HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_DenormalizeUr std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); // Test to AbilityThread interface - auto returnDenormalizeUri = [&](const Uri &uri) { + auto returnDenormalizeUri = [&](const Uri &uri) { Uri uriValue("dataability://device_id/com.domainname.dataability."); return uriValue; }; diff --git a/frameworks/kits/ability/native/test/unittest/form_ability_test.cpp b/frameworks/kits/ability/native/test/unittest/form_ability_test.cpp index aad5d943bbcdb10123a5de0e2e77ba3cdaaf513f..3549b48d6e4f8f46fa5b5b570e6ab617948f9208 100644 --- a/frameworks/kits/ability/native/test/unittest/form_ability_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/form_ability_test.cpp @@ -412,12 +412,12 @@ HWTEST_F(FormAbilityTest, AaFwk_Ability_DeleteForm_0100, Function | MediumTest | .SetElementName(deviceId2, bundleName2, abilityName2) .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); std::shared_ptr callback_2; - + ability_->appCallbacks_.insert(std::make_pair(120L, callback1)); ability_->userReqParams_.insert(std::make_pair(120L, want1)); ability_->appCallbacks_.insert(std::make_pair(121L, callback_2)); ability_->userReqParams_.insert(std::make_pair(121L, want2)); - + int64_t formId = 120L; ability_->DeleteForm(formId); @@ -497,7 +497,7 @@ HWTEST_F(FormAbilityTest, AaFwk_Ability_DeleteForm_0400, Function | MediumTest | .SetElementName(deviceId2, bundleName2, abilityName2) .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); std::shared_ptr callback2; - + ability_->appCallbacks_.insert(std::make_pair(120L, callback1)); ability_->userReqParams_.insert(std::make_pair(120L, want1)); ability_->appCallbacks_.insert(std::make_pair(121L, callback2)); @@ -1098,7 +1098,7 @@ HWTEST_F(FormAbilityTest, AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0200, F .SetElementName(deviceId2, bundleName2, abilityName2) .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); std::shared_ptr callback2; - + FormMgr::GetInstance().RegisterDeathCallback(ability_); int64_t formId1 = 200L; @@ -1157,7 +1157,7 @@ HWTEST_F(FormAbilityTest, AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0300, F .SetElementName(deviceId2, bundleName2, abilityName2) .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); std::shared_ptr callback2; - + FormMgr::GetInstance().RegisterDeathCallback(ability_); int64_t formId1 = 200L; diff --git a/frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp b/frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp index 3900a34b74407cef5ee263edf3490846512579c7..2413235ee239f40ab56e114653b3b21825423c52 100644 --- a/frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp @@ -33,7 +33,7 @@ using OHOS::Parcel; class FormHostClientTest : public testing::Test { public: - FormHostClientTest() + FormHostClientTest() {} ~FormHostClientTest() {} diff --git a/frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp b/frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp index fdaa12710bb044be19a641e741f50c3fb219cb36..79c0c40871e03ed3458011d1fd1005c5c4c9a1c2 100644 --- a/frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp @@ -35,7 +35,7 @@ const std::string FORM_SUPPLY_INFO = "com.form.supply.info.test"; class FormProviderClientTest : public testing::Test { public: - FormProviderClientTest() + FormProviderClientTest() {} ~FormProviderClientTest() {} @@ -71,9 +71,9 @@ void FormProviderClientTest::SetUp(void) Permission::PermissionKit::AddDefPermissions(permList); std::vector permnameList; permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_MANAGER_SERVICE_BUNDLE_NAME, + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_MANAGER_SERVICE_BUNDLE_NAME, permnameList, 0); - Permission::PermissionKit::GrantUserGrantedPermission(FORM_MANAGER_SERVICE_BUNDLE_NAME, + Permission::PermissionKit::GrantUserGrantedPermission(FORM_MANAGER_SERVICE_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -224,7 +224,7 @@ HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_EventNotify_0100, Func // callerToken const sptr callerToken = MockFormSupplyCallback::GetInstance(); - + // want Want want; want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) @@ -259,7 +259,7 @@ HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_EventNotify_0200, Func // callerToken const sptr callerToken = MockFormSupplyCallback::GetInstance(); - + // want Want want; want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) diff --git a/frameworks/kits/appkit/BUILD.gn b/frameworks/kits/appkit/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d91dfff8a08b36379f27d1b1ad433d8da9679d28 --- /dev/null +++ b/frameworks/kits/appkit/BUILD.gn @@ -0,0 +1,245 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("appkit_config") { + defines = [ + "APP_LOG_TAG = \"AppkitNative\"", + "LOG_DOMAIN = 0xD001150", + ] + + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/intent/include", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "${aafwk_path}/interfaces/innerkits/want/include", + "//utils/system/safwk/native/include", + "${aafwk_path}/interfaces/innerkits/app_manager/include/appmgr", + "${aafwk_path}/frameworks/kits/ability/native/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "//third_party/json/include", + ] +} + +config("appkit_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "//base/global/resmgr_standard/interfaces/innerkits/include", + "//base/global/i18n_standard/frameworks/intl/include", + "//third_party/icu/icu4c/source/common", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/include", + ] +} + +#build bin +ohos_executable("appexec") { + include_dirs = [ + "${appexecfwk_path}/common/log/include", + "${aafwk_path}/interfaces/innerkits/app_manager/include/appmgr", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/ability/native/include", + "${aafwk_path}/interfaces/innerkits/base/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/services/abilitymgr/include", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context", + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//utils/native/base/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + configs = [ ":appkit_config" ] + + sources = [ "${aafwk_path}/frameworks/kits/appkit/native/app/src/main.cpp" ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + install_enable = true + part_name = "ability_runtime" +} + +# build so +ohos_shared_library("appkit_native") { + include_dirs = [ + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/include", + "${aafwk_path}/interfaces/innerkits/app_manager/include/appmgr", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context", + "${aafwk_path}/frameworks/kits/appkit/native", + "${aafwk_path}/frameworks/kits/ability/native/include", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/services/abilitymgr/include", + "//utils/native/base/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk_L2/content", + + "${aafwk_path}/common/task_dispatcher/include/dispatcher", + "${aafwk_path}/common/task_dispatcher/include/task", + "${aafwk_path}/common/task_dispatcher/include/threading", + "${aafwk_path}/frameworks/kits/appkit/native/app/include/task", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + "//base/hiviewdfx/faultloggerd/interfaces/innerkits/faultloggerd_client/include", + "//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher/include", + ] + + configs = [ ":appkit_config" ] + + public_configs = [ ":appkit_public_config" ] + + sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/app/src/ability_manager.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/ability_record_mgr.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/application_context.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/application_env.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/application_env_impl.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/application_impl.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/context_container.cpp", + + #"${aafwk_path}/frameworks/kits/appkit/native/app/main.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_registry.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/delegator_thread.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/runner_runtime/js_test_runner.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/shell_cmd_result.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/test_runner.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/context_deal.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/main_thread.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/ohos_application.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/sys_mgr_client.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/watchdog.cpp", + "//foundation/aafwk/standard/tools/aa/src/shell_command_result.cpp", + "//foundation/aafwk/standard/tools/aa/src/test_observer_proxy.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/common/task_dispatcher:appkit_dispatcher_td", + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:app_context", + "${aafwk_path}/interfaces/innerkits/ability_manager:ability_manager", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher:lib_dfx_dump_catcher", + "//base/hiviewdfx/faultloggerd/interfaces/innerkits/faultloggerd_client:libfaultloggerd", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", + "//third_party/icu/icu4c:shared_icuuc", + "//utils/native/base:utils", + ] + + public_deps = [ + "//base/global/i18n_standard/frameworks/intl:intl_util", + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + ] + external_deps = [ + "ability_runtime:runtime", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] + + part_name = "ability_runtime" +} + +# build so +ohos_shared_library("app_context") { + include_dirs = [ + "//base/account/os_account/frameworks/common/account_error/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/log/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//utils/system/safwk/native/include", + ] + + configs = [ ":appkit_config" ] + + public_configs = [ ":appkit_public_config" ] + + sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/sys_mgr_client.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + + # "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/common/task_dispatcher:appkit_dispatcher_td", + "${aafwk_path}/interfaces/innerkits/ability_manager:ability_manager", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", + "//third_party/icu/icu4c:shared_icuuc", + "//utils/native/base:utils", + ] + + public_deps = [ + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//base/global/i18n_standard/frameworks/intl:intl_util", + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + ] + + external_deps = [ + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] + + part_name = "ability_runtime" +} diff --git a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h new file mode 100644 index 0000000000000000000000000000000000000000..d970c48d466338d8313cb1069bbde592b72f6d55 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_H + +#include +#include +#include +#include +#include +#include +#include + +#include "iability_monitor.h" +#include "delegator_thread.h" +#include "shell_cmd_result.h" +#include "test_runner.h" + +#include "ability_lifecycle_callbacks.h" +#include "ability_lifecycle_executor.h" +#include "ability_runtime/context/context.h" +#include "main_thread.h" + +namespace OHOS { +namespace AppExecFwk { +class AbilityDelegator : public AbilityLifecycleCallbacks, public std::enable_shared_from_this { +public: + enum class AbilityState : uint8_t { + UNINITIALIZED = 0, + STARTED, + FOREGROUND, + BACKGROUND, + STOPED + }; + + using ability_property = std::tuple, std::shared_ptr, AbilityDelegator::AbilityState>; + using list_ability_property = std::list; + +public: + AbilityDelegator(const sptr &mainThread, std::unique_ptr runner, + const sptr &observer); + ~AbilityDelegator(); + + void Init(); + + void OnAbilityStart(const std::shared_ptr &ability) override; + void OnAbilityInactive(const std::shared_ptr &ability) override; + void OnAbilityBackground(const std::shared_ptr &ability) override; + void OnAbilityForeground(const std::shared_ptr &ability) override; + void OnAbilityActive(const std::shared_ptr &ability) override; + void OnAbilityStop(const std::shared_ptr &ability) override; + void OnAbilitySaveState(const PacMap &outState) override; + + void AddAbilityMonitor(const std::shared_ptr &monitor); + void RemoveAbilityMonitor(const std::shared_ptr &monitor); + void ClearAllMonitors(); + size_t GetMonitorsNum(); + + sptr WaitAbilityMonitor(const std::shared_ptr &monitor); + sptr WaitAbilityMonitor( + const std::shared_ptr &monitor, const int64_t timeoutMs); + + std::shared_ptr GetAppContext() const; + AbilityDelegator::AbilityState GetAbilityState(const sptr &token); + sptr GetCurrentTopAbility(); + std::string GetThreadName() const; + + void Prepare(); + void OnRun(); + + bool DoAbilityForeground(const sptr &token); + bool DoAbilityBackground(const sptr &token); + + std::unique_ptr ExecuteShellCommand(const std::string &cmd, const int64_t timeoutMs); + + void Print(const std::string &msg); + + void PrePerformStart(const std::shared_ptr &ability); + void PostPerformStart(const std::shared_ptr &ability); + void PrePerformScenceCreated(const std::shared_ptr &ability); + void PrePerformScenceRestored(const std::shared_ptr &ability); + void PrePerformScenceDestroyed(const std::shared_ptr &ability); + void PrePerformForeground(const std::shared_ptr &ability); + void PrePerformBackground(const std::shared_ptr &ability); + void PrePerformStop(const std::shared_ptr &ability); + +private: + AbilityDelegator::AbilityState ConvertAbilityState(const AbilityLifecycleExecutor::LifecycleState lifecycleState); + void ProcessAbilityProperties(const std::shared_ptr &ability); + sptr GetAbilityToken(const std::shared_ptr &ability); + std::optional DoesPropertyExist(const sptr &token); + void FinishUserTest(const int32_t resultCode); + +private: + static constexpr size_t FIRST_PROPERTY {0}; + static constexpr size_t SECOND_PROPERTY {1}; + static constexpr size_t THIRD_PROPERTY {2}; + +private: + sptr mainThread_; + std::unique_ptr testRunner_; + std::unique_ptr delegatorThread_; + list_ability_property abilityProperties_; + std::vector> abilityMonitors_; + std::shared_ptr appContext_; + sptr observer_; + + std::mutex mutexMonitor_; + std::mutex mutexAbilityProperties_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_H diff --git a/frameworks/kits/ability/native/include/continuation/distributed/distributed_client.h b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_args.h similarity index 43% rename from frameworks/kits/ability/native/include/continuation/distributed/distributed_client.h rename to frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_args.h index d340c456e8c6f7cdd36fffc672b3752e9db6c732..f091705abed7c91657308b4a66890a429ce17d31 100644 --- a/frameworks/kits/ability/native/include/continuation/distributed/distributed_client.h +++ b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_args.h @@ -13,43 +13,41 @@ * limitations under the License. */ -#ifndef FOUNDATION_AAFWK_STANDARD_FRAMEWORKS_KITS_ABILITY_NATIVE_INCLUDE_CONTINUATION_DISTRIBUTED_CLIENT_H -#define FOUNDATION_AAFWK_STANDARD_FRAMEWORKS_KITS_ABILITY_NATIVE_INCLUDE_CONTINUATION_DISTRIBUTED_CLIENT_H - +#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_ARGS_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_ARGS_H +#include #include -#include -#include "ability.h" -#include "ability_info.h" -#include "want_params.h" #include "want.h" -#include "iremote_broker.h" -#include "distributed_errors.h" - -#include "distributed_sched_proxy.h" namespace OHOS { namespace AppExecFwk { -using namespace OHOS::DistributedSchedule; +class AbilityDelegatorArgs { +public: + static const std::string KEY_TEST_RUNNER_CLASS; + static const std::string KEY_TEST_CASE; -class DistributedClient { public: - DistributedClient(); - virtual ~DistributedClient(); - static std::shared_ptr GetInstance(); - ErrCode Connect(); - ErrCode NotifyCompleteContinuation( - const std::u16string &devId, int32_t sessionId, bool isSuccess, const sptr &reverseScheduler); + AbilityDelegatorArgs(); + explicit AbilityDelegatorArgs(const AAFwk::Want &want); -private: - static std::mutex mutex_; - static std::shared_ptr instance_; - sptr remoteObject_; + ~AbilityDelegatorArgs(); - std::shared_ptr dmsProxy_; -}; + void SetTestBundleName(const std::string &bundleName); + std::string GetTestBundleName() const; + std::string GetTestRunnerClassName() const; + std::string GetTestCaseName() const; + + void SetTestParam(const std::map ¶ms); + std::map GetTestParam() const; + +private: + std::string bundleName_; + std::map params_; +}; } // namespace AppExecFwk } // namespace OHOS -#endif \ No newline at end of file + +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_ARGS_H diff --git a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_registry.h b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..6b40a7d135bd3239c85aebb2be71fd4984c75972 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_registry.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_REGISTRY_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_REGISTRY_H + +#include +#include "ability_delegator.h" +#include "ability_delegator_args.h" + +namespace OHOS { +namespace AppExecFwk { +class AbilityDelegatorRegistry { +public: + static std::shared_ptr GetAbilityDelegator(); + static std::shared_ptr GetArguments(); + static void RegisterInstance( + const std::shared_ptr &delegator, const std::shared_ptr &args); + +private: + static std::shared_ptr abilityDelegator_; + static std::shared_ptr abilityDelegatorArgs_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_REGISTRY_H diff --git a/frameworks/kits/appkit/native/ability_delegator/include/delegator_thread.h b/frameworks/kits/appkit/native/ability_delegator/include/delegator_thread.h new file mode 100644 index 0000000000000000000000000000000000000000..136c60dd2db015c8e2a63ea4b452ef4cff19d324 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/delegator_thread.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_DELEGATOR_THREAD_H +#define FOUNDATION_APPEXECFWK_OHOS_DELEGATOR_THREAD_H + +#include +#include +#include +#include "event_handler.h" +#include "event_runner.h" + +namespace OHOS { +namespace AppExecFwk { +class DelegatorThread { +public: + using DTask = std::function; + +public: + explicit DelegatorThread(bool isMain = false); + ~DelegatorThread() = default; + + bool Run(const DTask &task); + std::string GetThreadName() const; + +private: + std::string threadName_; + std::shared_ptr runner_; + std::shared_ptr handler_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_DELEGATOR_THREAD_H diff --git a/frameworks/kits/appkit/native/ability_delegator/include/iability_monitor.h b/frameworks/kits/appkit/native/ability_delegator/include/iability_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..00a01e0dea99bb423aa8dd85b955b3e752f6c8b9 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/iability_monitor.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_IABILITY_MONITORE_H +#define FOUNDATION_APPEXECFWK_OHOS_IABILITY_MONITORE_H + +#include +#include +#include +#include +#include +#include + +#include "ability.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class IAbilityMonitor { +public: + static constexpr int64_t MAX_TIME_OUT {5000}; + +public: + explicit IAbilityMonitor(const std::string &abilityName); + virtual ~IAbilityMonitor() = default; + + virtual bool Match(const std::shared_ptr &ability, const Want &want); + + virtual std::shared_ptr waitForAbility(); + virtual std::shared_ptr waitForAbility(const int64_t timeoutMs); + + virtual void OnAbilityStart(); + virtual void OnAbilityForeground(); + virtual void OnAbilityBackground(); + virtual void OnAbilityStop(); + + virtual void OnWindowStageCreate(); + virtual void OnWindowStageRestore(); + virtual void OnWindowStageDestroy(); + +private: + std::string abilityName_; + std::shared_ptr matchedAbility_; + + std::condition_variable cvMatch_; + std::mutex mMatch_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_IABILITY_MONITORE_H diff --git a/frameworks/kits/appkit/native/ability_delegator/include/runner_runtime/js_test_runner.h b/frameworks/kits/appkit/native/ability_delegator/include/runner_runtime/js_test_runner.h new file mode 100755 index 0000000000000000000000000000000000000000..8752158751d428f9e20648f78650f5a176430b72 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/runner_runtime/js_test_runner.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 RUNNER_RUNTIME_JS_TEST_RUNNER_H +#define RUNNER_RUNTIME_JS_TEST_RUNNER_H + +#include "js_runtime.h" +#include "test_runner.h" + +class NativeReference; +class NativeValue; + +namespace OHOS { +namespace RunnerRuntime { +using namespace AppExecFwk; +using namespace AbilityRuntime; + +class JsTestRunner : public TestRunner { +public: + static std::unique_ptr Create( + const std::unique_ptr &runtime, const std::shared_ptr &args); + + JsTestRunner(JsRuntime &jsRuntime, const std::shared_ptr &args); + ~JsTestRunner() override; + + void Prepare() override; + void Run() override; + +private: + void CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0); + + JsRuntime &jsRuntime_; + std::unique_ptr jsTestRunnerObj_; +}; +} // namespace RunnerRuntime +} // namespace OHOS +#endif // RUNNER_RUNTIME_JS_TEST_RUNNER_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_delegator/include/shell_cmd_result.h b/frameworks/kits/appkit/native/ability_delegator/include/shell_cmd_result.h new file mode 100644 index 0000000000000000000000000000000000000000..800ff29c632e84524af5214504f060e366c61af3 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/shell_cmd_result.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_SHELL_CMD_RESULT_H +#define FOUNDATION_APPEXECFWK_OHOS_SHELL_CMD_RESULT_H + +#include +#include "shell_command_result.h" + +namespace OHOS { +namespace AppExecFwk { +class ShellCmdResult { +public: + ShellCmdResult() = default; + ShellCmdResult(const int32_t exitCode, const std::string &stdResult); + ShellCmdResult(const AAFwk::ShellCommandResult &result); + ~ShellCmdResult() = default; + + void SetExitCode(const int32_t exitCode); + int32_t GetExitCode() const; + + void SetStdResult(const std::string &stdResult); + std::string GetStdResult() const; + + std::string Dump(); + +private: + int32_t exitCode_ {-1}; + std::string stdResult_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_SHELL_CMD_RESULT_H diff --git a/frameworks/kits/appkit/native/ability_delegator/include/test_runner.h b/frameworks/kits/appkit/native/ability_delegator/include/test_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..ac4efc187ef145212ee756bf4aca91abfb2562a7 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/test_runner.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_TEST_RUNNER_H +#define FOUNDATION_APPEXECFWK_OHOS_TEST_RUNNER_H + +#include +#include "ability_delegator_args.h" + +namespace OHOS { +namespace AbilityRuntime { +class Runtime; +} + +namespace AppExecFwk { +class TestRunner { +public: + static std::unique_ptr Create(const std::unique_ptr& runtime, + const std::shared_ptr &args); + + TestRunner() = default; + virtual ~TestRunner() = default; + + virtual void Prepare(); + virtual void Run(); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_TEST_RUNNER_H diff --git a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2126710309487fe0e80ab1a48afad7f540b2ee93 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp @@ -0,0 +1,598 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_delegator.h" + +#include "app_log_wrapper.h" +#include "ohos_application.h" +#include "ability_manager_client.h" +#include "ability_delegator_registry.h" +#include "itest_observer.h" + +namespace OHOS { +namespace AppExecFwk { +AbilityDelegator::AbilityDelegator(const sptr &mainThread, std::unique_ptr runner, + const sptr &observer) + : mainThread_(mainThread), testRunner_(std::move(runner)), observer_(observer) +{} + +AbilityDelegator::~AbilityDelegator() +{ + if (mainThread_) { + auto app = mainThread_->GetApplication(); + if (app) { + app->UnregisterAbilityLifecycleCallbacks(shared_from_this()); + } + } +} + +void AbilityDelegator::Init() +{ + APP_LOGI("Enter"); + + if (!mainThread_) { + APP_LOGE("Invalid mainThread"); + return; + } + + auto app = mainThread_->GetApplication(); + if (!app) { + APP_LOGE("Invalid application"); + return; + } + + appContext_ = app->GetAppContext(); + app->RegisterAbilityLifecycleCallbacks(shared_from_this()); +} + +void AbilityDelegator::OnAbilityStart(const std::shared_ptr &ability) +{ + ProcessAbilityProperties(ability); +} + +void AbilityDelegator::OnAbilityInactive(const std::shared_ptr &ability) +{} + +void AbilityDelegator::OnAbilityBackground(const std::shared_ptr &ability) +{ + ProcessAbilityProperties(ability); +} + +void AbilityDelegator::OnAbilityForeground(const std::shared_ptr &ability) +{ + ProcessAbilityProperties(ability); +} + +void AbilityDelegator::OnAbilityActive(const std::shared_ptr &ability) +{} + +void AbilityDelegator::OnAbilityStop(const std::shared_ptr &ability) +{ + ProcessAbilityProperties(ability); +} + +void AbilityDelegator::OnAbilitySaveState(const PacMap &outState) +{} + +void AbilityDelegator::AddAbilityMonitor(const std::shared_ptr &monitor) +{ + if (!monitor) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + auto pos = std::find(abilityMonitors_.begin(), abilityMonitors_.end(), monitor); + if (pos != abilityMonitors_.end()) { + APP_LOGW("Monitor has been added"); + return; + } + + abilityMonitors_.emplace_back(monitor); +} + +void AbilityDelegator::RemoveAbilityMonitor(const std::shared_ptr &monitor) +{ + if (!monitor) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + auto pos = std::find(abilityMonitors_.begin(), abilityMonitors_.end(), monitor); + if (pos != abilityMonitors_.end()) { + abilityMonitors_.erase(pos); + } +} + +void AbilityDelegator::ClearAllMonitors() +{ + std::unique_lock lck(mutexMonitor_); + abilityMonitors_.clear(); +} + +size_t AbilityDelegator::GetMonitorsNum() +{ + std::unique_lock lck(mutexMonitor_); + return abilityMonitors_.size(); +} + +sptr AbilityDelegator::WaitAbilityMonitor(const std::shared_ptr &monitor) +{ + if (!monitor) { + APP_LOGW("Invalid input parameter"); + return {}; + } + + AddAbilityMonitor(monitor); + + auto obtainedAbility = monitor->waitForAbility(); + if (!obtainedAbility) { + APP_LOGW("Invalid obtained ability"); + return {}; + } + + return GetAbilityToken(obtainedAbility); +} + +sptr AbilityDelegator::WaitAbilityMonitor( + const std::shared_ptr &monitor, const int64_t timeoutMs) +{ + if (!monitor) { + APP_LOGW("Invalid input parameter"); + return {}; + } + + AddAbilityMonitor(monitor); + + auto obtainedAbility = monitor->waitForAbility(timeoutMs); + if (!obtainedAbility) { + APP_LOGW("Invalid obtained ability"); + return {}; + } + + return GetAbilityToken(obtainedAbility); +} + +std::shared_ptr AbilityDelegator::GetAppContext() const +{ + return appContext_; +} + +AbilityDelegator::AbilityState AbilityDelegator::GetAbilityState(const sptr &token) +{ + if (!token) { + APP_LOGW("Invalid input parameter"); + return AbilityDelegator::AbilityState::UNINITIALIZED; + } + + std::unique_lock lck(mutexAbilityProperties_); + auto existedProperty = DoesPropertyExist(token); + if (!existedProperty) { + APP_LOGW("Unknown ability token"); + return AbilityDelegator::AbilityState::UNINITIALIZED; + } + + return std::get(existedProperty.value()); +} + +sptr AbilityDelegator::GetCurrentTopAbility() +{ + sptr topAbilityToken; + if (AAFwk::AbilityManagerClient::GetInstance()->GetCurrentTopAbility(topAbilityToken)) { + APP_LOGE("Failed to get top ability"); + return {}; + } + + return topAbilityToken; +} + +std::string AbilityDelegator::GetThreadName() const +{ + return {}; +} + +void AbilityDelegator::Prepare() +{ + APP_LOGI("Enter"); + if (!testRunner_) { + APP_LOGW("Invalid TestRunner"); + return; + } + + APP_LOGI("Call TestRunner::Prepare()"); + testRunner_->Prepare(); + + if (!delegatorThread_) { + delegatorThread_ = std::make_unique(true); + if (!delegatorThread_) { + APP_LOGE("Create delegatorThread failed"); + return; + } + } + + auto runTask = [this]() { this->OnRun(); }; + if (!delegatorThread_->Run(runTask)) { + APP_LOGE("Run task on delegatorThread failed"); + } +} + +void AbilityDelegator::OnRun() +{ + APP_LOGI("Enter"); + if (!testRunner_) { + APP_LOGW("Invalid TestRunner"); + return; + } + + APP_LOGI("Call TestRunner::Run(), Start run"); + testRunner_->Run(); + APP_LOGI("Run finished"); +} + +bool AbilityDelegator::DoAbilityForeground(const sptr &token) +{ + if (!token) { + APP_LOGW("Invalid input parameter"); + return false; + } + + if (AAFwk::AbilityManagerClient::GetInstance()->DelegatorDoAbilityForeground(token)) { + APP_LOGE("Failed to call DelegatorDoAbilityForeground"); + return false; + } + + return true; +} + +bool AbilityDelegator::DoAbilityBackground(const sptr &token) +{ + if (!token) { + APP_LOGW("Invalid input parameter"); + return false; + } + + if (AAFwk::AbilityManagerClient::GetInstance()->DelegatorDoAbilityBackground(token)) { + APP_LOGE("Failed to call DelegatorDoAbilityBackground"); + return false; + } + + return true; +} + +std::unique_ptr AbilityDelegator::ExecuteShellCommand(const std::string &cmd, const int64_t timeoutMs) +{ + APP_LOGI("command : %{public}s, timeout : %{public}" PRId64, cmd.data(), timeoutMs); + + if (cmd.empty()) { + APP_LOGE("Invalid cmd"); + return {}; + } + + auto testObserver = iface_cast(observer_); + if (!testObserver) { + APP_LOGW("Invalid testObserver"); + return {}; + } + + auto result = testObserver->ExecuteShellCommand(cmd, timeoutMs); + return std::make_unique(result); +} + +void AbilityDelegator::Print(const std::string &msg) +{ + auto testObserver = iface_cast(observer_); + if (!testObserver) { + APP_LOGW("Invalid testObserver"); + return; + } + + testObserver->TestStatus(msg, 0); +} + +void AbilityDelegator::PrePerformStart(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + monitor->OnAbilityStart(); + } +} + +void AbilityDelegator::PostPerformStart(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + } +} + +void AbilityDelegator::PrePerformScenceCreated(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + monitor->OnWindowStageCreate(); + } +} + +void AbilityDelegator::PrePerformScenceRestored(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + monitor->OnWindowStageRestore(); + } +} + +void AbilityDelegator::PrePerformScenceDestroyed(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + monitor->OnWindowStageDestroy(); + } +} + +void AbilityDelegator::PrePerformForeground(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + monitor->OnAbilityForeground(); + } +} + +void AbilityDelegator::PrePerformBackground(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + monitor->OnAbilityBackground(); + } +} + +void AbilityDelegator::PrePerformStop(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid input parameter"); + return; + } + + std::unique_lock lck(mutexMonitor_); + if (abilityMonitors_.empty()) { + APP_LOGW("Empty abilityMonitors"); + return; + } + + for (auto &monitor : abilityMonitors_) { + if (!monitor) { + continue; + } + + monitor->Match(ability, {}); + monitor->OnAbilityStop(); + } +} + +AbilityDelegator::AbilityState AbilityDelegator::ConvertAbilityState( + const AbilityLifecycleExecutor::LifecycleState lifecycleState) +{ + AbilityDelegator::AbilityState abilityState {AbilityDelegator::AbilityState::UNINITIALIZED}; + switch (lifecycleState) { + case AbilityLifecycleExecutor::LifecycleState::STARTED_NEW: + abilityState = AbilityDelegator::AbilityState::STARTED; + break; + case AbilityLifecycleExecutor::LifecycleState::FOREGROUND_NEW: + abilityState = AbilityDelegator::AbilityState::FOREGROUND; + break; + case AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW: + abilityState = AbilityDelegator::AbilityState::BACKGROUND; + break; + case AbilityLifecycleExecutor::LifecycleState::STOPED_NEW: + abilityState = AbilityDelegator::AbilityState::STOPED; + break; + default: + APP_LOGE("Unknown lifecycleState"); + break; + } + + return abilityState; +} + +void AbilityDelegator::ProcessAbilityProperties(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid ability"); + return; + } + + auto abilityToken = GetAbilityToken(ability); + if (!abilityToken) { + APP_LOGE("Invalid ability token"); + return; + } + + std::unique_lock lck(mutexAbilityProperties_); + auto existedProperty = DoesPropertyExist(abilityToken); + if (existedProperty) { + abilityProperties_.remove(existedProperty.value()); + } + + auto abilityState = ConvertAbilityState(ability->GetState()); + if (abilityState == AbilityDelegator::AbilityState::FOREGROUND) { + abilityProperties_.emplace_front(abilityToken, ability, abilityState); + } else { + abilityProperties_.emplace_back(abilityToken, ability, abilityState); + } +} + +sptr AbilityDelegator::GetAbilityToken(const std::shared_ptr &ability) +{ + if (!ability) { + APP_LOGW("Invalid ability"); + return {}; + } + + auto abilityContext = ability->GetAbilityContext(); + if (!abilityContext) { + APP_LOGE("Invalid ability context"); + return {}; + } + + return abilityContext->GetAbilityToken(); +} + +std::optional AbilityDelegator::DoesPropertyExist(const sptr &token) +{ + if (!token) { + APP_LOGW("Invalid input parameter"); + return std::nullopt; + } + + for (auto &it : abilityProperties_) { + auto tmpToken = std::get(it); + if (token == tmpToken) { + return it; + } + } + + return std::nullopt; +} + +void AbilityDelegator::FinishUserTest(const int32_t resultCode) +{ + APP_LOGI("Enter"); + + if (!mainThread_) { + APP_LOGE("Invalid mainThread"); + return; + } + + if (!observer_) { + APP_LOGE("Invalid observer"); + return; + } + + auto delegatorArgs = AbilityDelegatorRegistry::GetArguments(); + if (!delegatorArgs) { + APP_LOGE("Invalid delegator args"); + return; + } + + const auto &bundleName = delegatorArgs->GetTestBundleName(); + + mainThread_->FinishUserTest("UserTest finished", resultCode, bundleName, observer_); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44fbeee45da24eecbc806470121bdada5dc2eb57 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_delegator_args.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string AbilityDelegatorArgs::KEY_TEST_RUNNER_CLASS {"-s unittest"}; +const std::string AbilityDelegatorArgs::KEY_TEST_CASE {"-s class"}; + +AbilityDelegatorArgs::AbilityDelegatorArgs() +{} + +AbilityDelegatorArgs::AbilityDelegatorArgs(const AAFwk::Want &want) +{ + bundleName_ = want.GetStringParam("-p"); + params_["-p"] = want.GetStringParam("-p"); + params_["-s unittest"] = want.GetStringParam("-s unittest"); + params_["-s class"] = want.GetStringParam("-s class"); + if (!want.GetStringParam("-w").empty()) { + params_["-w"] = want.GetStringParam("-w"); + } +} + +AbilityDelegatorArgs::~AbilityDelegatorArgs() +{} + +void AbilityDelegatorArgs::SetTestBundleName(const std::string &bundleName) +{ + bundleName_ = bundleName; +} + +std::string AbilityDelegatorArgs::GetTestBundleName() const +{ + return bundleName_; +} + +std::string AbilityDelegatorArgs::GetTestRunnerClassName() const +{ + auto target = params_.find(AbilityDelegatorArgs::KEY_TEST_RUNNER_CLASS); + if (target != params_.end()) { + return target->second; + } + + return {}; +} + +std::string AbilityDelegatorArgs::GetTestCaseName() const +{ + auto target = params_.find(AbilityDelegatorArgs::KEY_TEST_CASE); + if (target != params_.end()) { + return target->second; + } + + return {}; +} + +void AbilityDelegatorArgs::SetTestParam(const std::map ¶ms) +{ + params_ = params; +} + +std::map AbilityDelegatorArgs::GetTestParam() const +{ + return params_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_registry.cpp b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_registry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4ff7b2ba17c9ef19e8ee5cd55772bd542d38049 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_registry.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_delegator_registry.h" + +namespace OHOS { +namespace AppExecFwk { +std::shared_ptr AbilityDelegatorRegistry::abilityDelegator_ {}; +std::shared_ptr AbilityDelegatorRegistry::abilityDelegatorArgs_ {}; + +std::shared_ptr AbilityDelegatorRegistry::GetAbilityDelegator() +{ + return abilityDelegator_; +} + +std::shared_ptr AbilityDelegatorRegistry::GetArguments() +{ + return abilityDelegatorArgs_; +} + +void AbilityDelegatorRegistry::RegisterInstance( + const std::shared_ptr &delegator, const std::shared_ptr &args) +{ + abilityDelegator_ = delegator; + abilityDelegatorArgs_ = args; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/delegator_thread.cpp b/frameworks/kits/appkit/native/ability_delegator/src/delegator_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6685dafe8852068147142b2ecd01a78a569247a5 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/delegator_thread.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "delegator_thread.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +DelegatorThread::DelegatorThread(bool isMain) +{ + if (isMain) { + runner_ = EventRunner::GetMainEventRunner(); + } else { + runner_ = EventRunner::Create(); + } + + handler_ = std::make_shared(runner_); +} + +bool DelegatorThread::Run(const DTask &task) +{ + if (!task) { + APP_LOGW("Invalid input parameter"); + return false; + } + + if (!handler_) { + APP_LOGW("Invalid EventHandler"); + return false; + } + + return handler_->PostTask(task); +} + +std::string DelegatorThread::GetThreadName() const +{ + return threadName_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp b/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c592bcd1e6aa4ec6f9808a4c34fda051d839cce2 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "iability_monitor.h" +#include "app_log_wrapper.h" + +using namespace std::chrono_literals; + +namespace OHOS { +namespace AppExecFwk { +IAbilityMonitor::IAbilityMonitor(const std::string &abilityName) : abilityName_(abilityName) +{} + +bool IAbilityMonitor::Match(const std::shared_ptr &ability, const Want &want) +{ + std::string aName; + if (ability) { + aName = ability->GetAbilityName(); + } else { + aName = want.GetElement().GetAbilityName(); + } + + if (abilityName_.empty() || aName.empty()) { + APP_LOGW("Invalid name"); + return false; + } + + if (abilityName_.compare(aName)) { + APP_LOGW("Different name"); + return false; + } + + if (ability) { + { + std::lock_guard matchLock(mMatch_); + matchedAbility_ = ability; + } + cvMatch_.notify_one(); + + return true; + } + + return false; +} + +std::shared_ptr IAbilityMonitor::waitForAbility() +{ + return waitForAbility(MAX_TIME_OUT); +} + +std::shared_ptr IAbilityMonitor::waitForAbility(const int64_t timeoutMs) +{ + auto realTime = timeoutMs; + if (timeoutMs <= 0) { + APP_LOGW("Timeout should be a positive number"); + realTime = MAX_TIME_OUT; + } + + std::unique_lock matchLock(mMatch_); + + auto condition = [this] { return this->matchedAbility_ != nullptr; }; + if (!cvMatch_.wait_for(matchLock, realTime * 1ms, condition)) { + APP_LOGW("Wait ability timeout"); + } + + return matchedAbility_; +} + +void IAbilityMonitor::OnAbilityStart() +{} + +void IAbilityMonitor::OnAbilityForeground() +{} + +void IAbilityMonitor::OnAbilityBackground() +{} + +void IAbilityMonitor::OnAbilityStop() +{} + +void IAbilityMonitor::OnWindowStageCreate() +{} + +void IAbilityMonitor::OnWindowStageRestore() +{} + +void IAbilityMonitor::OnWindowStageDestroy() +{} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/runner_runtime/js_test_runner.cpp b/frameworks/kits/appkit/native/ability_delegator/src/runner_runtime/js_test_runner.cpp new file mode 100755 index 0000000000000000000000000000000000000000..43c744dd203b3c5ff64e583783f749fd86ba8938 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/runner_runtime/js_test_runner.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "js_runtime_utils.h" +#include "runner_runtime/js_test_runner.h" + +namespace OHOS { +namespace RunnerRuntime { +std::unique_ptr JsTestRunner::Create( + const std::unique_ptr &runtime, const std::shared_ptr &args) +{ + return std::make_unique(static_cast(*runtime), args); +} + +JsTestRunner::JsTestRunner(JsRuntime &jsRuntime, const std::shared_ptr &args) + : jsRuntime_(jsRuntime) +{ + std::string srcPath; + srcPath.append(args->GetTestBundleName()); + srcPath.append("/assets/js/"); + srcPath.append(args->GetTestRunnerClassName()); + srcPath.append(".abc"); + APP_LOGI("JsTestRunner srcPath is %{public}s", srcPath.c_str()); + + std::string moduleName; + jsTestRunnerObj_ = jsRuntime_.LoadModule(moduleName, srcPath); +} + +JsTestRunner::~JsTestRunner() = default; + +void JsTestRunner::Prepare() +{ + APP_LOGI("Enter"); + TestRunner::Prepare(); + CallObjectMethod("onPrepare"); + APP_LOGI("End"); +} + +void JsTestRunner::Run() +{ + APP_LOGI("Enter"); + TestRunner::Run(); + CallObjectMethod("onRun"); + APP_LOGI("End"); +} + +void JsTestRunner::CallObjectMethod(const char *name, NativeValue *const *argv, size_t argc) +{ + APP_LOGI("JsTestRunner::CallObjectMethod(%{public}s)", name); + + if (!jsTestRunnerObj_) { + APP_LOGE("Not found test_runner.js"); + return; + } + + HandleScope handleScope(jsRuntime_); + auto &nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue *value = jsTestRunnerObj_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + APP_LOGE("Failed to get Test Runner object"); + return; + } + + NativeValue *methodOnCreate = obj->GetProperty(name); + if (methodOnCreate == nullptr) { + APP_LOGE("Failed to get '%{public}s' from Test Runner object", name); + return; + } + nativeEngine.CallFunction(value, methodOnCreate, argv, argc); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/shell_cmd_result.cpp b/frameworks/kits/appkit/native/ability_delegator/src/shell_cmd_result.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23060d8f0100cf49c4d3053055d0564a9163e741 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/shell_cmd_result.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "shell_cmd_result.h" + +namespace OHOS { +namespace AppExecFwk { +ShellCmdResult::ShellCmdResult(const int32_t exitCode, const std::string &stdResult) + : exitCode_(exitCode), stdResult_(stdResult) +{} + +ShellCmdResult::ShellCmdResult(const AAFwk::ShellCommandResult &result) +{ + exitCode_ = result.exitCode; + stdResult_ = result.stdResult; +} + +void ShellCmdResult::SetExitCode(const int32_t exitCode) +{ + exitCode_ = exitCode; +} + +int32_t ShellCmdResult::GetExitCode() const +{ + return exitCode_; +} + +void ShellCmdResult::SetStdResult(const std::string &stdResult) +{ + stdResult_ = stdResult; +} + +std::string ShellCmdResult::GetStdResult() const +{ + return stdResult_; +} + +std::string ShellCmdResult::Dump() +{ + return "ShellCmdResult { exitCode = " + std::to_string(exitCode_) + ", stdResult = " + stdResult_ + "}"; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/test_runner.cpp b/frameworks/kits/appkit/native/ability_delegator/src/test_runner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4980f057f5cc9603d2b65902f7e6407c2ffa9435 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/src/test_runner.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_runner.h" +#include "runtime.h" +#include "runner_runtime/js_test_runner.h" + +namespace OHOS { +namespace AppExecFwk { +std::unique_ptr TestRunner::Create(const std::unique_ptr& runtime, + const std::shared_ptr &args) +{ + if (!runtime) { + return std::make_unique(); + } + + switch (runtime->GetLanguage()) { + case AbilityRuntime::Runtime::Language::JS: + return RunnerRuntime::JsTestRunner::Create(runtime, args); + default: + return std::make_unique(); + } +} + +void TestRunner::Prepare() +{} + +void TestRunner::Run() +{} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e249e7dfea2a62b620f05006ff117b75f3c9a3b4 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_stage.h" + +#include "hilog_wrapper.h" +#include "js_ability_stage.h" +#include "runtime.h" + +namespace OHOS { +namespace AbilityRuntime { +std::shared_ptr AbilityStage::Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo) +{ + if (!runtime) { + return std::make_shared(); + } + + switch (runtime->GetLanguage()) { + case Runtime::Language::JS: + return JsAbilityStage::Create(runtime, hapModuleInfo); + + default: + return std::make_shared(); + } +} + +void AbilityStage::OnCreate() const +{ + HILOG_INFO("AbilityStage::OnCreate come"); +} + +void AbilityStage::OnDestory() const +{ + HILOG_INFO("AbilityStage::OnDestory come"); +} + +std::shared_ptr AbilityStage::GetContext() const +{ + return context_; +} + +void AbilityStage::Init(std::shared_ptr context) +{ + this->context_ = context; +} + +void AbilityStage::AddAbility(const sptr &token, + std::shared_ptr abilityRecord) +{ + if (token == nullptr) { + HILOG_ERROR("AbilityStage::AddAbility failed, token is nullptr"); + return; + } + + if (abilityRecord == nullptr) { + HILOG_ERROR("AbilityStage::AddAbility failed, abilityRecord is nullptr"); + return; + } + + abilityRecords_[token] = abilityRecord; +} + +void AbilityStage::RemoveAbility(const sptr &token) +{ + if (token == nullptr) { + HILOG_ERROR("AbilityStage::RemoveAbility failed, token is nullptr"); + return; + } + abilityRecords_.erase(token); +} + +bool AbilityStage::ContainsAbility() +{ + return abilityRecords_.size() > 0; +} + +std::string AbilityStage::OnAcceptWant(const AAFwk::Want &want) +{ + HILOG_INFO("AbilityStage::OnAcceptWant come"); + return ""; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.h b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.h new file mode 100644 index 0000000000000000000000000000000000000000..9718625f0112b9a36968619f70453eecbaad420f --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_ABILITY_STAGE_H +#define ABILITY_RUNTIME_ABILITY_STAGE_H + +#include +#include +#include + +#include "ability_local_record.h" +#include "ability_runtime/context/context.h" +#include "want.h" + +namespace OHOS { +namespace AbilityRuntime { +class Runtime; +/** + * @brief the hap level entity + * + * To share the data amony the abilities of a hap, + * and supply lifecycle func for the developers. + * + */ +class AbilityStage { +public: + static std::shared_ptr Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo); + + AbilityStage() = default; + virtual ~AbilityStage() = default; + virtual void OnCreate() const; + virtual void OnDestory() const; + virtual std::string OnAcceptWant(const AAFwk::Want &want); + virtual void Init(std::shared_ptr context); + std::shared_ptr GetContext() const; + void AddAbility(const sptr &token, std::shared_ptr abilityRecord); + void RemoveAbility(const sptr &token); + bool ContainsAbility(); +private: + std::shared_ptr context_; + std::map, std::shared_ptr> abilityRecords_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_ABILITY_STAGE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e8984849b96c7f39cf61bd3701983b7b4914644 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_ability_stage.h" + +#include "hilog_wrapper.h" +#include "js_context_utils.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi_common_util.h" +#include "napi_common_want.h" + +namespace OHOS { +namespace AbilityRuntime { +std::shared_ptr JsAbilityStage::Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo) +{ + auto& jsRuntime = static_cast(*runtime); + std::string srcPath(hapModuleInfo.name); + + /* temporary compatibility api8 + config.json */ + if (!hapModuleInfo.isModuleJson) { + srcPath.append("/assets/js/"); + if (hapModuleInfo.srcPath.empty()) { + srcPath.append("AbilityStage.abc"); + } else { + srcPath.append(hapModuleInfo.srcPath); + srcPath.append("/AbilityStage.abc"); + } + std::string moduleName(hapModuleInfo.moduleName); + moduleName.append("::").append("AbilityStage"); + auto moduleObj = jsRuntime.LoadModule(moduleName, srcPath); + return std::make_shared(jsRuntime, std::move(moduleObj)); + } + + std::unique_ptr moduleObj; + srcPath.append("/"); + if (!hapModuleInfo.srcEntrance.empty()) { + srcPath.append(hapModuleInfo.srcEntrance); + srcPath.erase(srcPath.rfind(".")); + srcPath.append(".abc"); + std::string moduleName(hapModuleInfo.moduleName); + moduleName.append("::").append("AbilityStage"); + moduleObj = jsRuntime.LoadModule(moduleName, srcPath); + HILOG_INFO("JsAbilityStage srcPath is %{public}s", srcPath.c_str()); + } + return std::make_shared(jsRuntime, std::move(moduleObj)); +} + +JsAbilityStage::JsAbilityStage(JsRuntime& jsRuntime, std::unique_ptr&& jsAbilityStageObj) + : jsRuntime_(jsRuntime), jsAbilityStageObj_(std::move(jsAbilityStageObj)) +{} + +JsAbilityStage::~JsAbilityStage() = default; + +void JsAbilityStage::Init(std::shared_ptr context) +{ + AbilityStage::Init(context); + + if (!context) { + HILOG_ERROR("context is nullptr"); + return; + } + + if (!jsAbilityStageObj_) { + return; + } + + HandleScope handleScope(jsRuntime_); + auto& engine = jsRuntime_.GetNativeEngine(); + + NativeObject* obj = ConvertNativeValueTo(jsAbilityStageObj_->Get()); + if (obj == nullptr) { + HILOG_ERROR("Failed to get AbilityStage object"); + return; + } + + NativeValue* contextObj = CreateJsBaseContext(engine, context); + auto shellContextRef = jsRuntime_.LoadSystemModule("application.AbilityStageContext", &contextObj, 1); + contextObj = shellContextRef->Get(); + + context->Bind(jsRuntime_, shellContextRef.release()); + obj->SetProperty("context", contextObj); + + auto nativeObj = ConvertNativeValueTo(contextObj); + if (nativeObj == nullptr) { + HILOG_ERROR("Failed to get ability stage native object"); + return; + } + + HILOG_INFO("Set ability stage context pointer: %{public}p", context.get()); + + nativeObj->SetNativePointer(new std::weak_ptr(context), + [](NativeEngine*, void* data, void*) { + HILOG_INFO("Finalizer for weak_ptr ability stage context is called"); + delete static_cast*>(data); + }, nullptr); +} + +void JsAbilityStage::OnCreate() const +{ + HILOG_INFO("JsAbilityStage::OnCreate come"); + + AbilityStage::OnCreate(); + + if (!jsAbilityStageObj_) { + HILOG_WARN("Not found AbilityStage.js"); + return; + } + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* value = jsAbilityStageObj_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get AbilityStage object"); + return; + } + + NativeValue* methodOnCreate = obj->GetProperty("onCreate"); + if (methodOnCreate == nullptr) { + HILOG_ERROR("Failed to get 'onCreate' from AbilityStage object"); + return; + } + nativeEngine.CallFunction(value, methodOnCreate, nullptr, 0); +} + +std::string JsAbilityStage::OnAcceptWant(const AAFwk::Want &want) +{ + HILOG_INFO("JsAbilityStage::OnAcceptWant come"); + + AbilityStage::OnAcceptWant(want); + + if (!jsAbilityStageObj_) { + HILOG_WARN("Not found AbilityStage.js"); + return ""; + } + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* value = jsAbilityStageObj_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get AbilityStage object"); + return ""; + } + + napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(&nativeEngine), want); + NativeValue* jsWant = reinterpret_cast(napiWant); + + NativeValue* methodOnAcceptWant = obj->GetProperty("onAcceptWant"); + if (methodOnAcceptWant == nullptr) { + HILOG_ERROR("Failed to get 'OnAcceptWant' from AbilityStage object"); + return ""; + } + + NativeValue* argv[] = { jsWant }; + NativeValue* flagNative = nativeEngine.CallFunction(value, methodOnAcceptWant, argv, 1); + return AppExecFwk::UnwrapStringFromJS( + reinterpret_cast(&nativeEngine), reinterpret_cast(flagNative)); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.h b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.h new file mode 100644 index 0000000000000000000000000000000000000000..c6020b238248865ac8c26f068752ee6bd2a78b26 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_JS_ABILITY_STAGE_H +#define ABILITY_RUNTIME_JS_ABILITY_STAGE_H + +#include "ability_stage.h" + +class NativeReference; + +namespace OHOS { +namespace AbilityRuntime { +class JsRuntime; +class JsAbilityStage : public AbilityStage { +public: + static std::shared_ptr Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo); + + JsAbilityStage(JsRuntime& jsRuntime, std::unique_ptr&& jsAbilityStageObj); + ~JsAbilityStage() override; + + void Init(std::shared_ptr context) override; + + void OnCreate() const override; + + std::string OnAcceptWant(const AAFwk::Want &want) override; + +private: + JsRuntime& jsRuntime_; + std::unique_ptr jsAbilityStageObj_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_ABILITY_STAGE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/context/bindable.h b/frameworks/kits/appkit/native/ability_runtime/context/bindable.h new file mode 100644 index 0000000000000000000000000000000000000000..4fea92b45aed37dfd02615f84d38d3000d7dcfff --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/bindable.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_BINDABLE_H +#define ABILITY_RUNTIME_BINDABLE_H + +#include + +namespace OHOS { +namespace AbilityRuntime { +class Runtime; + +class BindingObject final { +public: + template + BindingObject(Runtime& runtime, T* ptr) : runtime_(runtime), object_(ptr, SimpleRelease) {} + ~BindingObject() = default; + + template + T* Get() + { + return static_cast(object_.get()); + } + + void Reset() + { + object_.reset(); + } + + Runtime& GetRuntime() + { + return runtime_; + } + + BindingObject(const BindingObject&) = delete; + BindingObject& operator=(const BindingObject&) = delete; + BindingObject(BindingObject&&) = delete; + BindingObject& operator=(BindingObject&&) = delete; + +private: + template + static void SimpleRelease(void* ptr) + { + delete static_cast(ptr); + } + + Runtime& runtime_; + std::unique_ptr object_; +}; + +class Bindable { +public: + virtual ~Bindable() = default; + + template + void Bind(Runtime& runtime, T* object) + { + object_ = std::make_unique(runtime, object); + } + + const std::unique_ptr& GetBindingObject() const + { + return object_; + } + +protected: + Bindable() = default; + +private: + std::unique_ptr object_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_BINDABLE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/context/context.h b/frameworks/kits/appkit/native/ability_runtime/context/context.h new file mode 100755 index 0000000000000000000000000000000000000000..c2ae9a9b18a3f28bd11808a288f15de618f3d119 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/context.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_CONTEXT_H +#define ABILITY_RUNTIME_CONTEXT_H + +#include +#include + +#include "application_info.h" +#include "bindable.h" +#include "hap_module_info.h" +#include "resource_manager.h" + +namespace OHOS { +namespace AbilityRuntime { +class Context : public Bindable { +public: + Context() = default; + ~Context() override = default; + + /** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ + static std::shared_ptr GetApplicationContext(); + + /** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ + virtual std::string GetBundleName() const = 0; + + /** + * @brief Creates a Context object for an application with the given bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * + * @return Returns a Context object created for the specified application. + */ + virtual std::shared_ptr CreateBundleContext(const std::string &bundleName) = 0; + + /** + * @brief Obtains information about the current application. The returned application information includes basic + * information such as the application name and application permissions. + * + * @return Returns the ApplicationInfo for the current application. + */ + virtual std::shared_ptr GetApplicationInfo() const = 0; + + /** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ + virtual std::shared_ptr GetResourceManager() const = 0; + + /** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ + virtual std::string GetBundleCodePath() const = 0; + + /** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ + virtual std::shared_ptr GetHapModuleInfo() const = 0; + + /** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ + virtual std::string GetBundleCodeDir() = 0; + + /** + * @brief Obtains the application-specific cache directory on the device's internal storage. The system + * automatically deletes files from the cache directory if disk space is required elsewhere on the device. + * Older files are always deleted first. + * + * @return Returns the application-specific cache directory. + */ + virtual std::string GetCacheDir() = 0; + + /** + * @brief Obtains the temporary directory. + * + * @return Returns the application temporary directory. + */ + virtual std::string GetTempDir() = 0; + + /** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ + virtual std::string GetFilesDir() = 0; + + /** + * @brief Obtains the local database path. + * If the local database path does not exist, the system creates one and returns the created path. + * + * @return Returns the local database file. + */ + virtual std::string GetDatabaseDir() = 0; + + /** + * @brief Obtains the path storing the storage file of the application. + * + * @return Returns the local storage file. + */ + virtual std::string GetStorageDir() = 0; + + /** + * @brief Obtains the path distributed file of the application + * + * @return Returns the distributed file. + */ + virtual std::string GetDistributedFilesDir() = 0; + + /** + * @brief Switch file area + * + * @param mode file area. + */ + virtual void SwitchArea(int mode) = 0; + + /** + * @brief Getting derived class + * + * @tparam T template + * @param context the context object + * @return std::shared_ptr derived class + */ + template + static std::shared_ptr ConvertTo(const std::shared_ptr& context) + { + if constexpr (!std::is_same_v) { + return nullptr; + } + + if (context && context->IsContext(T::CONTEXT_TYPE_ID)) { + return std::static_pointer_cast(context); + } + + return nullptr; + } + + using SelfType = Context; + static const size_t CONTEXT_TYPE_ID; + +protected: + virtual bool IsContext(size_t contextTypeId) + { + return contextTypeId == CONTEXT_TYPE_ID; + } + + static std::shared_ptr appContext_; + static std::mutex contextMutex_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_CONTEXT_H diff --git a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b3d253f3870c187d23e3148342aa65986ce86625 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp @@ -0,0 +1,380 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "context_impl.h" + +#include "hilog_wrapper.h" +#include "ipc_singleton.h" +#include "locale_config.h" +#include "os_account_manager.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AbilityRuntime { +const size_t Context::CONTEXT_TYPE_ID(std::hash {} ("Context")); +const int64_t ContextImpl::CONTEXT_CREATE_BY_SYSTEM_APP(0x00000001); +const std::string ContextImpl::CONTEXT_DATA_APP("/data/app/"); +const std::string ContextImpl::CONTEXT_BUNDLE("/bundle/"); +const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE("/mnt/hmdfs/"); +const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE("/device_view/local/data/"); +const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES("distributedfiles"); +const std::string ContextImpl::CONTEXT_FILE_SEPARATOR("/"); +const std::string ContextImpl::CONTEXT_DATA("/data/"); +const std::string ContextImpl::CONTEXT_DATA_STORAGE("/data/storage/"); +const std::string ContextImpl::CONTEXT_BASE("base"); +const std::string ContextImpl::CONTEXT_PRIVATE("/private/"); +const std::string ContextImpl::CONTEXT_CACHES("caches"); +const std::string ContextImpl::CONTEXT_STORAGE("storage"); +const std::string ContextImpl::CONTEXT_DATABASE("database"); +const std::string ContextImpl::CONTEXT_TEMP("/temp"); +const std::string ContextImpl::CONTEXT_FILES("/files"); +const std::string ContextImpl::CONTEXT_HAPS("/haps"); +const std::string ContextImpl::CONTEXT_ELS[] = {"el1", "el2", "el3", "el4"}; + +std::string ContextImpl::GetBundleName() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetBundleName(); + } + return (applicationInfo_ != nullptr) ? applicationInfo_->bundleName : ""; +} + +std::string ContextImpl::GetBundleCodeDir() +{ + std::string dir; + if (IsCreateBySystemApp()) { + dir = CONTEXT_DATA_APP + CONTEXT_ELS[0] + CONTEXT_BUNDLE + GetBundleName(); + } else { + dir = CONTEXT_DATA_STORAGE + CONTEXT_ELS[0] + CONTEXT_BUNDLE; + } + HILOG_DEBUG("ContextImpl::GetBundleCodeDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetCacheDir() +{ + std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_CACHES; + HILOG_DEBUG("ContextImpl::GetCacheDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetDatabaseDir() +{ + std::string dir; + if (IsCreateBySystemApp()) { + dir = CONTEXT_DATA_APP + currArea_ + CONTEXT_FILE_SEPARATOR + std::to_string(GetCurrentAccountId()) + + CONTEXT_FILE_SEPARATOR + CONTEXT_DATABASE + GetBundleName(); + } else { + dir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_DATABASE; + } + dir = dir + CONTEXT_FILE_SEPARATOR + ((GetHapModuleInfo() == nullptr) ? "" : GetHapModuleInfo()->moduleName); + HILOG_DEBUG("ContextImpl::GetDatabaseDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetStorageDir() +{ + std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_STORAGE; + HILOG_DEBUG("ContextImpl::GetStorageDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetTempDir() +{ + std::string dir = GetBaseDir() + CONTEXT_TEMP; + HILOG_DEBUG("ContextImpl::GetTempDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetFilesDir() +{ + std::string dir = GetBaseDir() + CONTEXT_FILES; + HILOG_DEBUG("ContextImpl::GetFilesDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetDistributedFilesDir() +{ + HILOG_DEBUG("ContextImpl::GetDistributedFilesDir"); + std::string dir; + if (IsCreateBySystemApp()) { + dir = CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE + std::to_string(GetCurrentAccountId()) + + CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE + GetBundleName(); + } else { + dir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_DISTRIBUTEDFILES + + CONTEXT_FILE_SEPARATOR + ((GetHapModuleInfo() == nullptr) ? "" : GetHapModuleInfo()->moduleName); + } + HILOG_DEBUG("ContextImpl::GetDistributedFilesDir:%{public}s", dir.c_str()); + return dir; +} + +void ContextImpl::SwitchArea(int mode) +{ + HILOG_DEBUG("ContextImpl::SwitchArea, mode:%{public}d.", mode); + if (mode < 0 || mode >= (sizeof(CONTEXT_ELS) / sizeof(CONTEXT_ELS[0]))) { + HILOG_ERROR("ContextImpl::SwitchArea, mode is invalid."); + return; + } + currArea_ = CONTEXT_ELS[mode]; + HILOG_DEBUG("ContextImpl::SwitchArea end, currArea:%{public}s.", currArea_.c_str()); +} + +std::string ContextImpl::GetBaseDir() const +{ + std::string baseDir; + if (IsCreateBySystemApp()) { + baseDir = CONTEXT_DATA_APP + currArea_ + CONTEXT_FILE_SEPARATOR + std::to_string(GetCurrentAccountId()) + + CONTEXT_FILE_SEPARATOR + CONTEXT_BASE + CONTEXT_FILE_SEPARATOR + GetBundleName(); + } else { + baseDir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_BASE; + } + if (parentContext_ != nullptr) { + baseDir = baseDir + CONTEXT_HAPS + CONTEXT_FILE_SEPARATOR + + ((GetHapModuleInfo() == nullptr) ? "" : GetHapModuleInfo()->moduleName); + } + + HILOG_DEBUG("ContextImpl::GetBaseDir:%{public}s", baseDir.c_str()); + return baseDir; +} + +int ContextImpl::GetCurrentAccountId() const +{ + int userId = 0; + AccountSA::OsAccountManager::GetOsAccountLocalIdFromProcess(userId); + return userId; +} + +int ContextImpl::GetCurrentActiveAccountId() const +{ + std::vector osAccountInfos; + ErrCode ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + if (ret != ERR_OK) { + HILOG_ERROR("ContextImpl::GetCurrentActiveAccountId error."); + return 0; + } + + if (osAccountInfos.size() == 0) { + HILOG_ERROR("ContextImpl::GetCurrentActiveAccountId error, no accounts."); + return 0; + } + + if (osAccountInfos.size() > 1) { + HILOG_ERROR("ContextImpl::GetCurrentActiveAccountId error, no current now."); + return 0; + } + + return osAccountInfos[0].GetLocalId(); +} + +std::shared_ptr ContextImpl::CreateBundleContext(const std::string &bundleName) +{ + if (parentContext_ != nullptr) { + return parentContext_->CreateBundleContext(bundleName); + } + + if (bundleName.empty()) { + HILOG_ERROR("ContextImpl::CreateBundleContext bundleName is empty"); + return nullptr; + } + + sptr bundleMgr = GetBundleManager(); + if (bundleMgr == nullptr) { + HILOG_ERROR("ContextImpl::CreateBundleContext GetBundleManager is nullptr"); + return nullptr; + } + + AppExecFwk::BundleInfo bundleInfo; + int accountId = GetCurrentAccountId(); + if (accountId == 0) { + accountId = GetCurrentActiveAccountId(); + } + HILOG_DEBUG("ContextImpl::CreateBundleContext length: %{public}zu, bundleName: %{public}s, accountId: %{public}d", + (size_t)bundleName.length(), bundleName.c_str(), accountId); + bundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, accountId); + + if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) { + HILOG_ERROR("ContextImpl::CreateBundleContext GetBundleInfo is error"); + return nullptr; + } + + std::shared_ptr appContext = std::make_shared(); + appContext->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP); + + // init resourceManager. + InitResourceManager(bundleInfo, appContext); + + appContext->SetApplicationInfo(std::make_shared(bundleInfo.applicationInfo)); + return appContext; +} + +void ContextImpl::InitResourceManager( + const AppExecFwk::BundleInfo &bundleInfo, const std::shared_ptr &appContext) const +{ + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (appContext == nullptr || resourceManager == nullptr) { + HILOG_ERROR("ContextImpl::InitResourceManager create resourceManager failed"); + return; + } + + HILOG_DEBUG( + "ContextImpl::InitResourceManager moduleResPaths count: %{public}zu", bundleInfo.moduleResPaths.size()); + for (auto moduleResPath : bundleInfo.moduleResPaths) { + if (!moduleResPath.empty()) { + HILOG_ERROR("ContextImpl::InitResourceManager length: %{public}zu, moduleResPath: %{public}s", + moduleResPath.length(), + moduleResPath.c_str()); + if (!resourceManager->AddResource(moduleResPath.c_str())) { + HILOG_ERROR("ContextImpl::InitResourceManager AddResource failed"); + } + } + } + + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + UErrorCode status = U_ZERO_ERROR; + icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); + resConfig->SetLocaleInfo(locale); + if (resConfig->GetLocaleInfo() != nullptr) { + HILOG_DEBUG("ContextImpl::InitResourceManager language: %{public}s, script: %{public}s, region: %{public}s,", + resConfig->GetLocaleInfo()->getLanguage(), + resConfig->GetLocaleInfo()->getScript(), + resConfig->GetLocaleInfo()->getCountry()); + } else { + HILOG_ERROR("ContextImpl::InitResourceManager language: GetLocaleInfo is null."); + } + resourceManager->UpdateResConfig(*resConfig); + appContext->SetResourceManager(resourceManager); +} + +sptr ContextImpl::GetBundleManager() const +{ + HILOG_DEBUG("ContextImpl::GetBundleManager begin"); + auto bundleObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility( + BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleObj == nullptr) { + HILOG_ERROR("failed to get bundle manager service"); + return nullptr; + } + HILOG_DEBUG("ContextImpl::GetBundleManager before iface_cast"); + sptr bms = iface_cast(bundleObj); + HILOG_DEBUG("ContextImpl::GetBundleManager after iface_cast"); + HILOG_DEBUG("ContextImpl::GetBundleManager end"); + return bms; +} + +void ContextImpl::SetApplicationInfo(const std::shared_ptr &info) +{ + if (info == nullptr) { + HILOG_ERROR("ContextImpl::SetApplicationInfo failed, info is empty"); + return; + } + applicationInfo_ = info; +} + +void ContextImpl::SetResourceManager(const std::shared_ptr &resourceManager) +{ + HILOG_DEBUG("ContextImpl::initResourceManager. Start."); + resourceManager_ = resourceManager; + HILOG_DEBUG("ContextImpl::initResourceManager. End."); +} + +std::shared_ptr ContextImpl::GetResourceManager() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetResourceManager(); + } + + return resourceManager_; +} + +std::shared_ptr ContextImpl::GetApplicationInfo() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetApplicationInfo(); + } + + return applicationInfo_; +} + +void ContextImpl::SetParentContext(const std::shared_ptr &context) +{ + parentContext_ = context; +} + +std::string ContextImpl::GetBundleCodePath() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetBundleCodePath(); + } + return (applicationInfo_ != nullptr) ? applicationInfo_->codePath : ""; +} + +void ContextImpl::InitHapModuleInfo(const std::shared_ptr &abilityInfo) +{ + if (hapModuleInfo_ != nullptr || abilityInfo == nullptr) { + return; + } + sptr ptr = GetBundleManager(); + if (ptr == nullptr) { + HILOG_ERROR("InitHapModuleInfo: failed to get bundle manager service"); + return; + } + + hapModuleInfo_ = std::make_shared(); + if (!ptr->GetHapModuleInfo(*abilityInfo.get(), *hapModuleInfo_)) { + HILOG_ERROR("InitHapModuleInfo: GetHapModuleInfo failed, will retval false value"); + } +} + +void ContextImpl::InitHapModuleInfo(const AppExecFwk::HapModuleInfo &hapModuleInfo) +{ + hapModuleInfo_ = std::make_shared(hapModuleInfo); +} + +std::shared_ptr ContextImpl::GetHapModuleInfo() const +{ + if (hapModuleInfo_ == nullptr) { + HILOG_ERROR("ContextImpl::GetHapModuleInfo, hapModuleInfo is empty"); + } + return hapModuleInfo_; +} + +void ContextImpl::SetFlags(int64_t flags) +{ + flags_ = static_cast(flags_) | CONTEXT_CREATE_BY_SYSTEM_APP; +} + +bool ContextImpl::IsCreateBySystemApp() const +{ + return (static_cast(flags_) & CONTEXT_CREATE_BY_SYSTEM_APP) == 1; +} + +std::shared_ptr Context::appContext_ = nullptr; +std::mutex Context::contextMutex_; + +std::shared_ptr Context::GetApplicationContext() +{ + std::lock_guard lock(contextMutex_); + return appContext_; +} + +void ContextImpl::InitAppContext() +{ + std::lock_guard lock(Context::contextMutex_); + Context::appContext_ = shared_from_this(); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..a6de5ba025b26f6606de409160b1c1e8cb7100c4 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_CONTEXT_IMPL_H +#define ABILITY_RUNTIME_CONTEXT_IMPL_H + +#include "context.h" + +#include "bundle_mgr_interface.h" + +namespace OHOS { +namespace AbilityRuntime { +class ContextImpl : public Context, public std::enable_shared_from_this { +public: + ContextImpl() = default; + virtual ~ContextImpl() = default; + + /** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ + std::string GetBundleName() const override; + + /** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ + std::string GetBundleCodeDir() override; + + /** + * @brief Obtains the application-specific cache directory on the device's internal storage. The system + * automatically deletes files from the cache directory if disk space is required elsewhere on the device. + * Older files are always deleted first. + * + * @return Returns the application-specific cache directory. + */ + std::string GetCacheDir() override; + + /** + * @brief Obtains the temporary directory. + * + * @return Returns the application temporary directory. + */ + std::string GetTempDir() override; + + /** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ + std::string GetFilesDir() override; + + /** + * @brief Obtains the local database path. + * If the local database path does not exist, the system creates one and returns the created path. + * + * @return Returns the local database file. + */ + std::string GetDatabaseDir() override; + + /** + * @brief Obtains the path storing the storage file of the application. + * + * @return Returns the local storage file. + */ + std::string GetStorageDir() override; + + /** + * @brief Obtains the path distributed file of the application + * + * @return Returns the distributed file. + */ + std::string GetDistributedFilesDir() override; + + /** + * @brief Switch file area + * + * @param mode file area. + */ + void SwitchArea(int mode) override; + + /** + * @brief set the ResourceManager. + * + * @param the ResourceManager has been inited. + * + */ + void SetResourceManager(const std::shared_ptr &resourceManager); + + /** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ + std::shared_ptr GetResourceManager() const override; + + /** + * @brief Creates a Context object for an application with the given bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * + * @return Returns a Context object created for the specified application. + */ + std::shared_ptr CreateBundleContext(const std::string &bundleName) override; + + /** + * @brief Obtains an IBundleMgr instance. + * You can use this instance to obtain information about the application bundle. + * + * @return Returns an IBundleMgr instance. + */ + sptr GetBundleManager() const; + + /** + * @brief Set ApplicationInfo + * + * @param info ApplicationInfo instance. + */ + void SetApplicationInfo(const std::shared_ptr &info); + + /** + * @brief Obtains information about the current application. The returned application information includes basic + * information such as the application name and application permissions. + * + * @return Returns the ApplicationInfo for the current application. + */ + std::shared_ptr GetApplicationInfo() const override; + + /** + * @brief Set ApplicationInfo + * + * @param info ApplicationInfo instance. + */ + void SetParentContext(const std::shared_ptr &context); + + /** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ + std::string GetBundleCodePath() const override; + + /** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ + std::shared_ptr GetHapModuleInfo() const override; + + /** + * @brief Set HapModuleInfo + * + * @param hapModuleInfo HapModuleInfo instance. + */ + void InitHapModuleInfo(const std::shared_ptr &abilityInfo); + + /** + * @brief Set HapModuleInfo + * + * @param hapModuleInfo HapModuleInfo instance. + */ + void InitHapModuleInfo(const AppExecFwk::HapModuleInfo &hapModuleInfo); + + /** + * @brief Set application context + */ + void InitAppContext(); +private: + static const int64_t CONTEXT_CREATE_BY_SYSTEM_APP; + static const std::string CONTEXT_DATA_APP; + static const std::string CONTEXT_BUNDLE; + static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE; + static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE; + static const std::string CONTEXT_DISTRIBUTEDFILES; + static const std::string CONTEXT_FILE_SEPARATOR; + static const std::string CONTEXT_DATA; + static const std::string CONTEXT_DATA_STORAGE; + static const std::string CONTEXT_BASE; + static const std::string CONTEXT_PRIVATE; + static const std::string CONTEXT_CACHES; + static const std::string CONTEXT_STORAGE; + static const std::string CONTEXT_DATABASE; + static const std::string CONTEXT_TEMP; + static const std::string CONTEXT_FILES; + static const std::string CONTEXT_HAPS; + static const std::string CONTEXT_ELS[]; + static const int EL_DEFAULT = 1; + int flags_ = 0x00000000; + + void InitResourceManager( + const AppExecFwk::BundleInfo &bundleInfo, const std::shared_ptr &appContext) const; + bool IsCreateBySystemApp() const; + std::string GetBaseDir() const; + int GetCurrentAccountId() const; + void SetFlags(int64_t flags); + int GetCurrentActiveAccountId() const; + + std::shared_ptr applicationInfo_ = nullptr; + std::shared_ptr parentContext_ = nullptr; + std::shared_ptr resourceManager_ = nullptr; + std::shared_ptr hapModuleInfo_ = nullptr; + std::string currArea_ = CONTEXT_ELS[EL_DEFAULT]; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_CONTEXT_IMPL_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp b/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp new file mode 100755 index 0000000000000000000000000000000000000000..08c265d7c6faae0b5110e5bd47955592c5a85e80 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_context_utils.h" + +#include "hilog_wrapper.h" +#include "js_data_struct_converter.h" +#include "js_hap_module_info_utils.h" +#include "js_resource_manager_utils.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr char BASE_CONTEXT_NAME[] = "__base_context_ptr__"; + +class JsBaseContext { +public: + explicit JsBaseContext(std::weak_ptr&& context) : context_(std::move(context)) {} + virtual ~JsBaseContext() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint); + static NativeValue* CreateBundleContext(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetApplicationContext(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* SwitchArea(NativeEngine* engine, NativeCallbackInfo* info); + + void KeepContext(std::shared_ptr context) + { + keepContext_ = context; + } + +private: + NativeValue* OnCreateBundleContext(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetApplicationContext(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnSwitchArea(NativeEngine& engine, NativeCallbackInfo& info); + + std::shared_ptr keepContext_; + +protected: + std::weak_ptr context_; +}; + +void JsBaseContext::Finalizer(NativeEngine* engine, void* data, void* hint) +{ + HILOG_INFO("JsBaseContext::Finalizer is called"); + std::unique_ptr(static_cast(data)); +} + +NativeValue* JsBaseContext::CreateBundleContext(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnCreateBundleContext(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::GetApplicationContext(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetApplicationContext(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::SwitchArea(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnSwitchArea(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnSwitchArea(NativeEngine& engine, NativeCallbackInfo& info) +{ + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + + int mode; + if (!ConvertFromJsValue(engine, info.argv[0], mode)) { + HILOG_ERROR("Parse mode failed"); + return engine.CreateUndefined(); + } + + context->SwitchArea(mode); + + NativeValue* thisVar = info.thisVar; + NativeObject* object = ConvertNativeValueTo(thisVar); + object->SetProperty("cacheDir", CreateJsValue(engine, context->GetCacheDir())); + object->SetProperty("tempDir", CreateJsValue(engine, context->GetTempDir())); + object->SetProperty("filesDir", CreateJsValue(engine, context->GetFilesDir())); + object->SetProperty("distributedFilesDir", CreateJsValue(engine, context->GetDistributedFilesDir())); + object->SetProperty("databaseDir", CreateJsValue(engine, context->GetDatabaseDir())); + object->SetProperty("storageDir", CreateJsValue(engine, context->GetStorageDir())); + object->SetProperty("bundleCodeDir", CreateJsValue(engine, context->GetBundleCodeDir())); + + return engine.CreateUndefined(); +} + +NativeValue* JsBaseContext::OnCreateBundleContext(NativeEngine& engine, NativeCallbackInfo& info) +{ + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + + std::string bundleName; + if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) { + HILOG_ERROR("Parse bundleName failed"); + return engine.CreateUndefined(); + } + + auto bundleContext = context->CreateBundleContext(bundleName); + if (!bundleContext) { + HILOG_ERROR("bundleContext is nullptr"); + return engine.CreateUndefined(); + } + + JsRuntime& jsRuntime = *static_cast(engine.GetJsEngine()); + NativeValue* value = CreateJsBaseContext(engine, bundleContext, true); + return jsRuntime.LoadSystemModule("application.Context", &value, 1)->Get(); +} + +NativeValue* JsBaseContext::OnGetApplicationContext(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + + auto appContext = context->GetApplicationContext(); + if (!appContext) { + HILOG_ERROR("appContext is nullptr"); + return engine.CreateUndefined(); + } + + JsRuntime& jsRuntime = *static_cast(engine.GetJsEngine()); + NativeValue* value = CreateJsBaseContext(engine, appContext, true); + return jsRuntime.LoadSystemModule("application.Context", &value, 1)->Get(); +} +} // namespace + +NativeValue* CreateJsBaseContext(NativeEngine& engine, std::shared_ptr context, bool keepContext) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + auto jsContext = std::make_unique(context); + if (keepContext) { + jsContext->KeepContext(context); + } + SetNamedNativePointer(engine, *object, BASE_CONTEXT_NAME, jsContext.release(), JsBaseContext::Finalizer); + + auto appInfo = context->GetApplicationInfo(); + if (appInfo != nullptr) { + object->SetProperty("applicationInfo", CreateJsApplicationInfo(engine, *appInfo)); + } + auto hapModuleInfo = context->GetHapModuleInfo(); + if (hapModuleInfo != nullptr) { + object->SetProperty("currentHapModuleInfo", CreateJsHapModuleInfo(engine, *hapModuleInfo)); + } + auto resourceManager = context->GetResourceManager(); + if (resourceManager != nullptr) { + object->SetProperty("resourceManager", CreateJsResourceManager(engine, resourceManager)); + } + object->SetProperty("cacheDir", CreateJsValue(engine, context->GetCacheDir())); + object->SetProperty("tempDir", CreateJsValue(engine, context->GetTempDir())); + object->SetProperty("filesDir", CreateJsValue(engine, context->GetFilesDir())); + object->SetProperty("distributedFilesDir", CreateJsValue(engine, context->GetDistributedFilesDir())); + object->SetProperty("databaseDir", CreateJsValue(engine, context->GetDatabaseDir())); + object->SetProperty("storageDir", CreateJsValue(engine, context->GetStorageDir())); + object->SetProperty("bundleCodeDir", CreateJsValue(engine, context->GetBundleCodeDir())); + + BindNativeFunction(engine, *object, "createBundleContext", JsBaseContext::CreateBundleContext); + BindNativeFunction(engine, *object, "getApplicationContext", JsBaseContext::GetApplicationContext); + BindNativeFunction(engine, *object, "switchArea", JsBaseContext::SwitchArea); + + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.h b/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a6595e2ea73edea06b65252730da74ea50a52905 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_JS_CONTEXT_UTILS_H +#define ABILITY_RUNTIME_JS_CONTEXT_UTILS_H + +#include + +#include "context.h" + +class NativeEngine; +class NativeValue; +struct NativeCallbackInfo; + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsBaseContext(NativeEngine& engine, std::shared_ptr context, bool keepContext = false); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_CONTEXT_UTILS_H diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp b/frameworks/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16e2947f4244b9e80d3fdf689a926840d9f7c2b9 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_hap_module_info_utils.h" + +#include "js_data_struct_converter.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsHapModuleInfo(NativeEngine& engine, AppExecFwk::HapModuleInfo& hapModuleInfo) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + object->SetProperty("name", CreateJsValue(engine, hapModuleInfo.name)); + object->SetProperty("moduleName", CreateJsValue(engine, hapModuleInfo.moduleName)); + object->SetProperty("description", CreateJsValue(engine, hapModuleInfo.description)); + object->SetProperty("icon", CreateJsValue(engine, hapModuleInfo.iconPath)); + object->SetProperty("label", CreateJsValue(engine, hapModuleInfo.label)); + object->SetProperty("backgroundImg", CreateJsValue(engine, hapModuleInfo.backgroundImg)); + object->SetProperty("mainAbilityName", CreateJsValue(engine, hapModuleInfo.mainAbility)); + // object->SetProperty("srcPath", CreateJsValue(engine, hapModuleInfo.srcPath)); // d.ts no have + object->SetProperty("supportedModes", CreateJsValue(engine, hapModuleInfo.supportedModes)); + + NativeValue *capArrayValue = engine.CreateArray(hapModuleInfo.reqCapabilities.size()); + NativeArray *capArray = ConvertNativeValueTo(capArrayValue); + if (capArray != nullptr) { + int index = 0; + for (auto cap : hapModuleInfo.reqCapabilities) { + capArray->SetElement(index++, CreateJsValue(engine, cap)); + } + } + object->SetProperty("reqCapabilities", capArrayValue); + + NativeValue *deviceArrayValue = engine.CreateArray(hapModuleInfo.deviceTypes.size()); + NativeArray *deviceArray = ConvertNativeValueTo(deviceArrayValue); + if (deviceArray != nullptr) { + int index = 0; + for (auto device : hapModuleInfo.deviceTypes) { + deviceArray->SetElement(index++, CreateJsValue(engine, device)); + } + } + object->SetProperty("deviceTypes", deviceArrayValue); + + NativeValue *abilityArrayValue = engine.CreateArray(hapModuleInfo.abilityInfos.size()); + NativeArray *abilityArray = ConvertNativeValueTo(abilityArrayValue); + if (abilityArray != nullptr) { + int index = 0; + for (auto abilityInfo : hapModuleInfo.abilityInfos) { + abilityArray->SetElement(index++, CreateJsAbilityInfo(engine, abilityInfo)); + } + } + object->SetProperty("abilityInfo", abilityArrayValue); + + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.h b/frameworks/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..c7dfd66671b35e3bdd1e059a66e571a774ef2ce4 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H +#define ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H + +#include "hap_module_info.h" + +class NativeEngine; +class NativeValue; + +namespace OHOS { +namespace AbilityRuntime { +class JsRuntime; + +NativeValue* CreateJsHapModuleInfo(NativeEngine& engine, AppExecFwk::HapModuleInfo& hapModuleInfo); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp b/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b75cad0dfb84a2327bed40e6f1007d94acd143c0 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_resource_manager_utils.h" + +#include "hilog_wrapper.h" +#include "js_runtime_utils.h" +#include "rstate.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +const int32_t GETSTRING_PARAM_SIZE = 1; +class JsResourceManager final { +public: + JsResourceManager(const std::shared_ptr& resourceManager) + : resourceManager_(resourceManager) {} + ~JsResourceManager() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsResourceManager::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static NativeValue* GetString(NativeEngine* engine, NativeCallbackInfo* info) + { + JsResourceManager* me = CheckParamsAndGetThis(engine, info); + return me != nullptr ? me->GetString(*engine, *info) : nullptr; + } + +private: + NativeValue* GetString(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("JsResourceManager GetString is called"); + + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + NativeNumber* number = ConvertNativeValueTo(info.argv[0]); + uint32_t param = number ? *(number) : 0; + + AsyncTask::CompleteCallback complete = + [weak = resourceManager_, resId = param](NativeEngine& engine, AsyncTask& task, int32_t status) { + auto resourceManager = weak.lock(); + if (!resourceManager) { + HILOG_INFO("JsResourceManager is released"); + task.Reject(engine, CreateJsError(engine, 1, "resourceManager is released")); + return; + } + std::string retValue; + OHOS::Global::Resource::RState errval = resourceManager->GetStringById(resId, retValue); + if (errval == OHOS::Global::Resource::RState::SUCCESS) { + HILOG_DEBUG("resourceManager GetStringById:%{public}s", retValue.c_str()); + task.Resolve(engine, engine.CreateString(retValue.c_str(), retValue.length())); + } else { + HILOG_DEBUG("resourceManager GetStringById failed"); + task.Reject(engine, CreateJsError(engine, errval, "getString failed")); + } + }; + + NativeValue* lastParam = info.argc > GETSTRING_PARAM_SIZE ? info.argv[GETSTRING_PARAM_SIZE] : nullptr; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + std::weak_ptr resourceManager_; +}; +} // namespace + +NativeValue* CreateJsResourceManager( + NativeEngine& engine, std::shared_ptr resourceManager) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + std::unique_ptr jsResourceManager = std::make_unique(resourceManager); + object->SetNativePointer(jsResourceManager.release(), JsResourceManager::Finalizer, nullptr); + + BindNativeFunction(engine, *object, "getString", JsResourceManager::GetString); + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.h b/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..973231b754cb3a7f9a4447882882426886f31640 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H +#define ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H + +#include "resource_manager.h" + +class NativeEngine; +class NativeValue; + +namespace OHOS { +namespace AbilityRuntime { +class JsRuntime; + +NativeValue* CreateJsResourceManager(NativeEngine& engine, + std::shared_ptr resourceManager); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H diff --git a/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp b/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f939d4f4928006f7141de58b4b1b2b494ecced3 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "extension_context.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +const size_t ExtensionContext::CONTEXT_TYPE_ID(std::hash {} ("ExtensionContext")); + +void ExtensionContext::SetToken(const sptr &token) +{ + if (token == nullptr) { + HILOG_DEBUG("ExtensionContext::SetToken failed, application is nullptr"); + return; + } + token_ = token; +} + +sptr ExtensionContext::GetToken() const +{ + return token_; +} + +void ExtensionContext::SetAbilityInfo(const std::shared_ptr &abilityInfo) +{ + if (abilityInfo == nullptr) { + HILOG_ERROR("ExtensionContext::SetAbilityInfo Info == nullptr"); + return; + } + abilityInfo_ = abilityInfo; +} + +std::shared_ptr ExtensionContext::GetAbilityInfo() const +{ + return abilityInfo_; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/extension_context.h b/frameworks/kits/appkit/native/ability_runtime/extension_context.h new file mode 100644 index 0000000000000000000000000000000000000000..8be6220924adfe0e3a665d03e707fc693607e02d --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/extension_context.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 EXTENSION_CONTEXT_H +#define EXTENSION_CONTEXT_H + +#include "ability_info.h" +#include "context_impl.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for extension + * + */ +class ExtensionContext : public ContextImpl { +public: + ExtensionContext() = default; + virtual ~ExtensionContext() = default; + + /** + * @brief Set the token witch the app launched. + * + * @param token The token which the is launched by app. + */ + void SetToken(const sptr &token); + + /** + * @brief Get the token witch the app launched. + * + * @return token The token which the is launched by app. + */ + sptr GetToken() const; + + /** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ + std::shared_ptr GetAbilityInfo() const; + + /** + * @brief Set AbilityInfo when init. + * + */ + void SetAbilityInfo(const std::shared_ptr &abilityInfo); + + using SelfType = ExtensionContext; + static const size_t CONTEXT_TYPE_ID; + +protected: + bool IsContext(size_t contextTypeId) override + { + return contextTypeId == CONTEXT_TYPE_ID || Context::IsContext(contextTypeId); + } + + sptr token_; +private: + std::shared_ptr abilityInfo_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1918c42734cc287233b225698d9efd169e2877b5 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_extension_context.h" + +#include "appexecfwk_errors.h" +#include "form_mgr.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +const size_t FormExtensionContext::CONTEXT_TYPE_ID(std::hash {} ("FormExtensionContext")); + +int FormExtensionContext::UpdateForm(const int64_t formId, const AppExecFwk::FormProviderData &formProviderData) +{ + HILOG_DEBUG("%{public}s begin.", __func__); + // check fms recover status + if (AppExecFwk::FormMgr::GetRecoverStatus() == AppExecFwk::Constants::IN_RECOVERING) { + HILOG_ERROR("%{public}s error, form is in recover status, can't do action on form.", __func__); + return ERR_APPEXECFWK_FORM_IN_RECOVER; + } + + // check formId + if (formId <= 0) { + HILOG_ERROR("%{public}s error, the passed in formId can't be negative or zero.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // check formProviderData + if (formProviderData.GetDataString().empty()) { + HILOG_ERROR("%{public}s error, the formProviderData is null.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // update form request to fms + return AppExecFwk::FormMgr::GetInstance().UpdateForm(formId, abilityInfo_->bundleName, formProviderData); +} + +AppExecFwk::AbilityType FormExtensionContext::GetAbilityInfoType() const +{ + std::shared_ptr info = GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr"); + return AppExecFwk::AbilityType::UNKNOWN; + } + + return info->type; +} + +std::shared_ptr FormExtensionContext::GetAbilityInfo() const +{ + return abilityInfo_; +} + +void FormExtensionContext::SetAbilityInfo(const std::shared_ptr &abilityInfo) +{ + if (abilityInfo == nullptr) { + HILOG_ERROR("FormExtensionContext::SetAbilityInfo Info == nullptr"); + return; + } + abilityInfo_ = abilityInfo; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.h b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.h new file mode 100644 index 0000000000000000000000000000000000000000..0f7eae4c2cef4dd0daa07e5c3add774fcb415936 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_EXTENSION_CONTEXT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_EXTENSION_CONTEXT_H + +#include "ability_info.h" +#include "extension_context.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for form extension + * + */ +class FormExtensionContext : public ExtensionContext { +public: + FormExtensionContext() = default; + virtual ~FormExtensionContext() = default; + + /** + * @brief Updates the content of a specified JS form. + * + * @param formId Indicates the ID of the JS form to update. + * + * @param formProviderData Indicates the {@code FormProviderData} object used to update the JS form displayed + * on the client. + * + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const AppExecFwk::FormProviderData &formProviderData); + + /** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ + std::shared_ptr GetAbilityInfo() const; + + /** + * @brief Set AbilityInfo when init. + * + */ + void SetAbilityInfo(const std::shared_ptr &abilityInfo); + + using SelfType = FormExtensionContext; + static const size_t CONTEXT_TYPE_ID; + +protected: + bool IsContext(size_t contextTypeId) override + { + return contextTypeId == CONTEXT_TYPE_ID || Context::IsContext(contextTypeId); + } + +private: + /** + * @brief Get Current Ability Type + * + * @return Current Ability Type + */ + OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const; + + std::shared_ptr abilityInfo_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/service_extension_context.cpp b/frameworks/kits/appkit/native/ability_runtime/service_extension_context.cpp new file mode 100755 index 0000000000000000000000000000000000000000..f18800117c21787750fc1499d2e44da3992ad599 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/service_extension_context.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "service_extension_context.h" + +#include "ability_connection.h" +#include "ability_manager_client.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +const size_t ServiceExtensionContext::CONTEXT_TYPE_ID(std::hash {} ("ServiceExtensionContext")); +int ServiceExtensionContext::ILLEGAL_REQUEST_CODE(-1); + +ErrCode ServiceExtensionContext::StartAbility(const AAFwk::Want &want) const +{ + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, ILLEGAL_REQUEST_CODE); + HILOG_DEBUG("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err); + } + return err; +} + +ErrCode ServiceExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const +{ + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, + ILLEGAL_REQUEST_CODE); + HILOG_DEBUG("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err); + } + return err; +} + +bool ServiceExtensionContext::ConnectAbility( + const AAFwk::Want &want, const sptr &connectCallback) const +{ + HILOG_INFO("%{public}s begin.", __func__); + ErrCode ret = + ConnectionManager::GetInstance().ConnectAbility(token_, want, connectCallback); + HILOG_INFO("ServiceExtensionContext::ConnectAbility ErrorCode = %{public}d", ret); + return ret == ERR_OK; +} + +ErrCode ServiceExtensionContext::StartAbilityWithAccount(const AAFwk::Want &want, int accountId) const +{ + HILOG_DEBUG("%{public}s begin.", __func__); + HILOG_INFO("%{public}d accountId:", accountId); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility( + want, token_, ILLEGAL_REQUEST_CODE, accountId); + HILOG_DEBUG("%{public}s. End calling StartAbilityWithAccount. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("ServiceContext::StartAbilityWithAccount is failed %{public}d", err); + } + return err; +} + +ErrCode ServiceExtensionContext::StartAbilityWithAccount( + const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions) const +{ + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, + ILLEGAL_REQUEST_CODE, accountId); + HILOG_DEBUG("%{public}s. End calling StartAbilityWithAccount. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("ServiceContext::StartAbilityWithAccount is failed %{public}d", err); + } + return err; +} + +bool ServiceExtensionContext::ConnectAbilityWithAccount( + const AAFwk::Want &want, int accountId, const sptr &connectCallback) const +{ + HILOG_INFO("%{public}s begin.", __func__); + ErrCode ret = + ConnectionManager::GetInstance().ConnectAbilityWithAccount(token_, want, accountId, connectCallback); + HILOG_INFO("ServiceExtensionContext::ConnectAbilityWithAccount ErrorCode = %{public}d", ret); + return ret == ERR_OK; +} + +ErrCode ServiceExtensionContext::DisconnectAbility( + const AAFwk::Want &want, const sptr &connectCallback) const +{ + HILOG_INFO("%{public}s begin.", __func__); + ErrCode ret = + ConnectionManager::GetInstance().DisconnectAbility(token_, want.GetElement(), connectCallback); + if (ret != ERR_OK) { + HILOG_ERROR("%{public}s end DisconnectAbility error, ret=%{public}d", __func__, ret); + } + HILOG_INFO("%{public}s end DisconnectAbility", __func__); + return ret; +} + +ErrCode ServiceExtensionContext::TerminateAbility() +{ + HILOG_INFO("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr); + if (err != ERR_OK) { + HILOG_ERROR("ServiceExtensionContext::TerminateAbility is failed %{public}d", err); + } + HILOG_INFO("%{public}s end.", __func__); + return err; +} + +AppExecFwk::AbilityType ServiceExtensionContext::GetAbilityInfoType() const +{ + std::shared_ptr info = GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr"); + return AppExecFwk::AbilityType::UNKNOWN; + } + + return info->type; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/service_extension_context.h b/frameworks/kits/appkit/native/ability_runtime/service_extension_context.h new file mode 100755 index 0000000000000000000000000000000000000000..c75f9832336b658ab5e8493970e76c7141dd8865 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/service_extension_context.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 SERVICE_EXTENSION_CONTEXT_H +#define SERVICE_EXTENSION_CONTEXT_H + +#include "extension_context.h" + +#include "ability_connect_callback.h" +#include "connection_manager.h" +#include "start_options.h" +#include "want.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for service + * + */ +class ServiceExtensionContext : public ExtensionContext { +public: + ServiceExtensionContext() = default; + virtual ~ServiceExtensionContext() = default; + + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const AAFwk::Want &want) const; + + ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const; + + /** + * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. + * + * @param want Indicates the want containing information about the ability to connect + * + * @param conn Indicates the callback object when the target ability is connected. + * + * @return True means success and false means failure + */ + bool ConnectAbility( + const AAFwk::Want &want, const sptr &connectCallback) const; + + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * @param accountId caller user. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbilityWithAccount(const AAFwk::Want &want, int accountId) const; + + ErrCode StartAbilityWithAccount( + const AAFwk::Want &want, int accountId, const AAFwk::StartOptions &startOptions) const; + + /** + * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. + * + * @param want Indicates the want containing information about the ability to connect. + * + * @param accountId caller user. + * + * @param conn Indicates the callback object when the target ability is connected. + * + * @return True means success and false means failure. + */ + bool ConnectAbilityWithAccount( + const AAFwk::Want &want, int accountId, const sptr &connectCallback) const; + + /** + * @brief Disconnects the current ability from an ability. + * + * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection + * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode DisconnectAbility( + const AAFwk::Want &want, const sptr &connectCallback) const; + + /** + * @brief Destroys the current ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode TerminateAbility(); + + using SelfType = ServiceExtensionContext; + static const size_t CONTEXT_TYPE_ID; + +protected: + bool IsContext(size_t contextTypeId) override + { + return contextTypeId == CONTEXT_TYPE_ID || Context::IsContext(contextTypeId); + } + +private: + static int ILLEGAL_REQUEST_CODE; + + /** + * @brief Get Current Ability Type + * + * @return Current Ability Type + */ + OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // SERVICE_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/static_subscriber_extension_context.cpp b/frameworks/kits/appkit/native/ability_runtime/static_subscriber_extension_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7562021d22cef5a9ee1e17070801e238d7fff70f --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/static_subscriber_extension_context.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 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 "static_subscriber_extension_context.h" + +namespace OHOS { +namespace AbilityRuntime { + StaticSubscriberExtensionContext::StaticSubscriberExtensionContext() {} + + StaticSubscriberExtensionContext::~StaticSubscriberExtensionContext() {} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/static_subscriber_extension_context.h b/frameworks/kits/appkit/native/ability_runtime/static_subscriber_extension_context.h new file mode 100644 index 0000000000000000000000000000000000000000..684ddeeabd3fc86273008bb213b7a2e46aa5c652 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/static_subscriber_extension_context.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 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 FOUNDATION_APPEXECFWK_STATIC_SUBSCRIBER_EXTENSION_CONTEXT_H +#define FOUNDATION_APPEXECFWK_STATIC_SUBSCRIBER_EXTENSION_CONTEXT_H + +#include "extension_context.h" + +namespace OHOS { +namespace AbilityRuntime { +class StaticSubscriberExtensionContext : public ExtensionContext { +public: + StaticSubscriberExtensionContext(); + + virtual ~StaticSubscriberExtensionContext(); +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_STATIC_SUBSCRIBER_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/include/ability_manager.h b/frameworks/kits/appkit/native/app/include/ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..5c028146371b20ab1f643a6fcd120e7c28700502 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/ability_manager.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_MANAGER_H +#define ABILITY_MANAGER_H + +#include "ability_manager_client.h" +#include "app_mgr_interface.h" +#include "stack_info.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::AbilityManagerClient; +using OHOS::AAFwk::AbilityMissionInfo; +using OHOS::AAFwk::RECENT_IGNORE_UNAVAILABLE; +using OHOS::AAFwk::StackInfo; +using OHOS::AAFwk::Want; +using OHOS::AppExecFwk::RunningProcessInfo; +using RuningMissionInfo = AbilityMissionInfo; + +class AbilityManager { +public: + AbilityManager() = default; + virtual ~AbilityManager() = default; + + static AbilityManager &GetInstance(); + + /** + * StartAbility with want, send want to ability manager service. + * + * @param want Ability want. + * @param requestCode Ability request code. + * @return Returns ERR_OK on success, others on failure. + */ + void StartAbility(const Want &want, int requestCode); + + /** + * Ask that the mission associated with a given mission ID be moved to the + * front of the stack, so it is now visible to the user. + * + * @param missionId mission record id + */ + void MoveMissionToTop(int missionId); + + /** + * Get all stack info from ability manager service. + * + * @return Return stack information + */ + StackInfo GetAllStackInfo() const; + + /** + * Query recent Ability Mission info. + * @param numMax The maximum number of entries to return in the list. The + * actual number returned may be smaller, depending on how many tasks the + * user has started and the maximum number the system can remember. + * @param falgs Information about what to return. May be any combination + * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}. + * + * @returns Returns the AbilityMissionInfo. + */ + std::vector QueryRecentAbilityMissionInfo(int numMax, int flags) const; + + /** + * Query running Ability Mission info. + * @param numMax The maximum number of entries to return in the list. The + * actual number returned may be smaller, depending on how many tasks the + * user has started and the maximum number the system can remember. + * + * @returns Returns the AbilityMissionInfo. + */ + std::vector QueryRunningAbilityMissionInfo(int numMax) const; + + /** + * Remove the specified mission from the stack by mission id + */ + void RemoveMissions(const std::vector &missionId); + + /** + * Clears user data of the application, which is equivalent to initializing the application. + * + * @param bundleName. + */ + int32_t ClearUpApplicationData(const std::string &bundleName); + + /** + * Obtains information about application processes that are running on the device. + * + * @returns Returns a list of running processes. + */ + std::vector GetAllRunningProcesses(); + + /** + * Kill the process immediately. + * + * @param bundleName. + * @return Returns ERR_OK on success, others on failure. + */ + int KillProcessesByBundleName(const std::string &bundleName); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_MANAGER_H diff --git a/frameworks/kits/appkit/native/app/include/ability_record_mgr.h b/frameworks/kits/appkit/native/app/include/ability_record_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..74ed2a2735b0cf6f6ace168084488ec5098cf157 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/ability_record_mgr.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_ABILITY_RECORD_MGR_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_RECORD_MGR_H + +#include +#include "iremote_object.h" +#include "ability_local_record.h" + +namespace OHOS { +namespace AppExecFwk { +class AbilityLocalRecord; +class AbilityRecordMgr { +public: + AbilityRecordMgr() = default; + ~AbilityRecordMgr() = default; + + /** + * @brief Set the eventRunner of abilitythread to the AbilityRecordMgr. + * + * @param eventRunner The runner of the abilitythread. + * + */ + void SetEventRunner(const std::shared_ptr &eventRunner); + + /** + * @brief Get the token witch is set to the AbilityRecordMgr. + * + * @return Returns the token which is set to the AbilityRecordMgr. + */ + sptr GetToken() const; + + /** + * @brief Set the token witch the app launched. + * + * @param token The token which the is launched by app. + */ + void SetToken(const sptr &token); + + /** + * @brief Save the token and abilityRecord to the AbilityRecordMgr. + * + * @param token The token which the abilityRecord belongs to. + * @param abilityRecord the abilityRecord witch contains the context info belong the the ability. + * + */ + void AddAbilityRecord(const sptr &token, const std::shared_ptr &abilityRecord); + + /** + * @brief Remove the abilityRecord by token. + * + * @param token The token which the abilityRecord belongs to. + * + */ + void RemoveAbilityRecord(const sptr &token); + + /** + * @brief Get the number of abilityRecords which the AbilityRecordMgr saved. + * + * @return Return the number of abilityRecords which the AbilityRecordMgr saved. + * + */ + int GetRecordCount() const; + + /** + * @brief Get the abilityRecord by token. + * + * @param token The token which the abilityRecord belongs to. + * + */ + std::shared_ptr GetAbilityItem(const sptr &token) const; + + /** + * @brief Get the all tokens in the abilityRecordMgr. + * + * @return all tokens in the abilityRecordMgr. + * + */ + std::vector> GetAllTokens(); + +private: + std::map, std::shared_ptr> abilityRecords_; + sptr tokens_; // we use ThreadLocal +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_RECORD_MGR_H diff --git a/frameworks/kits/appkit/native/app/include/app_loader.h b/frameworks/kits/appkit/native/app/include/app_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..b38c156103007baf5d88dd9210057f2e5580984c --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/app_loader.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_APPLICATION_LOADER_H +#define FOUNDATION_APPEXECFWK_OHOS_APPLICATION_LOADER_H + +#include "ohos_application.h" + +#include +#include +#include + +namespace OHOS { +namespace AppExecFwk { +using CreateApplication = std::function; + +class ApplicationLoader { +public: + /** + * @description: Gets the ApplicationLoader object to application register + * @param None + * @return ApplicationLoader + */ + static ApplicationLoader &GetInstance(); + + /** + * @description: Ddefault deconstructor + * @param None + * @return None + */ + ~ApplicationLoader() = default; + + /** + * @description: Gets the ApplicationLoader object to register application + * @param bundleName the bundle name of the application. + * @param createFunc constructor function of application class. + * @return None + */ + void RegisterApplication(const std::string &bundleName, const CreateApplication &createFunc); + + /** + * @description: Gets the {@link OHOSApplication} object + * @return Return {@link OHOSApplication} object which is registered by developer. + */ + OHOSApplication *GetApplicationByName(); + +private: + ApplicationLoader() = default; + ApplicationLoader(const ApplicationLoader &) = delete; + ApplicationLoader &operator=(const ApplicationLoader &) = delete; + ApplicationLoader(ApplicationLoader &&) = delete; + ApplicationLoader &operator=(ApplicationLoader &&) = delete; + + std::unordered_map applications_; +}; + +/** + * @brief Registers the class name of an {@link OHOSApplication} child class. + * + * After implementing your own {@link OHOSApplication} class, you should call this function so that the + * OHOSApplication management framework can create OHOSApplication instances when loading your + * OHOSApplication class. + * + * @param className Indicates the {@link OHOSApplication} class name to register. + */ +#define REGISTER_APPLICATION(bundleName, className) \ + __attribute__((constructor)) void REGISTER_APPLICATION##className() \ + { \ + ApplicationLoader::GetInstance().RegisterApplication( \ + #bundleName, []()->OHOSApplication * { return new (std::nothrow) className; }); \ + } +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_APPLICATION_LOADER_H diff --git a/frameworks/kits/appkit/native/app/include/application_context.h b/frameworks/kits/appkit/native/app/include/application_context.h new file mode 100755 index 0000000000000000000000000000000000000000..b54f3ba758aa16345e4bc06621727da79a032177 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/application_context.h @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_APPLICATION_CONTEXT_H +#define FOUNDATION_APPEXECFWK_OHOS_APPLICATION_CONTEXT_H + +#include "context_container.h" + +namespace OHOS { +namespace AppExecFwk { +class TaskDispatcherContext; +class ApplicationContext : public ContextContainer, public std::enable_shared_from_this { +public: + ApplicationContext(); + virtual ~ApplicationContext(); + + /** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ + const std::shared_ptr GetAbilityInfo() override; + + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE + * template is started. You can define the request code to identify the results returned by abilities. The value + * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE + * template. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const AAFwk::Want &want, int requestCode) override; + + /** + * @brief Starts a new ability with special ability start setting. + * + * @param want Indicates the Want containing information about the target ability to start. + * @param requestCode Indicates the request code returned after the ability is started. You can define the request + * code to identify the results returned by abilities. The value ranges from 0 to 65535. + * @param abilityStartSetting Indicates the special start setting used in starting ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) override; + + /** + * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult + * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode + * passed. + * + * @param requestCode Indicates the request code passed for starting the ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode TerminateAbility(int requestCode) override; + + /** + * @brief Destroys the current ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode TerminateAbility() override; + + /** + * @brief + * Destroys this Service ability if the number of times it has been started equals the number represented by the + * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service + * ability, except that this method helps you avoid destroying it if a client has requested a Service + * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it. + * + * @param startId Indicates the number of startup times of this Service ability passed to + * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is + * incremented by 1 every time this ability is started. For example, + * if this ability has been started for six times, the value of {@code startId} is {@code 6}. + * + * @return Returns {@code true} if the {@code startId} matches the number of startup times + * and this Service ability will be destroyed; returns {@code false} otherwise. + */ + bool TerminateAbilityResult(int startId) override; + + /** + * @brief Obtains the bundle name of the ability that called the current ability. + * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will + * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int, + * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned. + * + * @return Returns the bundle name of the calling ability; returns null if no calling ability is available. + */ + std::string GetCallingBundle() override; + + /** + * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. + * + * @param want Indicates the want containing information about the ability to connect + * + * @param conn Indicates the callback object when the target ability is connected. + * + * @return True means success and false means failure + */ + bool ConnectAbility(const Want &want, const sptr &conn) override; + + /** + * @brief Disconnects the current ability from an ability + * + * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection + * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode DisconnectAbility(const sptr &conn) override; + + /** + * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. + * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE + * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE + * template. The current ability itself can be destroyed by calling the terminateAbility() method. + * + * @param want Indicates the Want containing information about the ability to destroy. + * + * @return Returns true if the ability is destroyed successfully; returns false otherwise. + */ + bool StopAbility(const AAFwk::Want &want) override; + + /** + * @brief Starts multiple abilities. + * + * @param wants Indicates the Want containing information array about the target ability to start. + */ + void StartAbilities(const std::vector &wants) override; + + /** + * @brief Checks whether this ability is the first ability in a mission. + * + * @return Returns true is first in Mission. + */ + bool IsFirstInMission() override; + + /** + * @brief Obtains the unique ID of the mission containing this ability. + * + * @return Returns the unique mission ID. + */ + int GetMissionId() override; + + /** + * @brief Creates a parallel task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. + * + * @return Returns a parallel task dispatcher. + */ + std::shared_ptr CreateParallelTaskDispatcher( + const std::string &name, const TaskPriority &priority) override; + + /** + * @brief Creates a serial task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. + * + * @return Returns a serial task dispatcher. + */ + std::shared_ptr CreateSerialTaskDispatcher( + const std::string &name, const TaskPriority &priority) override; + + /** + * @brief Obtains a global task dispatcher with a specified priority. + * + * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. + * + * @return Returns a global task dispatcher. + */ + std::shared_ptr GetGlobalTaskDispatcher(const TaskPriority &priority) override; + +protected: + sptr GetToken() override; + std::shared_ptr taskDispatcherContext_ = nullptr; + std::mutex mutex_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_APPLICATION_CONTEXT_H diff --git a/frameworks/kits/appkit/native/app/include/application_env.h b/frameworks/kits/appkit/native/app/include/application_env.h new file mode 100644 index 0000000000000000000000000000000000000000..a2ef64534f4b869602c48f0b1ff45446123f2173 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/application_env.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_APPLICATION_ENV_H +#define OHOS_APPEXECFWK_APPLICATION_ENV_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/** + * @brief Obtains the bundle name of the application + * @param - + * @return Returns the pointer to the bundle name if the operation is successful; returns a null pointer otherwise. + */ +const char *GetBundleName(); + +/** + * @brief Obtains the source code path of this application. + * @param - + * @return Returns the pointer to the source code path of this application. + */ +const char *GetSrcPath(); + +/** + * @brief Obtains the data path of this application. + * @param - + * @return Returns the pointer to the data path of this application. + */ +const char *GetDataPath(); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + +#endif // OHOS_ABILITY_ENV_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/include/application_env_impl.h b/frameworks/kits/appkit/native/app/include/application_env_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..966852d2b2746f275d5cd20662d09e026d783e07 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/application_env_impl.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPLICATION_ENV_IMPL_H +#define OHOS_APPLICATION_ENV_IMPL_H + +#include +#include "nocopyable.h" + +/** + * L1 App_info define + */ +#include +#include + +typedef struct { + std::string bundleName; + std::string srcPath; + std::string dataPath; + bool isNativeApp; + std::list moduleNames; +} AppInfo; + +namespace OHOS { +namespace AppExecFwk { +struct ApplicationInfo; +class ApplicationEnvImpl : public NoCopyable { +public: + /** + * @brief Gets an instance of the applicationenvimpl class + * @param - + * @return instance indicates + */ + static ApplicationEnvImpl *GetInstance() + { + static ApplicationEnvImpl instance; + return &instance; + } + /** + * @brief destructor + * @param - + * @return - + */ + ~ApplicationEnvImpl() override = default; + + /** + * @brief Sets L1 information about the runtime environment of the application to which the + * ability belongs, including the bundle name, source code path, and data path. + * @param appInfo + * @return void + */ + void SetAppInfo(const AppInfo &appInfo); + + /** + * @brief Sets information about the runtime environment of the application to which the + * ability belongs, including the bundle name, source code path, and data path. + * @param appInfo + * @return void + */ + void SetAppInfo(const ApplicationInfo &appInfo); + + /** + * @brief Gets the bundlename of the application's runtime environment + * @param - + * @return bundleName + */ + const std::string &GetBundleName() const; + + /** + * @brief Gets the SrcPath of the application's runtime environment + * @param - + * @return SrcPath + */ + const std::string &GetSrcPath() const; + + /** + * @brief Gets the DataPath of the application's runtime environment + * @param - + * @return DataPath + */ + const std::string &GetDataPath() const; + +private: + ApplicationEnvImpl() = default; + + std::string bundleName_; + + std::string srcPath_; + + std::string dataPath_; + + static ApplicationEnvImpl instance_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPLICATION_ENV_IMPL_H diff --git a/frameworks/kits/appkit/native/app/include/application_impl.h b/frameworks/kits/appkit/native/app/include/application_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..fca3847d28da522c458ebd6c5d89d5d1288c3f9c --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/application_impl.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_APPLICATION_IMPL_H +#define FOUNDATION_APPEXECFWK_OHOS_APPLICATION_IMPL_H + +#include +#include +#include "application_info.h" +#include "profile.h" +#include "iremote_object.h" +#include "ability_local_record.h" + +namespace OHOS { +namespace AppExecFwk { +class OHOSApplication; +class AbilityLocalRecord; +class Configuration; +class ApplicationImpl { +public: + ApplicationImpl(); + virtual ~ApplicationImpl() = default; + + /** + * @brief Set the application to the ApplicationImpl. + * + * @param application The application which the mainthread launched. + * + */ + void SetApplication(const std::shared_ptr &application); + + /** + * @brief Schedule the application to the APP_STATE_READY state. + * + * @return Returns true if performAppReady is scheduled successfully; + * Returns false otherwise. + */ + bool PerformAppReady(); + + /** + * @brief Schedule the application to the APP_STATE_FOREGROUND state. + * + * @return Returns true if PerformForeground is scheduled successfully; + * Returns false otherwise. + */ + bool PerformForeground(); + + /** + * @brief Schedule the application to the APP_STATE_BACKGROUND state. + * + * @return Returns true if PerformBackground is scheduled successfully; + * Returns false otherwise. + */ + bool PerformBackground(); + + /** + * @brief Schedule the application to the APP_STATE_TERMINATED state. + * + * @return Returns true if PerformTerminate is scheduled successfully; + * Returns false otherwise. + */ + bool PerformTerminate(); + + /** + * @brief Schedule the application to the APP_STATE_TERMINATED state. + * + * @return Returns true if PerformTerminate is scheduled successfully; + * Returns false otherwise. + */ + void PerformTerminateStrong(); + + /** + * @brief Set the target state to application. + * + * @param state The target state of application. + * + */ + int SetState(int state); + + /** + * @brief Get the current state of application. + * + * @return Returns the current state of application. + * + */ + int GetState() const; + + /** + * @brief Set the RecordId to application. + * + * @param id recordId. + * + */ + void SetRecordId(int id); + + /** + * @brief Get the recordId of application. + * + * @return Returns the recordId of application. + * + */ + int GetRecordId() const; + + /** + * @brief System determines to trim the memory. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + * + */ + void PerformMemoryLevel(int level); + + /** + * @brief System determines to send the new config to application. + * + * @param config Indicates the updated configuration information. + * + */ + void PerformConfigurationUpdated(const Configuration &config); + +private: + enum { + APP_STATE_CREATE = 0, + APP_STATE_READY = 1, + APP_STATE_FOREGROUND = 2, + APP_STATE_BACKGROUND = 3, + APP_STATE_TERMINATED = 4 + }; + int curState_; + int recordId_; + std::shared_ptr application_ = nullptr; + + DISALLOW_COPY_AND_MOVE(ApplicationImpl); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_APPLICATION_IMPL_H diff --git a/frameworks/kits/appkit/native/app/include/context.h b/frameworks/kits/appkit/native/app/include/context.h new file mode 100755 index 0000000000000000000000000000000000000000..33d6614dd4c6ab9e1a8e7648aba30e08d3ce13b7 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/context.h @@ -0,0 +1,727 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_CONTEXT_H +#define FOUNDATION_APPEXECFWK_OHOS_CONTEXT_H + +#include + +#include "bundle_mgr_interface.h" +#include "ability_manager_interface.h" +#include "ability_info.h" +#include "process_info.h" +#include "resource_manager.h" +#include "dummy_hap_module_info.h" +#include "hap_module_info.h" +#include "task/task_priority.h" +#include "mission_information.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +using AbilityStartSetting = AAFwk::AbilityStartSetting; +// Request permissions for user +#define OHOS_REQUEST_PERMISSION_BUNDLENAME "com.ohos.systemui" +#define OHOS_REQUEST_PERMISSION_ABILITY_NAME "com.ohos.systemui.systemdialog.MainAbility" + +#define OHOS_REQUEST_PERMISSION_KEY "OHOS_REQUEST_PERMISSION_KEY" +#define OHOS_REQUEST_PERMISSIONS_LIST "OHOS_REQUEST_PERMISSIONS_LIST" +#define OHOS_REQUEST_PERMISSIONS_DES_LIST "OHOS_REQUEST_PERMISSIONS_DES_LIST" +#define OHOS_REQUEST_CALLER_BUNDLERNAME "OHOS_REQUEST_CALLER_BUNDLERNAME" + +#define OHOS_RESULT_PERMISSION_KEY "OHOS_RESULT_PERMISSION_KEY" +#define OHOS_RESULT_PERMISSIONS_LIST "OHOS_RESULT_PERMISSIONS_LIST" +#define OHOS_RESULT_PERMISSIONS_LIST_YES "OHOS_RESULT_PERMISSIONS_LIST_YES" +#define OHOS_RESULT_PERMISSIONS_LIST_NO "OHOS_RESULT_PERMISSIONS_LIST_NO" +#define OHOS_RESULT_CALLER_BUNDLERNAME "OHOS_RESULT_CALLER_BUNDLERNAME" + +#define OHOS_REQUEST_PERMISSION_VALUE 1 + +constexpr int INVALID_RESOURCE_VALUE = -1; // GetColor() Failed return Value + +class DataAbilityHelper; +class ContinuationConnector; +class IAbilityManager; +class TaskDispatcher; +class EventRunner; +class Context { +public: + Context() = default; + virtual ~Context() = default; + + /** + * The value 0 indicates that there is no restriction on creating contexts for applications. + */ + int MODE_PRIVATE = 0x0000; + + /** + * static final int CONTEXT_INCLUDE_CODE + * Indicates the flag used with createBundleContext(java.lang.String,int) for creating a Context + * object that includes the application code. + * + * The value is 0x00000001. + * + * @since 3 + */ + int CONTEXT_INCLUDE_CODE = 0x00000001; + + /** + * static final int CONTEXT_IGNORE_SECURITY + * Indicates the flag used with createBundleContext(java.lang.String,int) for creating a Context + * object that can always be loaded with all security restrictions ignored. + * + * The value is 0x00000002. + * + * @since 3 + */ + int CONTEXT_IGNORE_SECURITY = 0x00000002; + + /** + * static final int CONTEXT_RESTRICTED + * Indicates the flag used with createBundleContext(java.lang.String,int) for creating a Context + * object in which particular features may be disabled. + * + * The value is 0x00000004. + * + * @since 3 + */ + int CONTEXT_RESTRICTED = 0x00000004; + + int CONTEXT_RESOUCE_ONLY = 0x00000008; + + /** + * Called when getting the ProcessInfo + * + * @return ProcessInfo + */ + virtual std::shared_ptr GetProcessInfo() const = 0; + + /** + * @brief Obtains information about the current application. The returned application information includes basic + * information such as the application name and application permissions. + * + * @return Returns the ApplicationInfo for the current application. + */ + virtual std::shared_ptr GetApplicationInfo() const = 0; + + /** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ + virtual std::shared_ptr GetApplicationContext() const = 0; + + /** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ + virtual std::string GetBundleCodePath() = 0; + + /** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ + virtual const std::shared_ptr GetAbilityInfo() = 0; + + /** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ + virtual std::shared_ptr GetContext() = 0; + + /** + * @brief Obtains an IBundleMgr instance. + * You can use this instance to obtain information about the application bundle. + * + * @return Returns an IBundleMgr instance. + */ + virtual sptr GetBundleManager() const = 0; + + /** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ + virtual std::shared_ptr GetResourceManager() const = 0; + + /** + * @brief Deletes the specified private file associated with the application. + * + * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators. + * + * @return Returns true if the file is deleted successfully; returns false otherwise. + */ + virtual bool DeleteFile(const std::string &fileName) = 0; + + /** + * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. + * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE + * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE + * template. The current ability itself can be destroyed by calling the terminateAbility() method. + * + * @param want Indicates the Want containing information about the ability to destroy. + * + * @return Returns true if the ability is destroyed successfully; returns false otherwise. + */ + virtual bool StopAbility(const AAFwk::Want &want) = 0; + + /** + * @brief Obtains the application-specific cache directory on the device's internal storage. The system + * automatically deletes files from the cache directory if disk space is required elsewhere on the device. + * Older files are always deleted first. + * + * @return Returns the application-specific cache directory. + */ + virtual std::string GetCacheDir() = 0; + + /** + * @brief Obtains the application-specific code-cache directory on the device's internal storage. + * The system will delete any files stored in this location both when your specific application is upgraded, + * and when the entire platform is upgraded. + * + * @return Returns the application-specific code-cache directory. + */ + virtual std::string GetCodeCacheDir() = 0; + + /** + * @brief Obtains the local database path. + * If the local database path does not exist, the system creates one and returns the created path. + * + * @return Returns the local database file. + */ + virtual std::string GetDatabaseDir() = 0; + + /** + * @brief Obtains the absolute path where all private data files of this application are stored. + * + * @return Returns the absolute path storing all private data files of this application. + */ + virtual std::string GetDataDir() = 0; + + /** + * @brief Obtains the directory for storing custom data files of the application. + * You can use the returned File object to create and access files in this directory. The files + * can be accessible only by the current application. + * + * @param name Indicates the name of the directory to retrieve. This directory is created as part + * of your application data. + * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE. + * + * @return Returns a File object for the requested directory. + */ + virtual std::string GetDir(const std::string &name, int mode) = 0; + + /** + * @brief Obtains the absolute path to the application-specific cache directory + * on the primary external or shared storage device. + * + * @return Returns the absolute path to the application-specific cache directory on the external or + * shared storage device; returns null if the external or shared storage device is temporarily unavailable. + */ + virtual std::string GetExternalCacheDir() = 0; + + /** + * @brief Obtains the absolute path to the directory for storing files for the application on the + * primary external or shared storage device. + * + * @param type Indicates the type of the file directory to return + * + * @return Returns the absolute path to the application file directory on the external or shared storage + * device; returns null if the external or shared storage device is temporarily unavailable. + */ + virtual std::string GetExternalFilesDir(std::string &type) = 0; + + /** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ + virtual std::string GetFilesDir() = 0; + + /** + * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage. + * The returned path maybe changed if the application is moved to an adopted storage device. + * + * @return The path of the directory holding application files that will not be automatically backed up to remote + * storage. + */ + virtual std::string GetNoBackupFilesDir() = 0; + + /** + * @brief Checks whether the calling process for inter-process communication has the given permission. + * The calling process is not the current process. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + virtual int VerifyCallingPermission(const std::string &permission) = 0; + + /** + * @brief Checks whether the current process has the given permission. + * You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only + * if the current process does not have the specific permission. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + virtual int VerifySelfPermission(const std::string &permission) = 0; + + /** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ + virtual std::string GetBundleName() = 0; + + /** + * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability. + * + * @return Returns the path of the HAP containing this ability. + */ + virtual std::string GetBundleResourcePath() = 0; + + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE + * template is started. You can define the request code to identify the results returned by abilities. The value + * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE + * template. + * + * @return errCode ERR_OK on success, others on failure. + */ + virtual ErrCode StartAbility(const AAFwk::Want &want, int requestCode) = 0; + + /** + * @brief Remove permissions for all users who have access to specific permissions + * + * @param permission Indicates the permission to unauth. This parameter cannot be null. + * @param uri Indicates the URI to unauth. This parameter cannot be null. + * @param uid Indicates the UID of the unauth to check. + * + */ + virtual void UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) = 0; + + /** + * @brief Obtains an ability manager. + * The ability manager provides information about running processes and memory usage of an application. + * + * @return Returns an IAbilityManager instance. + */ + virtual sptr GetAbilityManager() = 0; + + /** + * @brief Obtains the type of this application. + * + * @return Returns system if this application is a system application; + * returns normal if it is released in OHOS AppGallery; + * returns other if it is released by a third-party vendor; + * returns an empty string if the query fails. + */ + virtual std::string GetAppType() = 0; + + /** + * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult + * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode + * passed. + * + * @param requestCode Indicates the request code passed for starting the ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + virtual ErrCode TerminateAbility(int requestCode) = 0; + + /** + * @brief Destroys the current ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + virtual ErrCode TerminateAbility() = 0; + + /** + * @brief Confirms with the permission management module to check whether a request prompt is required for granting + * a certain permission. You need to call the current method to check whether a prompt is required before calling + * requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, + * permission request will not be initiated. + * + * @param requestCode Indicates the permission to be queried. This parameter cannot be null. + * + * @return Returns true if the current application does not have the permission and the user does not turn off + * further requests; returns false if the current application already has the permission, the permission is rejected + * by the system, or the permission is denied by the user and the user has turned off further requests. + */ + virtual bool CanRequestPermission(const std::string &permission) = 0; + + /** + * @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has + * permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + virtual int VerifyCallingOrSelfPermission(const std::string &permission) = 0; + + /** + * @brief Query whether the application of the specified PID and UID has been granted a certain permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param pid Process id + * @param uid + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + virtual int VerifyPermission(const std::string &permission, int pid, int uid) = 0; + + /** + * @brief Obtains the distributed file path. + * If the distributed file path does not exist, the system creates one and returns the created path. This method is + * applicable only to the context of an ability rather than that of an application. + * + * @return Returns the distributed file. + */ + virtual std::string GetDistributedDir() = 0; + + /** + * @brief Sets the pattern of this Context based on the specified pattern ID. + * + * @param patternId Indicates the resource ID of the pattern to set. + */ + virtual void SetPattern(int patternId) = 0; + + /** + * @brief Obtains the Context object of this ability. + * + * @return Returns the Context object of this ability. + */ + virtual std::shared_ptr GetAbilityPackageContext() = 0; + + /** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ + virtual std::shared_ptr GetHapModuleInfo() = 0; + + /** + * @brief Obtains the name of the current process. + * + * @return Returns the current process name. + */ + virtual std::string GetProcessName() = 0; + + /** + * @brief Obtains the bundle name of the ability that called the current ability. + * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will + * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int, + * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned. + * + * @return Returns the bundle name of the calling ability; returns null if no calling ability is available. + */ + virtual std::string GetCallingBundle() = 0; + + /** + * @brief Requests certain permissions from the system. + * This method is called for permission request. This is an asynchronous method. When it is executed, + * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, + * String[], int[]) callback method. This code cannot be a negative number. + * + */ + virtual void RequestPermissionsFromUser(std::vector &permissions, int requestCode) = 0; + + /** + * @brief Starts a new ability with special ability start setting. + * + * @param want Indicates the Want containing information about the target ability to start. + * @param requestCode Indicates the request code returned after the ability is started. You can define the request + * code to identify the results returned by abilities. The value ranges from 0 to 65535. + * @param abilityStartSetting Indicates the special start setting used in starting ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + virtual ErrCode StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) = 0; + + /** + * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. + * + * @param want Indicates the want containing information about the ability to connect + * + * @param conn Indicates the callback object when the target ability is connected. + * + * @return True means success and false means failure + */ + virtual bool ConnectAbility(const Want &want, const sptr &conn) = 0; + + /** + * @brief Disconnects the current ability from an ability + * + * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection + * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. + */ + virtual ErrCode DisconnectAbility(const sptr &conn) = 0; + + /** + * @brief Obtains information about the caller of this ability. + * + * @return Returns the caller information. + */ + virtual Uri GetCaller() = 0; + + /** + * @brief Get the string of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string to get. + * + * @return Returns the string of this Context. + */ + virtual std::string GetString(int resId) = 0; + + /** + * @brief Get the string array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string array to get. + * + * @return Returns the string array of this Context. + */ + virtual std::vector GetStringArray(int resId) = 0; + + /** + * @brief Get the integer array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the integer array to get. + * + * @return Returns the integer array of this Context. + */ + virtual std::vector GetIntArray(int resId) = 0; + + /** + * @brief Obtains the theme of this Context. + * + * @return theme Returns the theme of this Context. + */ + virtual std::map GetTheme() = 0; + + /** + * @brief Sets the theme of this Context based on the specified theme ID. + * + * @param themeId Indicates the resource ID of the theme to set. + */ + virtual void SetTheme(int themeId) = 0; + + /** + * @brief Obtains the pattern of this Context. + * + * @return getPattern in interface Context + */ + virtual std::map GetPattern() = 0; + + /** + * @brief Get the color of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the color to get. + * + * @return Returns the color value of this Context. + */ + virtual int GetColor(int resId) = 0; + + /** + * @brief Obtains the theme id of this Context. + * + * @return int Returns the theme id of this Context. + */ + virtual int GetThemeId() = 0; + + /** + * @brief + * Destroys this Service ability if the number of times it has been started equals the number represented by the + * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service + * ability, except that this method helps you avoid destroying it if a client has requested a Service + * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it. + * + * @param startId Indicates the number of startup times of this Service ability passed to + * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is + * incremented by 1 every time this ability is started. For example, + * if this ability has been started for six times, the value of {@code startId} is {@code 6}. + * + * @return Returns {@code true} if the {@code startId} matches the number of startup times + * and this Service ability will be destroyed; returns {@code false} otherwise. + */ + virtual bool TerminateAbilityResult(int startId) = 0; + + /** + * @brief Obtains the current display orientation of this ability. + * + * @return Returns the current display orientation. + */ + virtual int GetDisplayOrientation() = 0; + + /** + * @brief Obtains the path storing the preference file of the application. + * If the preference file path does not exist, the system creates one and returns the created path. + * + * @return Returns the preference file path . + */ + virtual std::string GetPreferencesDir() = 0; + + /** + * @brief Set color mode + * + * @param the value of color mode. + */ + virtual void SetColorMode(int mode) = 0; + + /** + * @brief Obtains color mode. + * + * @return Returns the color mode value. + */ + virtual int GetColorMode() = 0; + + /** + * @brief Obtains the unique ID of the mission containing this ability. + * + * @return Returns the unique mission ID. + */ + virtual int GetMissionId() = 0; + + /** + * @brief Call this when your ability should be closed and the mission should be completely removed as a part of + * finishing the root ability of the mission. + */ + virtual void TerminateAndRemoveMission() = 0; + + /** + * @brief Starts multiple abilities. + * + * @param wants Indicates the Want containing information array about the target ability to start. + */ + virtual void StartAbilities(const std::vector &wants) = 0; + + /** + * @brief Checks whether this ability is the first ability in a mission. + * + * @return Returns true is first in Mission. + */ + virtual bool IsFirstInMission() = 0; + + /** + * @brief Obtains a task dispatcher that is bound to the UI thread. + * + * @return Returns the task dispatcher that is bound to the UI thread. + */ + virtual std::shared_ptr GetUITaskDispatcher() = 0; + + /** + * @brief Obtains a task dispatcher that is bound to the application main thread. + * + * @return Returns the task dispatcher that is bound to the application main thread. + */ + virtual std::shared_ptr GetMainTaskDispatcher() = 0; + + /** + * @brief Creates a parallel task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. + * + * @return Returns a parallel task dispatcher. + */ + virtual std::shared_ptr CreateParallelTaskDispatcher( + const std::string &name, const TaskPriority &priority) = 0; + + /** + * @brief Creates a serial task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. + * + * @return Returns a serial task dispatcher. + */ + virtual std::shared_ptr CreateSerialTaskDispatcher( + const std::string &name, const TaskPriority &priority) = 0; + + /** + * @brief Obtains a global task dispatcher with a specified priority. + * + * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. + * + * @return Returns a global task dispatcher. + */ + virtual std::shared_ptr GetGlobalTaskDispatcher(const TaskPriority &priority) = 0; + + /** + * @brief Requires that tasks associated with a given capability token be moved to the background + * + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * + * @return Returns true on success, others on failure. + */ + virtual bool MoveMissionToEnd(bool nonFirst) = 0; + + /** + * @brief Sets the application to start its ability in lock mission mode. + */ + virtual void LockMission() = 0; + + /** + * @brief Unlocks this ability by exiting the lock mission mode. + */ + virtual void UnlockMission() = 0; + + /** + * @brief Sets description information about the mission containing this ability. + * + * @param MissionInformation Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns true on success, others on failure. + */ + virtual bool SetMissionInformation(const MissionInformation &missionInformation) = 0; + + /** + * set lock screen white list + * + * @param isAllow Whether to allow lock screen. + * + */ + virtual void SetShowOnLockScreen(bool isAllow) = 0; + + friend DataAbilityHelper; + friend ContinuationConnector; + +protected: + virtual sptr GetToken() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_CONTEXT_H diff --git a/frameworks/kits/appkit/native/app/include/context_container.h b/frameworks/kits/appkit/native/app/include/context_container.h new file mode 100755 index 0000000000000000000000000000000000000000..034c1159c1ed503a7a420b3af3c826ebfae16f24 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/context_container.h @@ -0,0 +1,557 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_CONTEXT_CONTAINER_H +#define FOUNDATION_APPEXECFWK_OHOS_CONTEXT_CONTAINER_H + +#include "context_deal.h" + +namespace OHOS { +namespace AppExecFwk { +class ContextContainer : public Context { +public: + ContextContainer() = default; + virtual ~ContextContainer() = default; + + /** + * Attaches a Context object to the current ability. + * Generally, this method is called after Ability is loaded to provide the application context for the current + * ability. + * + * @param base Indicates a Context object. + */ + void AttachBaseContext(const std::shared_ptr &base); + + /** + * Called when getting the ProcessInfo + * + * @return ProcessInfo + */ + std::shared_ptr GetProcessInfo() const override; + + /** + * @brief Obtains information about the current application. The returned application information includes basic + * information such as the application name and application permissions. + * + * @return Returns the ApplicationInfo for the current application. + */ + std::shared_ptr GetApplicationInfo() const override; + + /** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ + std::shared_ptr GetApplicationContext() const override; + + /** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ + virtual std::string GetBundleCodePath() override; + + /** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ + virtual const std::shared_ptr GetAbilityInfo() override; + + /** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ + std::shared_ptr GetContext() override; + + /** + * @brief Obtains an IBundleMgr instance. + * You can use this instance to obtain information about the application bundle. + * + * @return Returns an IBundleMgr instance. + */ + sptr GetBundleManager() const override; + + /** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ + std::shared_ptr GetResourceManager() const override; + + /** + * @brief Deletes the specified private file associated with the application. + * + * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators. + * + * @return Returns true if the file is deleted successfully; returns false otherwise. + */ + bool DeleteFile(const std::string &fileName) override; + + /** + * @brief Obtains the application-specific cache directory on the device's internal storage. The system + * automatically deletes files from the cache directory if disk space is required elsewhere on the device. + * Older files are always deleted first. + * + * @return Returns the application-specific cache directory. + */ + std::string GetCacheDir() override; + + /** + * @brief Obtains the application-specific code-cache directory on the device's internal storage. + * The system will delete any files stored in this location both when your specific application is upgraded, + * and when the entire platform is upgraded. + * + * @return Returns the application-specific code-cache directory. + */ + std::string GetCodeCacheDir() override; + + /** + * @brief Obtains the local database path. + * If the local database path does not exist, the system creates one and returns the created path. + * + * @return Returns the local database file. + */ + std::string GetDatabaseDir() override; + + /** + * @brief Obtains the absolute path where all private data files of this application are stored. + * + * @return Returns the absolute path storing all private data files of this application. + */ + std::string GetDataDir() override; + + /** + * @brief Obtains the directory for storing custom data files of the application. + * You can use the returned File object to create and access files in this directory. The files + * can be accessible only by the current application. + * + * @param name Indicates the name of the directory to retrieve. This directory is created as part + * of your application data. + * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE. + * + * @return Returns a File object for the requested directory. + */ + std::string GetDir(const std::string &name, int mode) override; + + /** + * @brief Obtains the absolute path to the application-specific cache directory + * on the primary external or shared storage device. + * + * @return Returns the absolute path to the application-specific cache directory on the external or + * shared storage device; returns null if the external or shared storage device is temporarily unavailable. + */ + std::string GetExternalCacheDir() override; + + /** + * @brief Obtains the absolute path to the directory for storing files for the application on the + * primary external or shared storage device. + * + * @param type Indicates the type of the file directory to return + * + * @return Returns the absolute path to the application file directory on the external or shared storage + * device; returns null if the external or shared storage device is temporarily unavailable. + */ + std::string GetExternalFilesDir(std::string &type) override; + + /** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ + std::string GetFilesDir() override; + + /** + * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage. + * The returned path maybe changed if the application is moved to an adopted storage device. + * + * @return The path of the directory holding application files that will not be automatically backed up to remote + * storage. + */ + std::string GetNoBackupFilesDir() override; + + /** + * @brief Checks whether the calling process for inter-process communication has the given permission. + * The calling process is not the current process. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + int VerifyCallingPermission(const std::string &permission) override; + + /** + * @brief Checks whether the current process has the given permission. + * You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only + * if the current process does not have the specific permission. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + int VerifySelfPermission(const std::string &permission) override; + + /** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ + std::string GetBundleName() override; + + /** + * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability. + * + * @return Returns the path of the HAP containing this ability. + */ + std::string GetBundleResourcePath() override; + + /** + * @brief Remove permissions for all users who have access to specific permissions + * + * @param permission Indicates the permission to unauth. This parameter cannot be null. + * @param uri Indicates the URI to unauth. This parameter cannot be null. + * @param uid Indicates the UID of the unauth to check. + * + */ + void UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) override; + + /** + * @brief Obtains an ability manager. + * The ability manager provides information about running processes and memory usage of an application. + * + * @return Returns an IAbilityManager instance. + */ + sptr GetAbilityManager() override; + + /** + * @brief Obtains the type of this application. + * + * @return Returns system if this application is a system application; + * returns normal if it is released in OHOS AppGallery; + * returns other if it is released by a third-party vendor; + * returns an empty string if the query fails. + */ + std::string GetAppType() override; + + /** + * @brief Confirms with the permission management module to check whether a request prompt is required for granting + * a certain permission. You need to call the current method to check whether a prompt is required before calling + * requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, + * permission request will not be initiated. + * + * @param requestCode Indicates the permission to be queried. This parameter cannot be null. + * + * @return Returns true if the current application does not have the permission and the user does not turn off + * further requests; returns false if the current application already has the permission, the permission is rejected + * by the system, or the permission is denied by the user and the user has turned off further requests. + */ + bool CanRequestPermission(const std::string &permission) override; + + /** + * @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has + * permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + int VerifyCallingOrSelfPermission(const std::string &permission) override; + + /** + * @brief Query whether the application of the specified PID and UID has been granted a certain permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param pid Process id + * @param uid + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + int VerifyPermission(const std::string &permission, int pid, int uid) override; + + /** + * @brief Obtains the distributed file path. + * If the distributed file path does not exist, the system creates one and returns the created path. This method is + * applicable only to the context of an ability rather than that of an application. + * + * @return Returns the distributed file. + */ + std::string GetDistributedDir() override; + + /** + * @brief Sets the pattern of this Context based on the specified pattern ID. + * + * @param patternId Indicates the resource ID of the pattern to set. + */ + void SetPattern(int patternId) override; + + /** + * @brief Obtains the Context object of this ability. + * + * @return Returns the Context object of this ability. + */ + std::shared_ptr GetAbilityPackageContext() override; + + /** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ + std::shared_ptr GetHapModuleInfo() override; + + /** + * @brief Obtains the name of the current process. + * + * @return Returns the current process name. + */ + std::string GetProcessName() override; + + /** + * @brief Requests certain permissions from the system. + * This method is called for permission request. This is an asynchronous method. When it is executed, + * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, + * String[], int[]) callback method. This code cannot be a negative number. + * + */ + void RequestPermissionsFromUser(std::vector &permissions, int requestCode) override; + + /** + * @brief Creates a Context object for an application with the given bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * + * @param flag Indicates the flag for creating a Context object. It can be 0, any of + * the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY, + * CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction + * on creating contexts for applications. + * + * @return Returns a Context object created for the specified application. + */ + std::shared_ptr CreateBundleContext(std::string bundleName, int flag); + + /** + * @brief Obtains information about the caller of this ability. + * + * @return Returns the caller information. + */ + Uri GetCaller() override; + + /** + * @brief InitResourceManager + * + * @param bundleInfo BundleInfo + */ + void InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr &deal); + + /** + * @brief Get the string of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string to get. + * + * @return Returns the string of this Context. + */ + std::string GetString(int resId) override; + + /** + * @brief Get the string array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string array to get. + * + * @return Returns the string array of this Context. + */ + std::vector GetStringArray(int resId) override; + + /** + * @brief Get the integer array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the integer array to get. + * + * @return Returns the integer array of this Context. + */ + std::vector GetIntArray(int resId) override; + + /** + * @brief Obtains the theme of this Context. + * + * @return theme Returns the theme of this Context. + */ + std::map GetTheme() override; + + /** + * @brief Sets the theme of this Context based on the specified theme ID. + * + * @param themeId Indicates the resource ID of the theme to set. + */ + void SetTheme(int themeId) override; + + /** + * @brief Obtains the pattern of this Context. + * + * @return getPattern in interface Context + */ + std::map GetPattern() override; + + /** + * @brief Get the color of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the color to get. + * + * @return Returns the color value of this Context. + */ + int GetColor(int resId) override; + + /** + * @brief Obtains the theme id of this Context. + * + * @return int Returns the theme id of this Context. + */ + int GetThemeId() override; + + /** + * @brief Obtains the current display orientation of this ability. + * + * @return Returns the current display orientation. + */ + int GetDisplayOrientation() override; + + /** + * @brief Obtains the path storing the preference file of the application. + * If the preference file path does not exist, the system creates one and returns the created path. + * + * @return Returns the preference file path . + */ + std::string GetPreferencesDir() override; + + /** + * @brief Set color mode + * + * @param the value of color mode. + */ + void SetColorMode(int mode) override; + + /** + * @brief Obtains color mode. + * + * @return Returns the color mode value. + */ + int GetColorMode() override; + + /** + * @brief Obtains the unique ID of the mission containing this ability. + * + * @return Returns the unique mission ID. + */ + int GetMissionId() override; + + /** + * @brief Call this when your ability should be closed and the mission should be completely removed as a part of + * finishing the root ability of the mission. + */ + void TerminateAndRemoveMission() override; + + /** + * @brief Obtains a task dispatcher that is bound to the UI thread. + * + * @return Returns the task dispatcher that is bound to the UI thread. + */ + std::shared_ptr GetUITaskDispatcher() override; + + /** + * @brief Obtains a task dispatcher that is bound to the application main thread. + * + * @return Returns the task dispatcher that is bound to the application main thread. + */ + std::shared_ptr GetMainTaskDispatcher() override; + + /** + * @brief Creates a parallel task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. + * + * @return Returns a parallel task dispatcher. + */ + std::shared_ptr CreateParallelTaskDispatcher( + const std::string &name, const TaskPriority &priority) override; + + /** + * @brief Creates a serial task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. + * + * @return Returns a serial task dispatcher. + */ + std::shared_ptr CreateSerialTaskDispatcher( + const std::string &name, const TaskPriority &priority) override; + + /** + * @brief Obtains a global task dispatcher with a specified priority. + * + * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. + * + * @return Returns a global task dispatcher. + */ + std::shared_ptr GetGlobalTaskDispatcher(const TaskPriority &priority) override; + + /** + * @brief Requires that tasks associated with a given capability token be moved to the background + * + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * + * @return Returns true on success, others on failure. + */ + bool MoveMissionToEnd(bool nonFirst) override; + + /** + * @brief Sets the application to start its ability in lock mission mode. + */ + void LockMission() override; + + /** + * @brief Unlocks this ability by exiting the lock mission mode. + */ + void UnlockMission() override; + + /** + * @brief Sets description information about the mission containing this ability. + * + * @param MissionInformation Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns true on success, others on failure. + */ + bool SetMissionInformation(const MissionInformation &missionInformation) override; + + /** + * set lock screen white list + * + * @param isAllow is it allow wake up screen. + * + */ + void SetShowOnLockScreen(bool isAllow) override; + +private: + std::shared_ptr baseContext_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_CONTEXT_CONTAINER_H diff --git a/frameworks/kits/appkit/native/app/include/context_deal.h b/frameworks/kits/appkit/native/app/include/context_deal.h new file mode 100755 index 0000000000000000000000000000000000000000..4259664701092bcb6eff375ebbb6c77784e0adac --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/context_deal.h @@ -0,0 +1,765 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_CONTEXT_DEAL_H +#define FOUNDATION_APPEXECFWK_OHOS_CONTEXT_DEAL_H + +#include "context.h" +#include "profile.h" +#include "lifecycle_state_info.h" + +namespace OHOS { +namespace AppExecFwk { +class ContextDeal : public Context, public std::enable_shared_from_this { +public: + ContextDeal() = default; + virtual ~ContextDeal() = default; + + /** + * Called when getting the ProcessInfo + * + * @return ProcessInfo + */ + std::shared_ptr GetProcessInfo() const override; + + /** + * Called when setting the ProcessInfo + * + * @param info ProcessInfo instance + */ + void SetProcessInfo(const std::shared_ptr &info); + + /** + * @brief Obtains information about the current application. The returned application information includes basic + * information such as the application name and application permissions. + * + * @return Returns the ApplicationInfo for the current application. + */ + std::shared_ptr GetApplicationInfo() const override; + + /** + * @brief Set ApplicationInfo + * + * @param info ApplicationInfo instance. + */ + void SetApplicationInfo(const std::shared_ptr &info); + + /** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ + std::shared_ptr GetApplicationContext() const override; + + /** + * @brief Set ApplicationContext + * + * @param context ApplicationContext instance. + */ + void SetApplicationContext(const std::shared_ptr &context); + + /** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ + std::string GetBundleCodePath() override; + + /** + * @brief SetBundleCodePath + * + * @param Returns string path + */ + void SetBundleCodePath(std::string &path); + + /** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ + const std::shared_ptr GetAbilityInfo() override; + + /** + * @brief Set AbilityInfo + * + * @param info AbilityInfo instance. + */ + void SetAbilityInfo(const std::shared_ptr &info); + + /** + * @brief Obtains the Context object of the ability. + * + * @return Returns the Context object of the ability. + */ + std::shared_ptr GetContext() override; + + /** + * @brief Set Ability context + * + * @param context Ability object + */ + void SetContext(const std::shared_ptr &context); + + /** + * @brief Obtains an IBundleMgr instance. + * You can use this instance to obtain information about the application bundle. + * + * @return Returns an IBundleMgr instance. + */ + sptr GetBundleManager() const override; + + /** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ + std::shared_ptr GetResourceManager() const override; + + /** + * @brief Set Profile instance. + * + * @param Profile instance. + */ + void SetProfile(const std::shared_ptr &profile); + + /** + * @brief Obtains an Profile instance. + * + * @return Returns an Profile instance. + */ + std::shared_ptr GetProfile() const; + + /** + * @brief Deletes the specified private file associated with the application. + * + * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators. + * + * @return Returns true if the file is deleted successfully; returns false otherwise. + */ + bool DeleteFile(const std::string &fileName) override; + + /** + * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. + * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE + * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE + * template. The current ability itself can be destroyed by calling the terminateAbility() method. + * + * @param want Indicates the Want containing information about the ability to destroy. + * + * @return Returns true if the ability is destroyed successfully; returns false otherwise. + */ + bool StopAbility(const AAFwk::Want &want) override; + + /** + * @brief Obtains the application-specific cache directory on the device's internal storage. The system + * automatically deletes files from the cache directory if disk space is required elsewhere on the device. + * Older files are always deleted first. + * + * @return Returns the application-specific cache directory. + */ + std::string GetCacheDir() override; + + /** + * @brief Obtains the application-specific code-cache directory on the device's internal storage. + * The system will delete any files stored in this location both when your specific application is upgraded, + * and when the entire platform is upgraded. + * + * @return Returns the application-specific code-cache directory. + */ + std::string GetCodeCacheDir() override; + + /** + * @brief Obtains the local database path. + * If the local database path does not exist, the system creates one and returns the created path. + * + * @return Returns the local database file. + */ + std::string GetDatabaseDir() override; + + /** + * @brief Obtains the absolute path where all private data files of this application are stored. + * + * @return Returns the absolute path storing all private data files of this application. + */ + std::string GetDataDir() override; + + /** + * @brief Obtains the directory for storing custom data files of the application. + * You can use the returned File object to create and access files in this directory. The files + * can be accessible only by the current application. + * + * @param name Indicates the name of the directory to retrieve. This directory is created as part + * of your application data. + * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE. + * + * @return Returns a File object for the requested directory. + */ + std::string GetDir(const std::string &name, int mode) override; + + /** + * @brief Obtains the absolute path to the application-specific cache directory + * on the primary external or shared storage device. + * + * @return Returns the absolute path to the application-specific cache directory on the external or + * shared storage device; returns null if the external or shared storage device is temporarily unavailable. + */ + std::string GetExternalCacheDir() override; + + /** + * @brief Obtains the absolute path to the directory for storing files for the application on the + * primary external or shared storage device. + * + * @param type Indicates the type of the file directory to return + * + * @return Returns the absolute path to the application file directory on the external or shared storage + * device; returns null if the external or shared storage device is temporarily unavailable. + */ + std::string GetExternalFilesDir(std::string &type) override; + + /** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ + std::string GetFilesDir() override; + + /** + * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage. + * The returned path maybe changed if the application is moved to an adopted storage device. + * + * @return The path of the directory holding application files that will not be automatically backed up to remote + * storage. + */ + std::string GetNoBackupFilesDir() override; + + /** + * @brief Checks whether the calling process for inter-process communication has the given permission. + * The calling process is not the current process. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + int VerifyCallingPermission(const std::string &permission) override; + + /** + * @brief Checks whether the current process has the given permission. + * You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only + * if the current process does not have the specific permission. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + int VerifySelfPermission(const std::string &permission) override; + + /** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ + std::string GetBundleName() override; + + /** + * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability. + * + * @return Returns the path of the HAP containing this ability. + */ + std::string GetBundleResourcePath() override; + + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE + * template is started. You can define the request code to identify the results returned by abilities. The value + * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE + * template. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const AAFwk::Want &want, int requestCode) override; + + /** + * @brief Remove permissions for all users who have access to specific permissions + * + * @param permission Indicates the permission to unauth. This parameter cannot be null. + * @param uri Indicates the URI to unauth. This parameter cannot be null. + * @param uid Indicates the UID of the unauth to check. + * + */ + void UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) override; + + /** + * @brief Obtains an ability manager. + * The ability manager provides information about running processes and memory usage of an application. + * + * @return Returns an IAbilityManager instance. + */ + sptr GetAbilityManager() override; + + /** + * @brief Obtains the type of this application. + * + * @return Returns system if this application is a system application; + * returns normal if it is released in OHOS AppGallery; + * returns other if it is released by a third-party vendor; + * returns an empty string if the query fails. + */ + std::string GetAppType() override; + + /** + * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult + * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode + * passed. + * + * @param requestCode Indicates the request code passed for starting the ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode TerminateAbility(int requestCode) override; + + /** + * @brief Confirms with the permission management module to check whether a request prompt is required for granting + * a certain permission. You need to call the current method to check whether a prompt is required before calling + * requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, + * permission request will not be initiated. + * + * @param requestCode Indicates the permission to be queried. This parameter cannot be null. + * + * @return Returns true if the current application does not have the permission and the user does not turn off + * further requests; returns false if the current application already has the permission, the permission is rejected + * by the system, or the permission is denied by the user and the user has turned off further requests. + */ + bool CanRequestPermission(const std::string &permission) override; + + /** + * @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has + * permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + virtual int VerifyCallingOrSelfPermission(const std::string &permission) override; + + /** + * @brief Query whether the application of the specified PID and UID has been granted a certain permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param pid Process id + * @param uid + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ + virtual int VerifyPermission(const std::string &permission, int pid, int uid) override; + + /** + * @brief Obtains the distributed file path. + * If the distributed file path does not exist, the system creates one and returns the created path. This method is + * applicable only to the context of an ability rather than that of an application. + * + * @return Returns the distributed file. + */ + std::string GetDistributedDir() override; + + /** + * @brief Sets the pattern of this Context based on the specified pattern ID. + * + * @param patternId Indicates the resource ID of the pattern to set. + */ + void SetPattern(int patternId) override; + + /** + * @brief Obtains the Context object of this ability. + * + * @return Returns the Context object of this ability. + */ + std::shared_ptr GetAbilityPackageContext() override; + + /** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ + std::shared_ptr GetHapModuleInfo() override; + + /** + * @brief Obtains the name of the current process. + * + * @return Returns the current process name. + */ + std::string GetProcessName() override; + + /** + * @brief Obtains the bundle name of the ability that called the current ability. + * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will + * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int, + * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned. + * + * @return Returns the bundle name of the calling ability; returns null if no calling ability is available. + */ + std::string GetCallingBundle() override; + + /** + * @brief Requests certain permissions from the system. + * This method is called for permission request. This is an asynchronous method. When it is executed, + * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, + * String[], int[]) callback method. This code cannot be a negative number. + * + */ + void RequestPermissionsFromUser(std::vector &permissions, int requestCode) override; + + /** + * @brief Starts a new ability with special ability start setting. + * + * @param want Indicates the Want containing information about the target ability to start. + * @param requestCode Indicates the request code returned after the ability is started. You can define the request + * code to identify the results returned by abilities. The value ranges from 0 to 65535. + * @param abilityStartSetting Indicates the special start setting used in starting ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) override; + + /** + * @brief Destroys the current ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode TerminateAbility() override; + + /** + * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. + * + * @param want Indicates the want containing information about the ability to connect + * + * @param conn Indicates the callback object when the target ability is connected. + * + * @return True means success and false means failure + */ + bool ConnectAbility(const Want &want, const sptr &conn) override; + + /** + * @brief Disconnects the current ability from an ability + * + * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection + * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode DisconnectAbility(const sptr &conn) override; + + /** + * @brief init the ResourceManager for ContextDeal. + * + * @param the ResourceManager has been inited. + * + */ + void initResourceManager(const std::shared_ptr &resourceManager); + + /** + * @brief Obtains information about the caller of this ability. + * + * @return Returns the caller information. + */ + Uri GetCaller() override; + + /** + * @brief SerUriString + */ + void SerUriString(const std::string &uri); + + /** + * @brief Get the string of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string to get. + * + * @return Returns the string of this Context. + */ + std::string GetString(int resId) override; + + /** + * @brief Get the string array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string array to get. + * + * @return Returns the string array of this Context. + */ + std::vector GetStringArray(int resId) override; + + /** + * @brief Get the integer array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the integer array to get. + * + * @return Returns the integer array of this Context. + */ + std::vector GetIntArray(int resId) override; + + /** + * @brief Obtains the theme of this Context. + * + * @return theme Returns the theme of this Context. + */ + std::map GetTheme() override; + + /** + * @brief Sets the theme of this Context based on the specified theme ID. + * + * @param themeId Indicates the resource ID of the theme to set. + */ + void SetTheme(int themeId) override; + + /** + * @brief Obtains the pattern of this Context. + * + * @return getPattern in interface Context + */ + std::map GetPattern() override; + + /** + * @brief Get the color of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the color to get. + * + * @return Returns the color value of this Context. + */ + int GetColor(int resId) override; + + /** + * @brief Obtains the theme id of this Context. + * + * @return int Returns the theme id of this Context. + */ + int GetThemeId() override; + + /** + * @brief + * Destroys this Service ability if the number of times it has been started equals the number represented by the + * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service + * ability, except that this method helps you avoid destroying it if a client has requested a Service + * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it. + * + * @param startId Indicates the number of startup times of this Service ability passed to + * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is + * incremented by 1 every time this ability is started. For example, + * if this ability has been started for six times, the value of {@code startId} is {@code 6}. + * + * @return Returns {@code true} if the {@code startId} matches the number of startup times + * and this Service ability will be destroyed; returns {@code false} otherwise. + */ + bool TerminateAbilityResult(int startId) override; + + /** + * @brief Obtains the current display orientation of this ability. + * + * @return Returns the current display orientation. + */ + int GetDisplayOrientation() override; + + /** + * @brief Obtains the path storing the preference file of the application. + * If the preference file path does not exist, the system creates one and returns the created path. + * + * @return Returns the preference file path . + */ + std::string GetPreferencesDir() override; + + /** + * @brief Set color mode + * + * @param the value of color mode. + */ + void SetColorMode(int mode) override; + + /** + * @brief Obtains color mode. + * + * @return Returns the color mode value. + */ + int GetColorMode() override; + + /** + * @brief Set the LifeCycleStateInfo to the deal. + * + * @param info the info to set. + */ + void SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info); + + /** + * @brief Obtains the unique ID of the mission containing this ability. + * + * @return Returns the unique mission ID. + */ + int GetMissionId() override; + + /** + * @brief Call this when your ability should be closed and the mission should be completely removed as a part of + * finishing the root ability of the mission. + */ + void TerminateAndRemoveMission() override; + + /** + * @brief Starts multiple abilities. + * + * @param wants Indicates the Want containing information array about the target ability to start. + */ + void StartAbilities(const std::vector &wants) override; + + /** + * @brief Checks whether this ability is the first ability in a mission. + * + * @return Returns true is first in Mission. + */ + bool IsFirstInMission() override; + + /** + * @brief Obtains a task dispatcher that is bound to the UI thread. + * + * @return Returns the task dispatcher that is bound to the UI thread. + */ + std::shared_ptr GetUITaskDispatcher() final override; + + /** + * @brief Obtains a task dispatcher that is bound to the application main thread. + * + * @return Returns the task dispatcher that is bound to the application main thread. + */ + std::shared_ptr GetMainTaskDispatcher() override; + + /** + * @brief Creates a parallel task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. + * + * @return Returns a parallel task dispatcher. + */ + std::shared_ptr CreateParallelTaskDispatcher( + const std::string &name, const TaskPriority &priority) override; + + /** + * @brief Creates a serial task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. + * + * @return Returns a serial task dispatcher. + */ + std::shared_ptr CreateSerialTaskDispatcher( + const std::string &name, const TaskPriority &priority) override; + + /** + * @brief Obtains a global task dispatcher with a specified priority. + * + * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. + * + * @return Returns a global task dispatcher. + */ + std::shared_ptr GetGlobalTaskDispatcher(const TaskPriority &priority) override; + /** + * @brief Requires that tasks associated with a given capability token be moved to the background + * + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * + * @return Returns true on success, others on failure. + */ + bool MoveMissionToEnd(bool nonFirst) override; + + /** + * @brief Sets the application to start its ability in lock mission mode. + */ + void LockMission() override; + + /** + * @brief Unlocks this ability by exiting the lock mission mode. + */ + void UnlockMission() override; + + /** + * @brief Sets description information about the mission containing this ability. + * + * @param MissionInformation Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns true on success, others on failure. + */ + bool SetMissionInformation(const MissionInformation &missionInformation) override; + + /** + * set lock screen white list + * + * @param isAllow is it allow wake up screen. + * + */ + void SetShowOnLockScreen(bool isAllow) override; + + /** + * @brief Set EventRunner for main thread. + * + * @param runner The EventRunner. + */ + void SetRunner(const std::shared_ptr &runner); + + /** + * @brief Obtains the lifecycle state info. + * + * @return Returns the lifecycle state info. + */ + AAFwk::LifeCycleStateInfo GetLifeCycleStateInfo() const; + +public: + static const std::string CONTEXT_DEAL_FILE_SEPARATOR; + static const std::string CONTEXT_DEAL_CODE_CACHE; + static const std::string CONTEXT_DEAL_Files; + static const std::string CONTEXT_DEAL_NO_BACKUP_Files; + static const std::string CONTEXT_DEAL_DIRNAME; + +protected: + sptr GetToken() override; + bool HapModuleInfoRequestInit(); + +private: + std::shared_ptr processInfo_ = nullptr; + std::shared_ptr applicationInfo_ = nullptr; + std::shared_ptr abilityInfo_ = nullptr; + std::shared_ptr profile_ = nullptr; + std::shared_ptr appContext_ = nullptr; + std::shared_ptr abilityContext_ = nullptr; + std::shared_ptr resourceManager_ = nullptr; + std::string path_ = ""; + std::string uriString_ = ""; + std::string preferenceDir_ = ""; + std::map pattern_; + std::map theme_; + AAFwk::LifeCycleStateInfo lifeCycleStateInfo_; + std::shared_ptr mainTaskDispatcher_; + std::shared_ptr mainEventRunner_; + std::shared_ptr hapModuleInfoLocal_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_CONTEXT_DEAL_H diff --git a/frameworks/kits/appkit/native/app/include/dummy_hap_module_info.h b/frameworks/kits/appkit/native/app/include/dummy_hap_module_info.h new file mode 100644 index 0000000000000000000000000000000000000000..3119ea62ad003957e668390c1bcda983afe2561b --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/dummy_hap_module_info.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_HAPMODULEINFO_H +#define FOUNDATION_APPEXECFWK_OHOS_HAPMODULEINFO_H + +namespace OHOS { +namespace AppExecFwk { +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_HAPMODULEINFO_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/include/element_callback.h b/frameworks/kits/appkit/native/app/include/element_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..34353c96eed055cdbaf863aa44d5c0662b1ca235 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/element_callback.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_ELEMENTS_CALLBACK_H +#define FOUNDATION_APPEXECFWK_OHOS_ELEMENTS_CALLBACK_H + +#include "configuration.h" + +namespace OHOS { +namespace AppExecFwk { +class ElementsCallback { +public: + ElementsCallback() = default; + virtual ~ElementsCallback() = default; + + /** + * + * Called when the system configuration of the device changes. + * + * @param config Indicates the new Configuration object. + * @param ability Indicates the new Ability object. + */ + virtual void OnConfigurationUpdated(const std::shared_ptr &ability, const Configuration &config) = 0; + + /** + * + * Will be called when the system has determined to trim the memory + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + */ + virtual void OnMemoryLevel(int level) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_ELEMENTS_CALLBACK_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/include/group.h b/frameworks/kits/appkit/native/app/include/group.h new file mode 100644 index 0000000000000000000000000000000000000000..897596a70cc6ab3ce2544a332abe5a5e2524afab --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/group.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_GROUP_H +#define OHOS_APP_DISPATCHER_GROUP_H + +namespace OHOS { +namespace AppExecFwk { +/** + * Defines a group, which stands for a set of tasks semantically. + *

Multiple tasks can be associated with a group so that they can be considered as a whole. + *

This interface must be used with methods in {@link ohos.app.dispatcher.TaskDispatcher TaskDispatcher}, + * such as {@link ohos.app.dispatcher.TaskDispatcher#createDispatchGroup createDispatchGroup}, + * {@link ohos.app.dispatcher.TaskDispatcher#asyncGroupDispatch asyncGroupDispatch}, + * {@link ohos.app.dispatcher.TaskDispatcher#groupDispatchWait groupDispatchWait}, + * and {@link ohos.app.dispatcher.TaskDispatcher#groupDispatchNotify groupDispatchNotify}. + * @since 1 + */ +class Group {}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/frameworks/kits/appkit/native/app/include/main_thread.h b/frameworks/kits/appkit/native/app/include/main_thread.h new file mode 100644 index 0000000000000000000000000000000000000000..4520c6a637fdcbaf43f7577afd95ac0aea34c1e5 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/main_thread.h @@ -0,0 +1,520 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_MAIN_THREAD_H +#define FOUNDATION_APPEXECFWK_MAIN_THREAD_H + +#include +#include +#include "event_handler.h" +#include "inner_event.h" +#include "app_scheduler_host.h" +#include "app_mgr_interface.h" +#include "ability_record_mgr.h" +#include "application_impl.h" +#include "resource_manager.h" +#include "foundation/aafwk/standard/interfaces/innerkits/runtime/include/runtime.h" +#include "ohos/aafwk/base/ipc_singleton.h" +#include "watchdog.h" +#define ABILITY_LIBRARY_LOADER + +class Runtime; +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::Global; +using OHOS::AbilityRuntime::Runtime; +enum class MainThreadState { INIT, ATTACH, READY, RUNNING }; +struct BundleInfo; +class ContextDeal; +// class Global::Resource::ResourceManager; +class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { +public: + /** + * + * @brief Notify the AppMgrDeathRecipient that the remote is dead. + * + * @param remote The remote which is dead. + */ + virtual void OnRemoteDied(const wptr &remote) override; + AppMgrDeathRecipient() = default; + ~AppMgrDeathRecipient() override = default; +}; + +class MainThread : public AppSchedulerHost { + DECLARE_DELAYED_IPCSINGLETON(MainThread); + +public: + /** + * + * @brief Get the current MainThreadState. + * + * @return Returns the current MainThreadState. + */ + MainThreadState GetMainThreadState() const; + + /** + * + * @brief Get the runner state of mainthread. + * + * @return Returns the runner state of mainthread. + */ + bool GetRunnerStarted() const; + + /** + * + * @brief Get the newThreadId. + * + * @return Returns the newThreadId. + */ + int GetNewThreadId(); + + /** + * + * @brief Get the application. + * + * @return Returns the application. + */ + std::shared_ptr GetApplication() const; + + /** + * + * @brief Get the applicationInfo. + * + * @return Returns the applicationInfo. + */ + std::shared_ptr GetApplicationInfo() const; + + /** + * + * @brief Get the applicationImpl. + * + * @return Returns the applicationImpl. + */ + std::shared_ptr GetApplicationImpl(); + + /** + * + * @brief Get the eventHandler of mainthread. + * + * @return Returns the eventHandler of mainthread. + */ + std::shared_ptr GetMainHandler() const; + + /** + * + * @brief Schedule the foreground lifecycle of application. + * + */ + void ScheduleForegroundApplication() override; + + /** + * + * @brief Schedule the background lifecycle of application. + * + */ + void ScheduleBackgroundApplication() override; + + /** + * + * @brief Schedule the terminate lifecycle of application. + * + */ + void ScheduleTerminateApplication() override; + + /** + * + * @brief Shrink the memory which used by application. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + */ + void ScheduleShrinkMemory(const int level) override; + + /** + * + * @brief Low the memory which used by application. + * + */ + void ScheduleLowMemory() override; + + /** + * + * @brief Launch the application. + * + * @param data The launchdata of the application witch launced. + * + */ + void ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config) override; + + /** + * Notify application to launch ability stage. + * + * @param The resident process data value. + */ + void ScheduleAbilityStage(const HapModuleInfo &abilityStage) override; + + /** + * + * @brief launch the application. + * + * @param info The launchdata of the application witch launced. + * @param token The launchdata of the application witch launced. + * + */ + void ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) override; + + /** + * + * @brief clean the ability by token. + * + * @param token The token belong to the ability which want to be cleaned. + * + */ + void ScheduleCleanAbility(const sptr &token) override; + + /** + * + * @brief send the new profile. + * + * @param profile The updated profile. + * + */ + void ScheduleProfileChanged(const Profile &profile) override; + + /** + * + * @brief send the new config to the application. + * + * @param config The updated config. + * + */ + void ScheduleConfigurationUpdated(const Configuration &config) override; + + /** + * + * @brief Starts the mainthread. + * + */ + static void Start(); + + /** + * + * @brief Schedule the application process exit safely. + * + */ + void ScheduleProcessSecurityExit() override; + + void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) override; + + /** + * @brief Finish user test. + * @param msg user test message. + * @param resultCode user test result Code. + * @param bundleName user test bundleName. + * @param observer test observer callback. + * + * @return Returns ERR_OK on success, others on failure. + */ + int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer); + +private: + /** + * + * @brief Terminate the application but don't notify ams. + * + */ + void HandleTerminateApplicationLocal(); + + void HandleScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName); + + /** + * + * @brief Schedule the application process exit safely. + * + */ + void HandleProcessSecurityExit(); + + /** + * + * @brief Clean the ability but don't notify ams. + * + * @param token The token which belongs to the ability launched. + * + */ + void HandleCleanAbilityLocal(const sptr &token); + + /** + * + * @brief Launch the application. + * + * @param appLaunchData The launchdata of the application witch launced. + * + */ + void HandleLaunchApplication(const AppLaunchData &appLaunchData, const Configuration &config); + + /** + * + * @brief Launch the application. + * + * @param appLaunchData The launchdata of the application witch launced. + * + */ + void HandleAbilityStage(const HapModuleInfo &abilityStage); + + /** + * + * @brief Launch the ability. + * + * @param abilityRecord The abilityRecord which belongs to the ability launched. + * + */ + void HandleLaunchAbility(const std::shared_ptr &abilityRecord); + + /** + * + * @brief Clean the ability. + * + * @param token The token which belongs to the ability launched. + * + */ + void HandleCleanAbility(const sptr &token); + + /** + * + * @brief Foreground the application. + * + */ + void HandleForegroundApplication(); + + /** + * + * @brief Background the application. + * + */ + void HandleBackgroundApplication(); + + /** + * + * @brief Terminate the application. + * + */ + void HandleTerminateApplication(); + + /** + * + * @brief Shrink the memory which used by application. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + * + */ + void HandleShrinkMemory(const int level); + + /** + * + * @brief send the new config to the application. + * + * @param config The updated config. + * + */ + void HandleConfigurationUpdated(const Configuration &config); + + /** + * + * @brief remove the deathRecipient from appMgr. + * + */ + void RemoveAppMgrDeathRecipient(); + + /** + * + * @brief Attach the mainthread to the AppMgr. + * + */ + void Attach(); + + /** + * + * @brief Set the runner state of mainthread. + * + * @param runnerStart whether the runner is started. + */ + void SetRunnerStarted(bool runnerStart); + + /** + * + * @brief Connect the mainthread to the AppMgr. + * + */ + bool ConnectToAppMgr(); + + /** + * + * @brief Check whether the appLaunchData is legal. + * + * @param appLaunchData The appLaunchData should be checked. + * + * @return if the appLaunchData is legal, return true. else return false. + */ + bool CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) const; + + /** + * + * @brief Check whether the record is legal. + * + * @param record The record should be checked. + * + * @return if the record is legal, return true. else return false. + */ + bool CheckAbilityItem(const std::shared_ptr &record) const; + + /** + * + * @brief Init the mainthread. + * + * @param runner the runner belong to the mainthread. + * + */ + void Init(const std::shared_ptr &runner, const std::shared_ptr &watchDogRunner); + + /** + * + * @brief Task in event handler timeout detected. + * + */ + void TaskTimeoutDetected(); + + /** + * + * @brief The handle of application not response process. + * + * @param sigMessage Recieve the sig message. + * + */ + static void HandleANRProcess(int sigMessage); + + /** + * + * @brief Check whether the OHOSApplication is ready. + * + * @return if the OHOSApplication is ready, return true. else return false. + * + */ + bool IsApplicationReady() const; + + void LoadAndRegisterExtension(const std::string &libName, const std::string &extensionName, + const std::unique_ptr& runtime); + + /** + * + * @brief Ability Delegator Prepare. + * + * @param UserTestRecord User Test info. + * + */ + bool AbilityDelegatorPrepare(const UserTestRecord &record); + + class MainHandler : public EventHandler { + public: + MainHandler(const std::shared_ptr &runner, const sptr &thread); + virtual ~MainHandler() = default; + + /** + * + * @brief Process the event. + * + * @param event the event want to be processed. + * + */ + void ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event) override; + + private: + sptr mainThreadObj_ = nullptr; + }; + + bool isRunnerStarted_ = false; + int newThreadId_ = -1; + std::shared_ptr appProfile_ = nullptr; + std::shared_ptr applicationInfo_ = nullptr; + std::shared_ptr processInfo_ = nullptr; + std::shared_ptr application_ = nullptr; + std::shared_ptr applicationImpl_ = nullptr; + std::shared_ptr mainHandler_ = nullptr; + std::shared_ptr watchDogHandler_ = nullptr; + std::shared_ptr abilityRecordMgr_ = nullptr; + MainThreadState mainThreadState_ = MainThreadState::INIT; + sptr appMgr_ = nullptr; // appMgrService Handler + sptr deathRecipient_ = nullptr; + std::string aceApplicationName_ = "AceApplication"; + std::string pathSeparator_ = "/"; + std::string abilityLibraryType_ = ".so"; + static std::shared_ptr applicationForAnr_; + +#ifdef ABILITY_LIBRARY_LOADER + /** + * + * @brief Load the ability library. + * + * @param libraryPaths the library paths. + * + */ + void LoadAbilityLibrary(const std::vector &libraryPaths); + + void LoadAppLibrary(); + + /** + * + * @brief Close the ability library loaded. + * + */ + void CloseAbilityLibrary(); + + /** + * + * @brief Scan the dir ability library loaded. + * + * @param dirPath the the path should be scan. + * + */ + bool ScanDir(const std::string &dirPath); + + /** + * + * @brief Check the fileType. + * + * @param fileName The fileName of the lib. + * @param extensionName The extensionName of the lib. + * + * @return if the FileType is legal, return true. else return false. + * + */ + bool CheckFileType(const std::string &fileName, const std::string &extensionName); + + bool InitCreate(std::shared_ptr &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo, + Profile &appProfile); + bool CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData); + bool InitResourceManager(std::shared_ptr &resourceManager, + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo); + std::vector fileEntries_; + std::vector handleAbilityLib_; // the handler of ACE Library. +#endif // ABILITY_LIBRARY_LOADER +#ifdef APPLICATION_LIBRARY_LOADER + void *handleAppLib_ = nullptr; // the handler of ACE Library. + constexpr static std::string applicationLibraryPath = "/hos/lib/libapplication_native.z.so"; +#endif // APPLICATION_LIBRARY_LOADER + DISALLOW_COPY_AND_MOVE(MainThread); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_MAIN_THREAD_H diff --git a/frameworks/kits/appkit/native/app/include/ohos_application.h b/frameworks/kits/appkit/native/app/include/ohos_application.h new file mode 100644 index 0000000000000000000000000000000000000000..40399f70e006df0e05578ceed0ba87eb3977bfb0 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/ohos_application.h @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_APPLICATION_H +#define FOUNDATION_APPEXECFWK_OHOS_APPLICATION_H + +#include +#include +#include + +#include "ability_lifecycle_callbacks.h" +#include "ability_runtime/context/context.h" +#include "ability_stage.h" +#include "application_context.h" +#include "element_callback.h" + +namespace OHOS { +namespace AbilityRuntime { +class Runtime; +} // namespace AbilityRuntime +namespace AppExecFwk { +class ElementsCallback; +class ApplicationImpl; +class Configuration; +class AbilityRecordMgr; +class OHOSApplication : public ApplicationContext, + public AbilityLifecycleCallbacks, + public std::enable_shared_from_this { +public: + OHOSApplication(); + virtual ~OHOSApplication(); + + /** + * @brief dump OHOSApplication info + * + * @param extra dump OHOSApplication info + */ + void DumpApplication(); + + /** + * @brief Set Runtime + * + * @param runtime Runtime instance. + */ + void SetRuntime(std::unique_ptr&& runtime); + + /** + * @brief Set ApplicationContext + * + * @param context ApplicationContext instance. + */ + void SetApplicationContext(const std::shared_ptr &abilityRuntimeContext); + + /** + * + * @brief Set the abilityRecordMgr to the OHOSApplication. + * + * @param abilityRecordMgr + */ + void SetAbilityRecordMgr(const std::shared_ptr &abilityRecordMgr); + + /** + * + * @brief Register AbilityLifecycleCallbacks with OHOSApplication + * + * @param callBack callBack When the life cycle of the ability in the application changes, + */ + void RegisterAbilityLifecycleCallbacks(const std::shared_ptr &callBack); + + /** + * + * @brief Unregister AbilityLifecycleCallbacks with OHOSApplication + * + * @param callBack RegisterAbilityLifecycleCallbacks`s callBack + */ + void UnregisterAbilityLifecycleCallbacks(const std::shared_ptr &callBack); + + /** + * + * @brief Will be called when the given ability calls Ability->onStart + * + * @param Ability Indicates the ability object that calls the onStart() method. + */ + void OnAbilityStart(const std::shared_ptr &ability); + + /** + * + * @brief Will be called when the given ability calls Ability->onInactive + * + * @param Ability Indicates the Ability object that calls the onInactive() method. + */ + void OnAbilityInactive(const std::shared_ptr &ability); + + /** + * + * @brief Will be called when the given ability calls Ability->onBackground + * + * @param Ability Indicates the Ability object that calls the onBackground() method. + */ + void OnAbilityBackground(const std::shared_ptr &ability); + + /** + * + * @brief Will be called when the given ability calls Ability->onForeground + * + * @param Ability Indicates the Ability object that calls the onForeground() method. + */ + void OnAbilityForeground(const std::shared_ptr &ability); + + /** + * + * @brief Will be called when the given ability calls Ability->onActive + * + * @param Ability Indicates the Ability object that calls the onActive() method. + */ + void OnAbilityActive(const std::shared_ptr &ability); + + /** + * + * @brief Will be called when the given ability calls Ability->onStop + * + * @param Ability Indicates the Ability object that calls the onStop() method. + */ + void OnAbilityStop(const std::shared_ptr &ability); + + /** + * + * Called when Ability#onSaveAbilityState(PacMap) was called on an ability. + * + * @param outState Indicates the PacMap object passed to Ability#onSaveAbilityState(PacMap) + * for storing user data and states. This parameter cannot be null. + */ + void DispatchAbilitySavedState(const PacMap &outState); + + /** + * + * @brief Called when an ability calls Ability#onSaveAbilityState(PacMap). + * You can implement your own logic in this method. + * @param outState IIndicates the {@link PacMap} object passed to the onSaveAbilityState() callback. + * + */ + void OnAbilitySaveState(const PacMap &outState); + + /** + * + * @brief Register ElementsCallback with OHOSApplication + * + * @param callBack callBack when the system configuration of the device changes. + */ + void RegisterElementsCallbacks(const std::shared_ptr &callback); + + /** + * + * @brief Unregister ElementsCallback with OHOSApplication + * + * @param callback RegisterElementsCallbacks`s callback + */ + void UnregisterElementsCallbacks(const std::shared_ptr &callback); + + /** + * + * @brief Will be Called when the system configuration of the device changes. + * + * @param config Indicates the new Configuration object. + */ + virtual void OnConfigurationUpdated(const Configuration &config); + + /** + * + * @brief Called when the system has determined to trim the memory, for example, + * when the ability is running in the background and there is no enough memory for + * running as many background processes as possible. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + */ + virtual void OnMemoryLevel(int level); + + /** + * + * @brief Will be called the application foregrounds + * + */ + virtual void OnForeground(); + + /** + * + * @brief Will be called the application backgrounds + * + */ + virtual void OnBackground(); + + /** + * + * @brief Will be called the application starts + * + */ + virtual void OnStart(); + + /** + * + * @brief Will be called the application ends + * + */ + virtual void OnTerminate(); + + /** + * @brief add the ability stage when a hap first load + * + * @param abilityRecord + * @return abilityStage context + */ + std::shared_ptr AddAbilityStage( + const std::shared_ptr &abilityRecord); + + /** + * @brief add the ability stage when a hap first load + * + * @param hapModuleInfo + * @return Returns true on success, false on failure + */ + bool AddAbilityStage(const AppExecFwk::HapModuleInfo &hapModuleInfo); + + /** + * @brief remove the ability stage when all of the abilities in the hap have been removed + * + * @param abilityInfo + */ + void CleanAbilityStage(const sptr &token, const std::shared_ptr &abilityInfo); + + /** + * @brief return the application context + * + * @param context + */ + std::shared_ptr GetAppContext() const; + + /** + * @brief return the application runtime + * + * @param runtime + */ + const std::unique_ptr& GetRuntime(); + + /* + * + * @brief Will be called the application ends + * + */ + virtual void SetConfiguration(const Configuration &config); + + void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName, std::string &flag); + + virtual std::shared_ptr GetConfiguration(); + +private: + std::list> abilityLifecycleCallbacks_; + std::list> elementsCallbacks_; + std::shared_ptr abilityRecordMgr_ = nullptr; + std::shared_ptr abilityRuntimeContext_ = nullptr; + std::unordered_map> abilityStages_; + std::unique_ptr runtime_; + std::shared_ptr configuration_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_APPLICATION_H diff --git a/frameworks/kits/appkit/native/app/include/sys_mgr_client.h b/frameworks/kits/appkit/native/app/include/sys_mgr_client.h new file mode 100644 index 0000000000000000000000000000000000000000..e31cd46556e8cbb6cf5f17bbb95440da033e9b68 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/sys_mgr_client.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_SYS_MRG_CLIENT_H +#define OHOS_AAFWK_SYS_MRG_CLIENT_H + +#include +#include +#include +#include + +#include "if_system_ability_manager.h" +#include "iremote_object.h" +#include "singleton.h" + +namespace OHOS { +namespace AppExecFwk { +class SysMrgClient { + DECLARE_DELAYED_SINGLETON(SysMrgClient) +public: + /** + * + * Get the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility whitch want to get. + */ + sptr GetSystemAbility(const int32_t systemAbilityId); + + /** + * + * Register the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility whitch want to register. + * @param broker The systemAbility whitch want to be registered. + */ + void RegisterSystemAbility(const int32_t systemAbilityId, sptr broker); + + /** + * + * Unregister the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility whitch want to unregister. + */ + void UnregisterSystemAbility(const int32_t systemAbilityId); + +private: + OHOS::sptr abilityManager_; + std::mutex saMutex_; + std::unordered_map> servicesMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_AAFWK_SYS_MRG_CLIENT_H diff --git a/frameworks/kits/appkit/native/app/include/task/revocable.h b/frameworks/kits/appkit/native/app/include/task/revocable.h new file mode 100644 index 0000000000000000000000000000000000000000..c1450361f65051755133c76047a8e01e817adf32 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/task/revocable.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_TASK_REVOCABLE_H +#define OHOS_APP_DISPATCHER_TASK_REVOCABLE_H + +namespace OHOS { +namespace AppExecFwk { +class Revocable { +public: + virtual bool Revoke() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/include/task/task_dispatcher_handler.h b/frameworks/kits/appkit/native/app/include/task/task_dispatcher_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..21799baeb81f7763f189dcc97657612c0488d5e1 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/task/task_dispatcher_handler.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_DISPATCHER_THREADING_TASK_DISPATCHER_HANDLER_H +#define OHOS_APP_DISPATCHER_THREADING_TASK_DISPATCHER_HANDLER_H + +#include +#include "task.h" +namespace OHOS { +namespace AppExecFwk { +/** + * Interface for handling post a task. + * + */ +class TaskDispatcherHandler { +public: + /** + * Dispatch a task asynchronously. + * + * @param task The task to post. + * @return true if successfully post a task, otherwise false. + */ + virtual bool Dispatch(const std::shared_ptr &runnable) = 0; + /** + * Dispatch a task synchronously. + * + * @param task The task to post. + * @return true if successfully post a task, otherwise false. + */ + virtual bool DispatchSync(const std::shared_ptr &runnable) = 0; + + /** + * Dispatch a task asynchronously at specific time point. + * + * @param task The task to post. + * @param delayMs The delay time expected to post the task, in milli second. + * @return true if successfully post a task, otherwise false. + */ + virtual bool Dispatch(const std::shared_ptr &runnable, long delayMs) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif diff --git a/frameworks/kits/appkit/native/app/include/task/task_priority.h b/frameworks/kits/appkit/native/app/include/task/task_priority.h new file mode 100644 index 0000000000000000000000000000000000000000..3c9f0664c4a1d0a64d2f4fad24bd38106d09dd94 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/task/task_priority.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_TASK_TASK_PRIORITY_H +#define OHOS_APP_DISPATCHER_TASK_TASK_PRIORITY_H + +namespace OHOS { +namespace AppExecFwk { +enum TaskPriority { + /** + * Indicates the highest task priority. Tasks with this priority are executed before other tasks. + * + * @see #DEFAULT + * @see #LOW + * @since 1 + */ + HIGH, + /** + * Indicates the default task priority. Tasks with this priority are executed after those with the {@link #HIGH} + * priority are complete. + * + * @see #HIGH + * @see #LOW + * @since 1 + */ + DEFAULT, + /** + * Indicates the low task priority. Tasks with this priority are executed after those with the {@link #HIGH} or + * {@link #DEFAULT} priority are complete. + * + * @see #HIGH + * @see #DEFAULT + * @since 1 + */ + LOW +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/frameworks/kits/appkit/native/app/include/task_dispatcher.h b/frameworks/kits/appkit/native/app/include/task_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..00c9147c48cb46a0b410ee36ed091382fb1a389f --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/task_dispatcher.h @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APP_DISPATCHER_TASK_DISPATCHER_H +#define OHOS_APP_DISPATCHER_TASK_DISPATCHER_H + +#include +#include "task_priority.h" +#include "revocable.h" +#include "runnable.h" +#include "group.h" +#include "appexecfwk_errors.h" +namespace OHOS { +namespace AppExecFwk { +template +using IteratableTask = std::function; + +class TaskDispatcher { +public: + virtual ~TaskDispatcher() = default; + + /** + * @brief Dispatches a task and waits until the task is complete in the current thread. + * + * @param runnable Indicates the task to be executed. This parameter includes all information required for the task + * execution. + */ + virtual ErrCode SyncDispatch(const std::shared_ptr &runnable) = 0; + + /** + * @brief Asynchronously dispatches a task. + * + *

This method dispatches a task and returns a value immediately without waiting for the task to execute.

+ * + * @param runnable Indicates the task to be executed. This parameter includes all information required for the task + * execution. + * @return Returns a {@link std::shared_ptr} instance used for revoking the given task + * if it has not been invoked. + */ + virtual std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable) = 0; + + /** + * @brief Dispatches a task after the given delay. + * + *

This is an asynchronous execution and returns a value immediately without waiting. The task will be + * dispatched to the queue after the given delay specified by {@code delayMs}, and its actual execution time + * maybe later than the given time. The time when the task will be executed depends on the length of the queue + * and how busy the thread pool is. + *

+ * + * @param runnable Indicates the task to be executed. This parameter includes all information required for the task + * execution. + * @param delayMs Indicates the time period that the given task has to wait before being dispatched. + * @return Returns a {@link std::shared_ptr} instance used for revoking the given task + * if it has not been invoked. + */ + virtual std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs) = 0; + + /** + * @brief Sets an execution barrier in a task group for the given task and waits for the task to be executed after all + * tasks in the task group are finished. + * + *

The current thread is blocked until the given task is complete. Incorrect use of this method may cause a + * deadlock. + * If too many threads are blocked, resources in the thread pool will be used up.

+ * + * @param runnable Indicates the task to be executed. + */ + virtual ErrCode SyncDispatchBarrier(const std::shared_ptr &runnable) = 0; + + /** + * @brief Sets an execution barrier for the given task to be executed only after all tasks in the task group are + * finished. This method does not wait for the given task to execute. + * + *

Task execution barriers are unavailable on global task dispatchers. Example code for setting a task + * execution barrier:

+ * + *
{@code
+     * std::shared_ptr parallelTaskDispatcher =
+     *     context.CreateParallelTaskDispatcher(dispatcherName, taskPriority);
+     * parallelTaskDispatcher->AsyncDispatch(std::make_shared([](){
+     *     sleep(1000);
+     *     // sleep enough time
+     *     std::cout << "before barrier" << std::endl;
+     * }));
+     * parallelTaskDispatcher->AsyncDispatchBarrier(std::make_shared([]() {
+     *     std::cout << "Barrier" << std::endl;
+     * }));
+     * parallelTaskDispatcher->AsyncDispatch(std::make_shared([]() {
+     *     std::cout << "after barrier" << std::endl;
+     * }));
+     *
+     * // Result will be: 1.before barrier; 2.Barrier; 3.after barrier.
+     * }
+     * 
+ * + * @param runnable Indicates the task to be executed. This parameter includes all information required for the task + * execution. + */ + virtual ErrCode AsyncDispatchBarrier(const std::shared_ptr &runnable) = 0; + + /** + * @brief Creates a task group. + * + *

The {@link std::shared_ptr} object returned by this method does not contain any task. + * If you need to dispatch tasks asynchronously, you can use {@link #asyncGroupDispatch} to associate this object + * with multiple tasks for monitoring the execution progress of all these tasks.

+ *

Example code for waiting for the completion of all download tasks in a task group:

+ *
 {@code
+     * void groupTest(Context context) {
+     *     std::shared_ptr parallelTaskDispatcher =
+     *         context.CreateParallelTaskDispatcher(dispatcherName, taskPriority);
+     *     // Creates a task group.
+     *     std::shared_ptr group = context.CreateDispatchGroup();
+     *     // Adds asynchronous tasks to the task group.
+     *     dispatcher->AsyncGroupDispatch(group, []() {
+     *         // Downloads a 10 MB file.
+     *         download(url1);
+     *         std::cout << "Finished downloading URL 1" << std::endl;
+     *     });
+     *
+     *     std::cout << "1" << std::endl;
+     *
+     *     dispatcher->AsyncGroupDispatch(group, []() {
+     *         // Downloads a 1 MB file.
+     *         download(url2);
+     *         std::cout << "Finished downloading URL 2" << std:endl;
+     *     });
+     *
+     *     // Executes a new task until all tasks in the task group are complete.
+     *     dispatcher->GroupDispatchNotify(group, []() {
+     *         std::cout << "All tasks finished. Do shutdown." << std:endl;
+     *     });
+     *     std::cout << "2" << std::endl;
+     * }
+     *
+     * @return Returns a {@link std::shared_ptr} object.
+     */
+    virtual std::shared_ptr CreateDispatchGroup() = 0;
+
+    /**
+     * @brief Adds a task to a task group asynchronously.
+     *
+     * 

This method returns a value immediately without waiting for the task to execute.

+ * + * @param group Indicates the group to which the task is added. + * @param runnable Indicates the task to be executed. This parameter includes all information required for the task + * execution. + * @return Returns a {@link std::shared_ptr} instance used for revoking the given task + * if it has not been invoked. + */ + virtual std::shared_ptr AsyncGroupDispatch( + const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; + + /** + * @brief Waits all tasks in a task group to finish. + * + * @param group Indicates the task group containing the waiting tasks. + * @param timeout Indicates the maximum waiting time for a task. + * @return Returns {@code true} if all tasks are correctly executed; returns {@code false} if any task times out. + */ + virtual bool GroupDispatchWait(const std::shared_ptr &group, long timeout) = 0; + + /** + * @brief Executes a task after all tasks in the task group are finished. + * + * @param group Indicates the task group containing the waiting tasks. + * @param runnable Indicates the task to be executed after all tasks are finished. + */ + virtual ErrCode GroupDispatchNotify( + const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; + + /** + * @brief Executes a task multiple times without waiting. + * + * @param task Indicates the task to be executed. This parameter includes all information required for the task + * execution. + * @param iterations Indicates the number of times the task is executed. The value must be a positive integer. + */ + virtual ErrCode ApplyDispatch(const std::shared_ptr> &task, long iterations) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/include/watchdog.h b/frameworks/kits/appkit/native/app/include/watchdog.h new file mode 100644 index 0000000000000000000000000000000000000000..63f1afd0bff26300925cf0cbfa838572d1f82140 --- /dev/null +++ b/frameworks/kits/appkit/native/app/include/watchdog.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_WATCH_DOG_H +#define FOUNDATION_APPEXECFWK_WATCH_DOG_H + +#include +#include +#include "event_handler.h" +#include "inner_event.h" + +namespace OHOS { +namespace AppExecFwk { +const uint32_t MAIN_THREAD_IS_ALIVE = 0; +const uint32_t MAIN_THREAD_TIMEOUT_TIME = 3000; +const uint32_t INI_ZERO = 0; +const uint32_t INI_TIMER_FIRST_SECOND = 10; +const uint32_t INI_TIMER_SECOND = 3; +const std::string MAIN_THREAD_IS_ALIVE_MSG = "MAIN_THREAD_IS_ALIVE"; +class WatchDog : public EventHandler { +public: + WatchDog(const std::shared_ptr &runner); + virtual ~WatchDog() = default; + + /** + * + * @brief Process the event. + * + * @param event the event want to be processed. + * + */ + void ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event) override; + static void Timer(int sig); + + /** + * + * @brief Init the Watchdog. + * + * @param mainHandler The handler of main thread. + * @param watchDogHandler The handler of watchdog thread. + */ + void Init(const std::shared_ptr &mainHandler, const std::shared_ptr &watchDogHandler); + + /** + * + * @brief Stop the mainthread function of watchdog. + * + */ + void Stop(); + + /** + * + * @brief Get the eventHandler of watchdog thread. + * + * @return Returns the eventHandler of watchdog thread. + */ + static std::shared_ptr GetCurrentHandler(); + + /** + * + * @brief Get the App main thread state. + * + * @return Returns the App main thread state. + */ + static bool GetAppMainThreadState(); + +private: + std::shared_ptr watchDogRunner_; + static bool appMainThreadIsAlive_; + static std::shared_ptr appMainHandler_; + static std::shared_ptr currentHandler_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_WATCH_DOG_H diff --git a/frameworks/kits/appkit/native/app/src/ability_manager.cpp b/frameworks/kits/appkit/native/app/src/ability_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ced6666e189536cc7cea91e5591944e2f129ca19 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/ability_manager.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_manager.h" +#include "app_log_wrapper.h" +#include "singleton.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +AbilityManager &AbilityManager::GetInstance() +{ + static AbilityManager abilityManager; + return abilityManager; +} + +void AbilityManager::StartAbility(const Want &want, int requestCode = -1) +{ + APP_LOGD("%s, %d", __func__, __LINE__); + ErrCode error = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, requestCode); + if (error != ERR_OK) { + APP_LOGE("%s failed, error : %d", __func__, error); + } +} + +void AbilityManager::MoveMissionToTop(int missionId) +{ + APP_LOGD("%s, %d", __func__, __LINE__); + ErrCode error = AAFwk::AbilityManagerClient::GetInstance()->MoveMissionToTop(missionId); + if (error != ERR_OK) { + APP_LOGE("%s failed, error : %d", __func__, error); + } +} + +StackInfo AbilityManager::GetAllStackInfo() const +{ + APP_LOGD("%s, %d", __func__, __LINE__); + StackInfo info; + ErrCode error = AAFwk::AbilityManagerClient::GetInstance()->GetAllStackInfo(info); + if (error != ERR_OK) { + APP_LOGE("%s failed, error : %d", __func__, error); + } + + return info; +} + +std::vector AbilityManager::QueryRecentAbilityMissionInfo(int numMax, int flags) const +{ + APP_LOGD("%s, %d", __func__, __LINE__); + std::vector info; + ErrCode error = AAFwk::AbilityManagerClient::GetInstance()->GetRecentMissions(numMax, flags, info); + if (error != ERR_OK) { + APP_LOGE("%s failed, error : %d", __func__, error); + } + + return info; +} + +std::vector AbilityManager::QueryRunningAbilityMissionInfo(int numMax) const +{ + APP_LOGD("%s, %d", __func__, __LINE__); + std::vector info; + ErrCode error = + AAFwk::AbilityManagerClient::GetInstance()->GetRecentMissions(numMax, RECENT_IGNORE_UNAVAILABLE, info); + if (error != ERR_OK) { + APP_LOGE("%s failed, error : %d", __func__, error); + } + + return info; +} + +void AbilityManager::RemoveMissions(const std::vector &missionId) +{ + APP_LOGD("%s, %d", __func__, __LINE__); + ErrCode error = AAFwk::AbilityManagerClient::GetInstance()->RemoveMissions(missionId); + if (error != ERR_OK) { + APP_LOGE("%s failed, error : %d", __func__, error); + } +} + +int32_t AbilityManager::ClearUpApplicationData(const std::string &bundleName) +{ + APP_LOGD("%s, %d", __func__, __LINE__); + auto object = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); + sptr appMgr_ = iface_cast(object); + if (appMgr_ == nullptr) { + APP_LOGE("%s, appMgr_ is nullptr", __func__); + return ERR_NULL_OBJECT; + } + + return appMgr_->ClearUpApplicationData(bundleName); +} + +std::vector AbilityManager::GetAllRunningProcesses() +{ + APP_LOGD("%s, %d", __func__, __LINE__); + auto object = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); + sptr appMgr_ = iface_cast(object); + std::vector info; + if (appMgr_ == nullptr) { + APP_LOGE("%s, appMgr_ is nullptr", __func__); + return info; + } + + appMgr_->GetAllRunningProcesses(info); + return info; +} + +int AbilityManager::KillProcessesByBundleName(const std::string &bundleName) +{ + APP_LOGD("%s, %d", __func__, __LINE__); + ErrCode error = AAFwk::AbilityManagerClient::GetInstance()->KillProcess(bundleName); + if (error != ERR_OK) { + APP_LOGE("%s failed, error : %d", __func__, error); + return error; + } + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/src/ability_record_mgr.cpp b/frameworks/kits/appkit/native/app/src/ability_record_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fde2f76718ed0609b00d1725528fe6f1c59e543 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/ability_record_mgr.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_record_mgr.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Get the token witch is set to the AbilityRecordMgr. + * + * @return Returns the token which is set to the AbilityRecordMgr. + */ +sptr AbilityRecordMgr::GetToken() const +{ + return tokens_; +} + +/** + * @brief Set the token witch the app launched. + * + * @param token The token which the is launched by app. + */ +void AbilityRecordMgr::SetToken(const sptr &token) +{ + if (token == nullptr) { + APP_LOGE("AbilityRecordMgr::SetToken failed, application is nullptr"); + return; + } + tokens_ = token; +} + +/** + * @brief Set the eventRunner of abilitythread to the AbilityRecordMgr. + * + * @param eventRunner The runner of the abilitythread. + * + */ +void AbilityRecordMgr::SetEventRunner(const std::shared_ptr &eventRunner) +{ + if (eventRunner == nullptr) { + APP_LOGE("AbilityRecordMgr::SetEventRunner failed, eventRunner is nullptr"); + return; + } + sptr token = GetToken(); + if (token == nullptr) { + APP_LOGE("AbilityRecordMgr::SetEventRunner failed, token is nullptr"); + return; + } + + std::shared_ptr abilityInstance = GetAbilityItem(token); + if (abilityInstance != nullptr) { + abilityInstance->SetEventRunner(eventRunner); + } else { + APP_LOGW("AbilityRecordMgr::setEventRunner failed, ability record is not exists"); + } +} + +/** + * @brief Save the token and abilityRecord to the AbilityRecordMgr. + * + * @param token The token which the abilityRecord belongs to. + * @param abilityRecord the abilityRecord witch contains the context info belong the the ability. + * + */ +void AbilityRecordMgr::AddAbilityRecord( + const sptr &token, const std::shared_ptr &abilityRecord) +{ + if (token == nullptr) { + APP_LOGE("AbilityRecordMgr::AddAbilityRecord failed, token is nullptr"); + return; + } + + if (abilityRecord == nullptr) { + APP_LOGE("AbilityRecordMgr::AddAbilityRecord failed, abilityRecord is nullptr"); + return; + } + + abilityRecords_[token] = abilityRecord; +} + +/** + * @brief Remove the abilityRecord by token. + * + * @param token The token which the abilityRecord belongs to. + * + */ +void AbilityRecordMgr::RemoveAbilityRecord(const sptr &token) +{ + if (token == nullptr) { + APP_LOGE("AbilityRecordMgr::RemoveAbilityRecord failed, token is nullptr"); + return; + } + abilityRecords_.erase(token); +} + +/** + * @brief Get the number of abilityRecords which the AbilityRecordMgr saved. + * + * @return Return the number of abilityRecords which the AbilityRecordMgr saved. + * + */ +int AbilityRecordMgr::GetRecordCount() const +{ + return abilityRecords_.size(); +} + +/** + * @brief Get the abilityRecord by token. + * + * @param token The token which the abilityRecord belongs to. + * + */ +std::shared_ptr AbilityRecordMgr::GetAbilityItem(const sptr &token) const +{ + if (token == nullptr) { + APP_LOGE("AbilityRecordMgr::GetAbilityItem failed, token is nullptr"); + return nullptr; + } + + const auto &iter = abilityRecords_.find(token); + if (iter != abilityRecords_.end()) { + APP_LOGI("AbilityRecordMgr::GetAbilityItem : the ability found"); + return iter->second; + } + APP_LOGI("AbilityRecordMgr::GetAbilityItem : the ability not found"); + return nullptr; +} + +/** + * @brief Get the all tokens in the abilityRecordMgr. + * + * @return all tokens in the abilityRecordMgr. + * + */ +std::vector> AbilityRecordMgr::GetAllTokens() +{ + std::vector> tokens; + for (std::map, std::shared_ptr>::iterator it = abilityRecords_.begin(); + it != abilityRecords_.end(); + ++it) { + sptr token = it->first; + tokens.emplace_back(token); + } + return tokens; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/app_loader.cpp b/frameworks/kits/appkit/native/app/src/app_loader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6a9d550bdd03919c0c3167bae9eb322887b757b --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/app_loader.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @description: Gets the ApplicationLoader object to application register + * @param None + * @return ApplicationLoader + */ +ApplicationLoader &ApplicationLoader::GetInstance() +{ + static ApplicationLoader applicationLoader; + return applicationLoader; +} + +/** + * @description: Gets the ApplicationLoader object to register application + * @param bundleName the bundle name of the application. + * @param createFunc constructor function of application class. + * @return None + */ +void ApplicationLoader::RegisterApplication(const std::string &bundleName, const CreateApplication &createFunc) +{ + applications_.emplace(bundleName, createFunc); + APP_LOGD("ApplicationLoader::RegisterApplication:%{public}s", bundleName.c_str()); +} + +/** + * @description: Gets the {@link OHOSApplication} object + * @return Return {@link OHOSApplication} object which is registered by developer. + */ +OHOSApplication *ApplicationLoader::GetApplicationByName() +{ + auto it = applications_.find("OHOSApplication"); + if (it == applications_.end()) { + APP_LOGE("ApplicationLoader::GetApplicationByName failed:OHOSApplication"); + } else { + return it->second(); + } + return nullptr; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/application_context.cpp b/frameworks/kits/appkit/native/app/src/application_context.cpp new file mode 100755 index 0000000000000000000000000000000000000000..1f44256711acc69a1163f11cc74b584cfb2b82f7 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/application_context.cpp @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_context.h" +#include "app_log_wrapper.h" +#include "task_dispatcher_context.h" + +namespace OHOS { +namespace AppExecFwk { +ApplicationContext::ApplicationContext() +{} +ApplicationContext::~ApplicationContext() +{} + +/** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ +const std::shared_ptr ApplicationContext::GetAbilityInfo() +{ + return nullptr; +} + +/** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE + * template is started. You can define the request code to identify the results returned by abilities. The value + * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE + * template. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ApplicationContext::StartAbility(const AAFwk::Want &want, int requestCode) +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief Starts a new ability with special ability start setting. + * + * @param want Indicates the Want containing information about the target ability to start. + * @param requestCode Indicates the request code returned after the ability is started. You can define the request code + * to identify the results returned by abilities. The value ranges from 0 to 65535. + * @param abilityStartSetting Indicates the special start setting used in starting ability. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ApplicationContext::StartAbility(const Want &want, int requestCode, + const AbilityStartSetting &abilityStartSetting) +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult + * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode passed. + * + * @param requestCode Indicates the request code passed for starting the ability. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ApplicationContext::TerminateAbility(int requestCode) +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief Destroys the current ability. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ApplicationContext::TerminateAbility() +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief + * Destroys this Service ability if the number of times it has been started equals the number represented by the + * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service + * ability, except that this method helps you avoid destroying it if a client has requested a Service + * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it. + * + * @param startId Indicates the number of startup times of this Service ability passed to + * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is + * incremented by 1 every time this ability is started. For example, + * if this ability has been started for six times, the value of {@code startId} is {@code 6}. + * + * @return Returns {@code true} if the {@code startId} matches the number of startup times + * and this Service ability will be destroyed; returns {@code false} otherwise. + */ +bool ApplicationContext::TerminateAbilityResult(int startId) +{ + return false; +} + +/** + * @brief Obtains the bundle name of the ability that called the current ability. + * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will + * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int, + * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned. + * + * @return Returns the bundle name of the calling ability; returns null if no calling ability is available. + */ +std::string ApplicationContext::GetCallingBundle() +{ + return ""; +} + +/** + * @brief Connects the current ability to an ability + * + * @param want Indicates the want containing information about the ability to connect + * + * @param conn Indicates the callback object when the target ability is connected. + * + * @return True means success and false means failure + */ +bool ApplicationContext::ConnectAbility(const Want &want, const sptr &conn) +{ + return false; +} + +/** + * @brief Disconnects the current ability from an ability + * + * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection + * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ApplicationContext::DisconnectAbility(const sptr &conn) +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. + * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE + * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE + * template. The current ability itself can be destroyed by calling the terminateAbility() method. + * + * @param want Indicates the Want containing information about the ability to destroy. + * + * @return Returns true if the ability is destroyed successfully; returns false otherwise. + */ +bool ApplicationContext::StopAbility(const AAFwk::Want &want) +{ + return false; +} + +sptr ApplicationContext::GetToken() +{ + return nullptr; +} + +/** + * @brief Starts multiple abilities. + * + * @param wants Indicates the Want containing information array about the target ability to start. + */ +void ApplicationContext::StartAbilities(const std::vector &wants) +{} + +/** + * @brief Checks whether this ability is the first ability in a mission. + * + * @return Returns true is first in Mission. + */ +bool ApplicationContext::IsFirstInMission() +{ + return false; +} + +/** + * @brief Obtains the unique ID of the mission containing this ability. + * + * @return Returns the unique mission ID. + */ +int ApplicationContext::GetMissionId() +{ + return -1; +} + +/** + * @brief Creates a parallel task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. + * + * @return Returns a parallel task dispatcher. + */ +std::shared_ptr ApplicationContext::CreateParallelTaskDispatcher( + const std::string &name, const TaskPriority &priority) +{ + APP_LOGI("ApplicationContext::CreateParallelTaskDispatcher begin"); + if (taskDispatcherContext_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (taskDispatcherContext_ == nullptr) { + taskDispatcherContext_ = std::make_shared(); + APP_LOGI("ApplicationContext::CreateParallelTaskDispatcher threadpool create"); + } + + if (taskDispatcherContext_ == nullptr) { + APP_LOGE("ApplicationContext::CreateParallelTaskDispatcher taskDispatcherContext_ is nullptr"); + return nullptr; + } + } + + std::shared_ptr task = taskDispatcherContext_->CreateParallelDispatcher(name, priority); + APP_LOGI("ApplicationContext::CreateParallelTaskDispatcher end"); + return task; +} + +/** + * @brief Creates a serial task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. + * + * @return Returns a serial task dispatcher. + */ +std::shared_ptr ApplicationContext::CreateSerialTaskDispatcher( + const std::string &name, const TaskPriority &priority) +{ + APP_LOGI("ApplicationContext::CreateSerialTaskDispatcher begin"); + if (taskDispatcherContext_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (taskDispatcherContext_ == nullptr) { + taskDispatcherContext_ = std::make_shared(); + APP_LOGI("ApplicationContext::CreateSerialTaskDispatcher threadpool create"); + } + + if (taskDispatcherContext_ == nullptr) { + APP_LOGE("ApplicationContext::CreateSerialTaskDispatcher taskDispatcherContext_ is nullptr"); + return nullptr; + } + } + + std::shared_ptr task = taskDispatcherContext_->CreateSerialDispatcher(name, priority); + APP_LOGI("ApplicationContext::CreateSerialTaskDispatcher end"); + return task; +} + +/** + * @brief Obtains a global task dispatcher with a specified priority. + * + * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. + * + * @return Returns a global task dispatcher. + */ +std::shared_ptr ApplicationContext::GetGlobalTaskDispatcher(const TaskPriority &priority) +{ + APP_LOGI("ApplicationContext::GetGlobalTaskDispatcher begin"); + if (taskDispatcherContext_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (taskDispatcherContext_ == nullptr) { + taskDispatcherContext_ = std::make_shared(); + APP_LOGI("ApplicationContext::GetGlobalTaskDispatcher threadpool create"); + } + + if (taskDispatcherContext_ == nullptr) { + APP_LOGE("ApplicationContext::GetGlobalTaskDispatcher taskDispatcherContext_ is nullptr"); + return nullptr; + } + } + + std::shared_ptr task = taskDispatcherContext_->GetGlobalTaskDispatcher(priority); + APP_LOGI("ApplicationContext::GetGlobalTaskDispatcher end"); + return task; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/application_env.cpp b/frameworks/kits/appkit/native/app/src/application_env.cpp new file mode 100644 index 0000000000000000000000000000000000000000..208aeaa11f48e148b87278ddc41acb55d6e741c6 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/application_env.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_env.h" +#include "application_env_impl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Obtains the bundle name of the application + * @param - + * @return Returns the pointer to the bundle name if the operation is successful; returns a null pointer otherwise. + */ +const char *GetBundleName() +{ + OHOS::AppExecFwk::ApplicationEnvImpl *pApplicationEnvIml = OHOS::AppExecFwk::ApplicationEnvImpl::GetInstance(); + const char *pBundleName = nullptr; + + if (pApplicationEnvIml) { + pBundleName = pApplicationEnvIml->GetBundleName().c_str(); + } + + return pBundleName; +} + +/** + * @brief Obtains the source code path of this application. + * @param - + * @return Returns the pointer to the source code path of this application. + */ +const char *GetSrcPath() +{ + OHOS::AppExecFwk::ApplicationEnvImpl *pApplicationEnvIml = OHOS::AppExecFwk::ApplicationEnvImpl::GetInstance(); + const char *pSrcPath = nullptr; + + if (pApplicationEnvIml) { + pSrcPath = pApplicationEnvIml->GetSrcPath().c_str(); + } + + return pSrcPath; +} + +/** + * @brief Obtains the data path of this application. + * @param - + * @return Returns the pointer to the data path of this application. + */ +const char *GetDataPath() +{ + OHOS::AppExecFwk::ApplicationEnvImpl *pApplicationEnvIml = OHOS::AppExecFwk::ApplicationEnvImpl::GetInstance(); + const char *pDataPath = nullptr; + + if (pApplicationEnvIml) { + pDataPath = pApplicationEnvIml->GetDataPath().c_str(); + } + + return pDataPath; +} + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/frameworks/kits/appkit/native/app/src/application_env_impl.cpp b/frameworks/kits/appkit/native/app/src/application_env_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4cc9612e2dcfe1327da73c06d17433c4332a3085 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/application_env_impl.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_env_impl.h" +#include "application_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Sets L1 information about the runtime environment of the application to which the + * ability belongs, including the bundle name, source code path, and data path. + * @param appInfo + * @return void + */ +void ApplicationEnvImpl::SetAppInfo(const AppInfo &appInfo) +{ + bundleName_ = appInfo.bundleName; + dataPath_ = appInfo.dataPath; + srcPath_ = appInfo.srcPath; +} + +/** + * @brief Sets information about the runtime environment of the application to which the + * ability belongs, including the bundle name, source code path, and data path. + * @param appInfo indicates + * @return void + */ +void ApplicationEnvImpl::SetAppInfo(const ApplicationInfo &appInfo) +{ + bundleName_ = appInfo.bundleName; + dataPath_ = appInfo.dataDir; + srcPath_ = appInfo.codePath; +} + +/** + * @brief Gets the bundlename of the application's runtime environment + * @param - + * @return bundleName + */ +const std::string &ApplicationEnvImpl::GetBundleName() const +{ + return bundleName_; +} + +/** + * @brief Gets the SrcPath of the application's runtime environment + * @param - + * @return SrcPath + */ +const std::string &ApplicationEnvImpl::GetSrcPath() const +{ + return srcPath_; +} + +/** + * @brief Gets the DataPath of the application's runtime environment + * @param - + * @return DataPath + */ +const std::string &ApplicationEnvImpl::GetDataPath() const +{ + return dataPath_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/application_impl.cpp b/frameworks/kits/appkit/native/app/src/application_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..639425164fae9b54b63d500341d7f264251dc6d9 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/application_impl.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_impl.h" + +#include "app_log_wrapper.h" +#include "ohos_application.h" + +namespace OHOS { +namespace AppExecFwk { +ApplicationImpl::ApplicationImpl() : curState_(APP_STATE_CREATE), recordId_(0) +{} + +/** + * @brief Set the application to the ApplicationImpl. + * + * @param application The application which the mainthread launched. + * + */ +void ApplicationImpl::SetApplication(const std::shared_ptr &application) +{ + if (application == nullptr) { + APP_LOGE("ApplicationImpl::SetApplication failed, application is nullptr"); + return; + } + this->application_ = application; +} + +/** + * @brief Schedule the application to the APP_STATE_READY state. + * + * @return Returns true if performAppReady is scheduled successfully; + * Returns false otherwise. + */ +bool ApplicationImpl::PerformAppReady() +{ + APP_LOGD("ApplicationImpl::PerformAppReady called"); + if (curState_ == APP_STATE_CREATE) { + application_->OnStart(); + curState_ = APP_STATE_READY; + return true; + } + APP_LOGE("ApplicationImpl::PerformAppReady error! curState is %{public}d", curState_); + return false; +} + +/** + * @brief Schedule the application to the APP_STATE_FOREGROUND state. + * + * @return Returns true if PerformForeground is scheduled successfully; + * Returns false otherwise. + */ +bool ApplicationImpl::PerformForeground() +{ + APP_LOGD("ApplicationImpl::performForeground called"); + if ((curState_ == APP_STATE_READY) || (curState_ == APP_STATE_BACKGROUND)) { + application_->OnForeground(); + curState_ = APP_STATE_FOREGROUND; + return true; + } + APP_LOGE("ApplicationImpl::performForeground error! curState is %{public}d", curState_); + return false; +} + +/** + * @brief Schedule the application to the APP_STATE_BACKGROUND state. + * + * @return Returns true if PerformBackground is scheduled successfully; + * Returns false otherwise. + */ +bool ApplicationImpl::PerformBackground() +{ + APP_LOGD("ApplicationImpl::performBackground called"); + if (curState_ == APP_STATE_FOREGROUND) { + application_->OnBackground(); + curState_ = APP_STATE_BACKGROUND; + return true; + } + APP_LOGE("ApplicationImpl::performBackground error! curState is %{public}d", curState_); + return false; +} + +/** + * @brief Schedule the application to the APP_STATE_TERMINATED state. + * + * @return Returns true if PerformTerminate is scheduled successfully; + * Returns false otherwise. + */ +bool ApplicationImpl::PerformTerminate() +{ + APP_LOGD("ApplicationImpl::PerformTerminate called"); + if (curState_ == APP_STATE_BACKGROUND) { + application_->OnTerminate(); + curState_ = APP_STATE_TERMINATED; + return true; + } + APP_LOGE("ApplicationImpl::performTerminate error! curState is %{public}d", curState_); + return false; +} + +/** + * @brief Schedule the application to the APP_STATE_TERMINATED state. + * + * @return Returns true if PerformTerminate is scheduled successfully; + * Returns false otherwise. + */ +void ApplicationImpl::PerformTerminateStrong() +{ + APP_LOGD("ApplicationImpl::PerformTerminateStrong called"); + application_->OnTerminate(); +} + +/** + * @brief System determines to trim the memory. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + * + */ +void ApplicationImpl::PerformMemoryLevel(int level) +{ + APP_LOGD("ApplicationImpl::PerformMemoryLevel called"); + application_->OnMemoryLevel(level); +} + +/** + * @brief System determines to send the new config to application. + * + * @param config Indicates the updated configuration information. + * + */ +void ApplicationImpl::PerformConfigurationUpdated(const Configuration &config) +{ + APP_LOGD("ApplicationImpl::PerformConfigurationUpdated called"); + application_->OnConfigurationUpdated(config); +} + +/** + * @brief Set the target state to application. + * + * @param state The target state of application. + * + */ +int ApplicationImpl::SetState(int state) +{ + curState_ = state; + return curState_; +} + +/** + * @brief Get the current state of application. + * + * @return Returns the current state of application. + * + */ +int ApplicationImpl::GetState() const +{ + return curState_; +} + +/** + * @brief Set the RecordId to application. + * + * @param id recordId. + * + */ +void ApplicationImpl::SetRecordId(int id) +{ + recordId_ = id; +} + +/** + * @brief Get the recordId of application. + * + * @return Returns the recordId of application. + * + */ +int ApplicationImpl::GetRecordId() const +{ + return recordId_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/context_container.cpp b/frameworks/kits/appkit/native/app/src/context_container.cpp new file mode 100644 index 0000000000000000000000000000000000000000..700eb866e6a87aea50343a33f961b1db0cd0984d --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/context_container.cpp @@ -0,0 +1,1130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "context_container.h" + +#include "ability_manager_client.h" +#include "ability_manager_errors.h" +#include "app_log_wrapper.h" +#include "application_context.h" +#include "bundle_constants.h" + +namespace OHOS { +namespace AppExecFwk { +constexpr int DEFAULT_USERID = 100; +/** + * Attaches a Context object to the current ability. + * Generally, this method is called after Ability is loaded to provide the application context for the current ability. + * + * @param base Indicates a Context object. + */ +void ContextContainer::AttachBaseContext(const std::shared_ptr &base) +{ + if (base == nullptr) { + APP_LOGE("ContextDeal::AttachBaseContext failed, base is nullptr"); + return; + } + baseContext_ = base; +} + +/** + * Called when getting the ProcessInfo + * + * @return ProcessInfo + */ +std::shared_ptr ContextContainer::GetProcessInfo() const +{ + if (baseContext_ != nullptr) { + return baseContext_->GetProcessInfo(); + } + return nullptr; +} + +/** + * @brief Obtains information about the current application. The returned application information includes basic + * information such as the application name and application permissions. + * + * @return Returns the ApplicationInfo for the current application. + */ +std::shared_ptr ContextContainer::GetApplicationInfo() const +{ + if (baseContext_ != nullptr) { + return baseContext_->GetApplicationInfo(); + } else { + APP_LOGE("ContextContainer::GetApplicationInfo baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ +std::shared_ptr ContextContainer::GetApplicationContext() const +{ + if (baseContext_ != nullptr) { + return baseContext_->GetApplicationContext(); + } else { + APP_LOGE("ContextContainer::GetApplicationContext baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ +std::string ContextContainer::GetBundleCodePath() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetBundleCodePath(); + } else { + APP_LOGE("ContextContainer::GetBundleCodePath baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ +const std::shared_ptr ContextContainer::GetAbilityInfo() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetAbilityInfo(); + } else { + APP_LOGE("ContextContainer::GetAbilityInfo baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ +std::shared_ptr ContextContainer::GetContext() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetContext(); + } else { + APP_LOGE("ContextContainer::GetContext baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains an IBundleMgr instance. + * You can use this instance to obtain information about the application bundle. + * + * @return Returns an IBundleMgr instance. + */ +sptr ContextContainer::GetBundleManager() const +{ + if (baseContext_ != nullptr) { + return baseContext_->GetBundleManager(); + } else { + APP_LOGE("ContextContainer::GetBundleManager baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ +std::shared_ptr ContextContainer::GetResourceManager() const +{ + if (baseContext_ != nullptr) { + return baseContext_->GetResourceManager(); + } else { + APP_LOGE("ContextContainer::GetResourceManager baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Deletes the specified private file associated with the application. + * + * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators. + * + * @return Returns true if the file is deleted successfully; returns false otherwise. + */ +bool ContextContainer::DeleteFile(const std::string &fileName) +{ + if (baseContext_ != nullptr) { + return baseContext_->DeleteFile(fileName); + } else { + APP_LOGE("ContextContainer::DeleteFile baseContext_ is nullptr"); + return false; + } +} + +/** + * @brief Obtains the application-specific cache directory on the device's internal storage. The system + * automatically deletes files from the cache directory if disk space is required elsewhere on the device. + * Older files are always deleted first. + * + * @return Returns the application-specific cache directory. + */ +std::string ContextContainer::GetCacheDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetCacheDir(); + } else { + APP_LOGE("ContextContainer::GetCacheDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the application-specific code-cache directory on the device's internal storage. + * The system will delete any files stored in this location both when your specific application is upgraded, + * and when the entire platform is upgraded. + * + * @return Returns the application-specific code-cache directory. + */ +std::string ContextContainer::GetCodeCacheDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetCodeCacheDir(); + } else { + APP_LOGE("ContextContainer::GetCodeCacheDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the local database path. + * If the local database path does not exist, the system creates one and returns the created path. + * + * @return Returns the local database file. + */ +std::string ContextContainer::GetDatabaseDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetDatabaseDir(); + } else { + APP_LOGE("ContextContainer::GetDatabaseDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the absolute path where all private data files of this application are stored. + * + * @return Returns the absolute path storing all private data files of this application. + */ +std::string ContextContainer::GetDataDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetDataDir(); + } else { + APP_LOGE("ContextContainer::GetDataDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the directory for storing custom data files of the application. + * You can use the returned File object to create and access files in this directory. The files + * can be accessible only by the current application. + * + * @param name Indicates the name of the directory to retrieve. This directory is created as part + * of your application data. + * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE. + * + * @return Returns a File object for the requested directory. + */ +std::string ContextContainer::GetDir(const std::string &name, int mode) +{ + if (baseContext_ != nullptr) { + return baseContext_->GetDir(name, mode); + } else { + APP_LOGE("ContextContainer::GetDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the absolute path to the application-specific cache directory + * on the primary external or shared storage device. + * + * @return Returns the absolute path to the application-specific cache directory on the external or + * shared storage device; returns null if the external or shared storage device is temporarily unavailable. + */ +std::string ContextContainer::GetExternalCacheDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetExternalCacheDir(); + } else { + APP_LOGE("ContextContainer::GetExternalCacheDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the absolute path to the directory for storing files for the application on the + * primary external or shared storage device. + * + * @param type Indicates the type of the file directory to return + * + * @return Returns the absolute path to the application file directory on the external or shared storage + * device; returns null if the external or shared storage device is temporarily unavailable. + */ +std::string ContextContainer::GetExternalFilesDir(std::string &type) +{ + if (baseContext_ != nullptr) { + return baseContext_->GetExternalFilesDir(type); + } else { + APP_LOGE("ContextContainer::GetExternalFilesDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ +std::string ContextContainer::GetFilesDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetFilesDir(); + } else { + APP_LOGE("ContextContainer::GetFilesDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage. + * The returned path maybe changed if the application is moved to an adopted storage device. + * + * @return The path of the directory holding application files that will not be automatically backed up to remote + * storage. + */ +std::string ContextContainer::GetNoBackupFilesDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetNoBackupFilesDir(); + } else { + APP_LOGE("ContextContainer::GetNoBackupFilesDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Checks whether the calling process for inter-process communication has the given permission. + * The calling process is not the current process. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextContainer::VerifyCallingPermission(const std::string &permission) +{ + if (baseContext_ != nullptr) { + return baseContext_->VerifyCallingPermission(permission); + } else { + APP_LOGE("ContextContainer::VerifyCallingPermission baseContext_ is nullptr"); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + } +} + +/** + * @brief Checks whether the current process has the given permission. + * You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only + * if the current process does not have the specific permission. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextContainer::VerifySelfPermission(const std::string &permission) +{ + if (baseContext_ != nullptr) { + return baseContext_->VerifySelfPermission(permission); + } else { + APP_LOGE("ContextContainer::VerifySelfPermission baseContext_ is nullptr"); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + } +} + +/** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ +std::string ContextContainer::GetBundleName() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetBundleName(); + } else { + APP_LOGE("ContextContainer::GetBundleName baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability. + * + * @return Returns the path of the HAP containing this ability. + */ +std::string ContextContainer::GetBundleResourcePath() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetBundleResourcePath(); + } else { + APP_LOGE("ContextContainer::GetBundleResourcePath baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Remove permissions for all users who have access to specific permissions + * + * @param permission Indicates the permission to unauth. This parameter cannot be null. + * @param uri Indicates the URI to unauth. This parameter cannot be null. + * @param uid Indicates the UID of the unauth to check. + * + */ +void ContextContainer::UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) +{ + if (baseContext_ != nullptr) { + baseContext_->UnauthUriPermission(permission, uri, uid); + } else { + APP_LOGE("ContextContainer::UnauthUriPermission baseContext_ is nullptr"); + } +} + +/** + * @brief Obtains an ability manager. + * The ability manager provides information about running processes and memory usage of an application. + * + * @return Returns an IAbilityManager instance. + */ +sptr ContextContainer::GetAbilityManager() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetAbilityManager(); + } else { + APP_LOGE("ContextContainer::GetAbilityManager baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains the type of this application. + * + * @return Returns system if this application is a system application; + * returns normal if it is released in OHOS AppGallery; + * returns other if it is released by a third-party vendor; + * returns an empty string if the query fails. + */ +std::string ContextContainer::GetAppType() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetAppType(); + } else { + APP_LOGE("ContextContainer::GetAppType baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Confirms with the permission management module to check whether a request prompt is required for granting a + * certain permission. You need to call the current method to check whether a prompt is required before calling + * requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, permission + * request will not be initiated. + * + * @param requestCode Indicates the permission to be queried. This parameter cannot be null. + * + * @return Returns true if the current application does not have the permission and the user does not turn off further + * requests; returns false if the current application already has the permission, the permission is rejected by the + * system, or the permission is denied by the user and the user has turned off further requests. + */ +bool ContextContainer::CanRequestPermission(const std::string &permission) +{ + if (baseContext_ != nullptr) { + return baseContext_->CanRequestPermission(permission); + } else { + APP_LOGE("ContextContainer::CanRequestPermission baseContext_ is nullptr"); + return true; + } +} + +/** + * @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has + * permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextContainer::VerifyCallingOrSelfPermission(const std::string &permission) +{ + if (baseContext_ != nullptr) { + return baseContext_->VerifyCallingOrSelfPermission(permission); + } else { + APP_LOGE("ContextContainer::VerifyCallingOrSelfPermission baseContext_ is nullptr"); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + } +} + +/** + * @brief Query whether the application of the specified PID and UID has been granted a certain permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param pid Process id + * @param uid + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextContainer::VerifyPermission(const std::string &permission, int pid, int uid) +{ + if (baseContext_ != nullptr) { + return baseContext_->VerifyPermission(permission, pid, uid); + } else { + APP_LOGE("ContextContainer::VerifyPermission baseContext_ is nullptr"); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + } +} + +/** + * @brief Obtains the distributed file path. + * If the distributed file path does not exist, the system creates one and returns the created path. This method is + * applicable only to the context of an ability rather than that of an application. + * + * @return Returns the distributed file. + */ +std::string ContextContainer::GetDistributedDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetDistributedDir(); + } else { + APP_LOGE("ContextContainer::GetDistributedDir baseContext_ is nullptr"); + return ""; + } +} +/** + * @brief Sets the pattern of this Context based on the specified pattern ID. + * + * @param patternId Indicates the resource ID of the pattern to set. + */ +void ContextContainer::SetPattern(int patternId) +{ + if (baseContext_ != nullptr) { + baseContext_->SetPattern(patternId); + } else { + APP_LOGE("ContextContainer::SetPattern baseContext_ is nullptr"); + } +} + +/** + * @brief Obtains the Context object of this ability. + * + * @return Returns the Context object of this ability. + */ +std::shared_ptr ContextContainer::GetAbilityPackageContext() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetAbilityPackageContext(); + } else { + APP_LOGE("ContextContainer::GetAbilityPackageContext baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ +std::shared_ptr ContextContainer::GetHapModuleInfo() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetHapModuleInfo(); + } else { + APP_LOGE("ContextContainer::GetHapModuleInfo baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains the name of the current process. + * + * @return Returns the current process name. + */ +std::string ContextContainer::GetProcessName() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetProcessName(); + } else { + APP_LOGE("ContextContainer::GetProcessName baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Requests certain permissions from the system. + * This method is called for permission request. This is an asynchronous method. When it is executed, + * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, + * String[], int[]) callback method. This code cannot be a negative number. + * + */ +void ContextContainer::RequestPermissionsFromUser(std::vector &permissions, int requestCode) +{ + if (baseContext_ != nullptr) { + baseContext_->RequestPermissionsFromUser(permissions, requestCode); + } else { + APP_LOGE("ContextContainer::RequestPermissionsFromUser baseContext_ is nullptr"); + } +} + +/** + * @brief Creates a Context object for an application with the given bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * + * @param flag Indicates the flag for creating a Context object. It can be 0, any of + * the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY, + * CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction + * on creating contexts for applications. + * + * @return Returns a Context object created for the specified application. + */ +std::shared_ptr ContextContainer::CreateBundleContext(std::string bundleName, int flag) +{ + if (bundleName.empty()) { + APP_LOGE("ContextContainer::CreateBundleContext bundleName is empty"); + return nullptr; + } + + if (strcmp(bundleName.c_str(), GetBundleName().c_str()) == 0) { + return GetApplicationContext(); + } + + sptr bundleMgr = GetBundleManager(); + if (nullptr == bundleMgr) { + APP_LOGE("ContextContainer::CreateBundleContext GetBundleManager is nullptr"); + return nullptr; + } + + BundleInfo bundleInfo; + APP_LOGI("ContextContainer::CreateBundleContext length: %{public}zu, bundleName: %{public}s", + bundleName.length(), + bundleName.c_str()); + bundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, DEFAULT_USERID); + + if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) { + APP_LOGE("ContextContainer::CreateBundleContext GetBundleInfo is error"); + return nullptr; + } + + std::shared_ptr appContext = std::make_shared(); + if (appContext == nullptr) { + APP_LOGE("ContextContainer::CreateBundleContext appContext is nullptr"); + return nullptr; + } + std::shared_ptr deal = std::make_shared(); + if (deal == nullptr) { + APP_LOGE("ContextContainer::CreateBundleContext bundleName is empty"); + return nullptr; + } + + // init resourceManager. + InitResourceManager(bundleInfo, deal); + + deal->SetApplicationInfo(std::make_shared(bundleInfo.applicationInfo)); + appContext->AttachBaseContext(deal); + return appContext; +} + +void ContextContainer::InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr &deal) +{ + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (deal == nullptr || resourceManager == nullptr) { + APP_LOGE("ContextContainer::InitResourceManager create resourceManager failed"); + return; + } + + APP_LOGI( + "ContextContainer::InitResourceManager moduleResPaths count: %{public}zu", bundleInfo.moduleResPaths.size()); + for (auto moduleResPath : bundleInfo.moduleResPaths) { + if (!moduleResPath.empty()) { + APP_LOGI("ContextContainer::InitResourceManager length: %{public}zu, moduleResPath: %{public}s", + moduleResPath.length(), + moduleResPath.c_str()); + if (!resourceManager->AddResource(moduleResPath.c_str())) { + APP_LOGE("ContextContainer::InitResourceManager AddResource failed"); + } + } + } + + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + resConfig->SetLocaleInfo("zh", "Hans", "CN"); + if (resConfig->GetLocaleInfo() != nullptr) { + APP_LOGI("ContextContainer::InitResourceManager language: %{public}s, script: %{public}s, region: %{public}s,", + resConfig->GetLocaleInfo()->getLanguage(), + resConfig->GetLocaleInfo()->getScript(), + resConfig->GetLocaleInfo()->getCountry()); + } else { + APP_LOGI("ContextContainer::InitResourceManager language: GetLocaleInfo is null."); + } + resourceManager->UpdateResConfig(*resConfig); + deal->initResourceManager(resourceManager); +} +/** + * @brief Obtains information about the caller of this ability. + * + * @return Returns the caller information. + */ +Uri ContextContainer::GetCaller() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetCaller(); + } else { + APP_LOGE("ContextContainer::GetCaller baseContext_ is nullptr"); + Uri uri(""); + return uri; + } +} + +/** + * @brief Get the string of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string to get. + * + * @return Returns the string of this Context. + */ +std::string ContextContainer::GetString(int resId) +{ + if (baseContext_ != nullptr) { + std::string ret = baseContext_->GetString(resId); + return ret; + } else { + APP_LOGE("ContextContainer::GetString baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Get the string array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string array to get. + * + * @return Returns the string array of this Context. + */ +std::vector ContextContainer::GetStringArray(int resId) +{ + if (baseContext_ != nullptr) { + return baseContext_->GetStringArray(resId); + } else { + return std::vector(); + APP_LOGE("ContextContainer::GetStringArray baseContext_ is nullptr"); + } +} + +/** + * @brief Get the integer array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the integer array to get. + * + * @return Returns the integer array of this Context. + */ +std::vector ContextContainer::GetIntArray(int resId) +{ + if (baseContext_ != nullptr) { + return baseContext_->GetIntArray(resId); + } else { + APP_LOGE("ContextContainer::GetIntArray baseContext_ is nullptr"); + return std::vector(); + } +} + +/** + * @brief Obtains the theme of this Context. + * + * @return theme Returns the theme of this Context. + */ +std::map ContextContainer::GetTheme() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetTheme(); + } else { + APP_LOGE("ContextContainer::GetTheme baseContext_ is nullptr"); + return std::map(); + } +} + +/** + * @brief Sets the theme of this Context based on the specified theme ID. + * + * @param themeId Indicates the resource ID of the theme to set. + */ +void ContextContainer::SetTheme(int themeId) +{ + if (baseContext_ != nullptr) { + baseContext_->SetTheme(themeId); + } else { + APP_LOGE("ContextContainer::SetTheme baseContext_ is nullptr"); + } +} + +/** + * @brief Obtains the pattern of this Context. + * + * @return getPattern in interface Context + */ +std::map ContextContainer::GetPattern() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetPattern(); + } else { + APP_LOGE("ContextContainer::GetPattern baseContext_ is nullptr"); + return std::map(); + } +} + +/** + * @brief Get the color of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the color to get. + * + * @return Returns the color value of this Context. + */ +int ContextContainer::GetColor(int resId) +{ + if (baseContext_ != nullptr) { + return baseContext_->GetColor(resId); + } else { + APP_LOGE("ContextContainer::GetColor baseContext_ is nullptr"); + return INVALID_RESOURCE_VALUE; + } +} + +/** + * @brief Obtains the theme id of this Context. + * + * @return int Returns the theme id of this Context. + */ +int ContextContainer::GetThemeId() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetThemeId(); + } else { + APP_LOGE("ContextContainer::GetThemeId baseContext_ is nullptr"); + return -1; + } +} + +/** + * @brief Obtains the current display orientation of this ability. + * + * @return Returns the current display orientation. + */ +int ContextContainer::GetDisplayOrientation() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetDisplayOrientation(); + } else { + APP_LOGE("ContextContainer::GetDisplayOrientation baseContext_ is nullptr"); + return static_cast(DisplayOrientation::UNSPECIFIED); + } +} + +/** + * @brief Obtains the path storing the preference file of the application. + * If the preference file path does not exist, the system creates one and returns the created path. + * + * @return Returns the preference file path . + */ +std::string ContextContainer::GetPreferencesDir() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetPreferencesDir(); + } else { + APP_LOGE("ContextContainer::GetPreferencesDir baseContext_ is nullptr"); + return ""; + } +} + +/** + * @brief Set color mode + * + * @param the value of color mode. + */ +void ContextContainer::SetColorMode(int mode) +{ + if (baseContext_ == nullptr) { + APP_LOGE("ContextContainer::SetColorMode baseContext_ is nullptr"); + return; + } + + baseContext_->SetColorMode(mode); +} + +/** + * @brief Obtains color mode. + * + * @return Returns the color mode value. + */ +int ContextContainer::GetColorMode() +{ + if (baseContext_ == nullptr) { + APP_LOGE("ContextContainer::GetColorMode baseContext_ is nullptr"); + return -1; + } + + return baseContext_->GetColorMode(); +} + +/** + * @brief Obtains the unique ID of the mission containing this ability. + * + * @return Returns the unique mission ID. + */ +int ContextContainer::GetMissionId() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetMissionId(); + } else { + APP_LOGE("ContextContainer::GetMissionId baseContext_ is nullptr"); + return -1; + } +} + +/** + * @brief Call this when your ability should be closed and the mission should be completely removed as a part of + * finishing the root ability of the mission. + */ +void ContextContainer::TerminateAndRemoveMission() +{ + if (baseContext_ != nullptr) { + baseContext_->TerminateAndRemoveMission(); + } else { + APP_LOGE("ContextContainer::TerminateAndRemoveMission baseContext_ is nullptr"); + } +} + +/** + * @brief Obtains a task dispatcher that is bound to the UI thread. + * + * @return Returns the task dispatcher that is bound to the UI thread. + */ +std::shared_ptr ContextContainer::GetUITaskDispatcher() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetUITaskDispatcher(); + } else { + APP_LOGE("ContextContainer::GetUITaskDispatcher baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains a task dispatcher that is bound to the application main thread. + * + * @return Returns the task dispatcher that is bound to the application main thread. + */ +std::shared_ptr ContextContainer::GetMainTaskDispatcher() +{ + if (baseContext_ != nullptr) { + return baseContext_->GetMainTaskDispatcher(); + } else { + APP_LOGE("ContextContainer::GetMainTaskDispatcher baseContext_ is nullptr"); + return nullptr; + } +} +/** + * @brief Creates a parallel task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. + * + * @return Returns a parallel task dispatcher. + */ +std::shared_ptr ContextContainer::CreateParallelTaskDispatcher( + const std::string &name, const TaskPriority &priority) +{ + if (baseContext_ != nullptr) { + return baseContext_->CreateParallelTaskDispatcher(name, priority); + } else { + APP_LOGE("ContextContainer::CreateParallelTaskDispatcher baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Creates a serial task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. + * + * @return Returns a serial task dispatcher. + */ +std::shared_ptr ContextContainer::CreateSerialTaskDispatcher( + const std::string &name, const TaskPriority &priority) +{ + if (baseContext_ != nullptr) { + return baseContext_->CreateSerialTaskDispatcher(name, priority); + } else { + APP_LOGE("ContextContainer::CreateSerialTaskDispatcher baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Obtains a global task dispatcher with a specified priority. + * + * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. + * + * @return Returns a global task dispatcher. + */ +std::shared_ptr ContextContainer::GetGlobalTaskDispatcher(const TaskPriority &priority) +{ + if (baseContext_ != nullptr) { + return baseContext_->GetGlobalTaskDispatcher(priority); + } else { + APP_LOGE("ContextContainer::GetGlobalTaskDispatcher baseContext_ is nullptr"); + return nullptr; + } +} + +/** + * @brief Requires that tasks associated with a given capability token be moved to the background + * + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * + * @return Returns true on success, others on failure. + */ +bool ContextContainer::MoveMissionToEnd(bool nonFirst) +{ + sptr token = GetToken(); + if (token == nullptr) { + APP_LOGE("ContextContainer::MoveMissionToEnd GetToken return nullptr"); + return false; + } + + auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityClient == nullptr) { + APP_LOGE("ContextContainer::MoveMissionToEnd abilityClient is nullptr"); + return false; + } + + ErrCode errval = abilityClient->MoveMissionToEnd(token, nonFirst); + if (errval != ERR_OK) { + APP_LOGE("ContextContainer::MoveMissionToEnd MoveMissionToEnd retval is %d", errval); + } + + return (errval == ERR_OK) ? true : false; +} + +/** + * @brief Sets the application to start its ability in lock mission mode. + */ +void ContextContainer::LockMission() +{ + auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityClient == nullptr) { + APP_LOGE("ContextContainer::LockMission abilityClient is nullptr"); + return; + } + + ErrCode errval = abilityClient->LockMission(GetMissionId()); + if (errval != ERR_OK) { + APP_LOGE("ContextContainer::LockMission LockMission retval is %d", errval); + } +} + +/** + * @brief Unlocks this ability by exiting the lock mission mode. + */ +void ContextContainer::UnlockMission() +{ + auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityClient == nullptr) { + APP_LOGE("ContextContainer::UnlockMission abilityClient is nullptr"); + return; + } + + ErrCode errval = abilityClient->UnlockMission(GetMissionId()); + if (errval != ERR_OK) { + APP_LOGE("ContextContainer::UnlockMission UnlockMission retval is %d", errval); + } +} + +/** + * @brief Sets description information about the mission containing this ability. + * + * @param MissionInformation Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns true on success, others on failure. + */ +bool ContextContainer::SetMissionInformation(const MissionInformation &missionInformation) +{ + sptr token = GetToken(); + if (token == nullptr) { + APP_LOGE("ContextContainer::SetMissionInformation GetToken return nullptr"); + return false; + } + + auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityClient == nullptr) { + APP_LOGE("ContextContainer::SetMissionInformation abilityClient is nullptr"); + return false; + } + + AAFwk::MissionDescriptionInfo missionInfoMat; + missionInfoMat.label = missionInformation.label; + missionInfoMat.iconPath = missionInformation.iconPath; + + ErrCode errval = abilityClient->SetMissionDescriptionInfo(token, missionInfoMat); + if (errval != ERR_OK) { + APP_LOGE("ContextContainer::SetMissionInformation SetMissionDescriptionInfo retval is %d", errval); + } + + return (errval == ERR_OK) ? true : false; +} + +/** + * set lock screen white list + * + * @param isAllow Whether to allow lock screen. + * + */ +void ContextContainer::SetShowOnLockScreen(bool isAllow) +{ + if (baseContext_ == nullptr) { + APP_LOGE("ContextContainer::SetShowOnLockScreen baseContext_ is nullptr"); + return; + } + + baseContext_->SetShowOnLockScreen(isAllow); + APP_LOGI("ContextContainer::SetShowOnLockScreen called end."); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/context_deal.cpp b/frameworks/kits/appkit/native/app/src/context_deal.cpp new file mode 100755 index 0000000000000000000000000000000000000000..d03ffb4d5542ea851dbaaecba80f5d9b16b41e20 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/context_deal.cpp @@ -0,0 +1,1378 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "context_deal.h" +#include "ability_manager_client.h" +#include "ability_manager_interface.h" +#include "app_log_wrapper.h" +#include "application_context.h" +#include "directory_ex.h" +#include "file_ex.h" +#include "iservice_registry.h" +#include "spec_task_dispatcher.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" +#include "task_dispatcher_context.h" + +#define MODE 0771 +namespace OHOS { +namespace AppExecFwk { +const std::string ContextDeal::CONTEXT_DEAL_FILE_SEPARATOR("/"); +const std::string ContextDeal::CONTEXT_DEAL_CODE_CACHE("code_cache"); +const std::string ContextDeal::CONTEXT_DEAL_Files("files"); +const std::string ContextDeal::CONTEXT_DEAL_NO_BACKUP_Files("no_backup"); +const std::string ContextDeal::CONTEXT_DEAL_DIRNAME("preferences"); + +/** + * Called when getting the ProcessInfo + * + * @return ProcessInfo + */ +std::shared_ptr ContextDeal::GetProcessInfo() const +{ + return processInfo_; +} + +/** + * Called when setting the ProcessInfo + * + * @param info ProcessInfo instance + */ +void ContextDeal::SetProcessInfo(const std::shared_ptr &info) +{ + APP_LOGI("ContextDeal::SetProcessInfo begin"); + if (info == nullptr) { + APP_LOGE("ContextDeal::SetProcessInfo failed, info is empty"); + return; + } + APP_LOGI("ContextDeal::SetProcessInfo end"); + processInfo_ = info; +} + +/** + * @brief Obtains information about the current application. The returned application information includes basic + * information such as the application name and application permissions. + * + * @return Returns the ApplicationInfo for the current application. + */ +std::shared_ptr ContextDeal::GetApplicationInfo() const +{ + return applicationInfo_; +} + +/** + * @brief Set ApplicationInfo + * + * @param info ApplicationInfo instance. + */ +void ContextDeal::SetApplicationInfo(const std::shared_ptr &info) +{ + APP_LOGI("ContextDeal::SetApplicationInfo begin"); + if (info == nullptr) { + APP_LOGE("ContextDeal::SetApplicationInfo failed, info is empty"); + return; + } + applicationInfo_ = info; + APP_LOGI("ContextDeal::SetApplicationInfo end"); +} + +/** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ +std::shared_ptr ContextDeal::GetApplicationContext() const +{ + return appContext_; +} + +/** + * @brief Set ApplicationContext + * + * @param context ApplicationContext instance. + */ +void ContextDeal::SetApplicationContext(const std::shared_ptr &context) +{ + APP_LOGI("ContextDeal::SetApplicationContext begin"); + if (context == nullptr) { + APP_LOGE("ContextDeal::SetApplicationContext failed, context is empty"); + return; + } + appContext_ = context; + APP_LOGI("ContextDeal::SetApplicationContext end"); +} + +/** + * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, + * source code, and configuration files of a module. + * + * @return Returns the path of the package file. + */ +std::string ContextDeal::GetBundleCodePath() +{ + return (applicationInfo_ != nullptr) ? applicationInfo_->codePath : ""; +} + +/** + * @brief SetBundleCodePath + * + * @param Returns string path + */ +void ContextDeal::SetBundleCodePath(std::string &path) +{ + path_ = path; +} + +/** + * @brief Obtains information about the current ability. + * The returned information includes the class name, bundle name, and other information about the current ability. + * + * @return Returns the AbilityInfo object for the current ability. + */ +const std::shared_ptr ContextDeal::GetAbilityInfo() +{ + return abilityInfo_; +} + +/** + * @brief Set AbilityInfo + * + * @param info AbilityInfo instance. + */ +void ContextDeal::SetAbilityInfo(const std::shared_ptr &info) +{ + APP_LOGI("ContextDeal::SetAbilityInfo begin"); + if (info == nullptr) { + APP_LOGE("ContextDeal::SetAbilityInfo failed, info is empty"); + return; + } + abilityInfo_ = info; + APP_LOGI("ContextDeal::SetAbilityInfo end"); +} + +/** + * @brief Obtains the Context object of the ability. + * + * @return Returns the Context object of the ability. + */ +std::shared_ptr ContextDeal::GetContext() +{ + return abilityContext_; +} + +/** + * @brief Set Ability context + * + * @param context Ability object + */ +void ContextDeal::SetContext(const std::shared_ptr &context) +{ + APP_LOGI("ContextDeal::SetContext begin"); + if (context == nullptr) { + APP_LOGE("ContextDeal::SetContext failed, context is empty"); + return; + } + abilityContext_ = context; + APP_LOGI("ContextDeal::SetContext end"); +} + +/** + * @brief Obtains an IBundleMgr instance. + * You can use this instance to obtain information about the application bundle. + * + * @return Returns an IBundleMgr instance. + */ +sptr ContextDeal::GetBundleManager() const +{ + APP_LOGI("ContextDeal::GetBundleManager begin"); + auto bundleObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleObj == nullptr) { + APP_LOGE("failed to get bundle manager service"); + return nullptr; + } + APP_LOGI("ContextDeal::GetBundleManager before iface_cast"); + sptr bms = iface_cast(bundleObj); + APP_LOGI("ContextDeal::GetBundleManager after iface_cast"); + APP_LOGI("ContextDeal::GetBundleManager end"); + return bms; +} + +/** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ +std::shared_ptr ContextDeal::GetResourceManager() const +{ + return resourceManager_; +} + +/** + * @brief Set Profile instance. + * + * @param Profile instance. + */ +void ContextDeal::SetProfile(const std::shared_ptr &profile) +{ + APP_LOGI("ContextDeal::SetProfile begin"); + if (profile == nullptr) { + APP_LOGE("ContextDeal::SetProfile failed, profile is nullptr"); + return; + } + profile_ = profile; + APP_LOGI("ContextDeal::SetProfile end"); +} + +/** + * @brief Obtains an Profile instance. + * + * @return Returns an Profile instance. + */ +std::shared_ptr ContextDeal::GetProfile() const +{ + return profile_; +} + +/** + * @brief Deletes the specified private file associated with the application. + * + * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators. + * + * @return Returns true if the file is deleted successfully; returns false otherwise. + */ +bool ContextDeal::DeleteFile(const std::string &fileName) +{ + APP_LOGI("ContextDeal::DeleteFile begin"); + std::string path = GetDataDir() + CONTEXT_DEAL_FILE_SEPARATOR + fileName; + bool ret = OHOS::RemoveFile(path); + APP_LOGI("ContextDeal::DeleteFile end"); + return ret; +} + +/** + * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. + * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE + * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE + * template. The current ability itself can be destroyed by calling the terminateAbility() method. + * + * @param want Indicates the Want containing information about the ability to destroy. + * + * @return Returns true if the ability is destroyed successfully; returns false otherwise. + */ +bool ContextDeal::StopAbility(const AAFwk::Want &want) +{ + return false; +} + +/** + * @brief Obtains the application-specific cache directory on the device's internal storage. The system + * automatically deletes files from the cache directory if disk space is required elsewhere on the device. + * Older files are always deleted first. + * + * @return Returns the application-specific cache directory. + */ +std::string ContextDeal::GetCacheDir() +{ + return (applicationInfo_ != nullptr) ? applicationInfo_->cacheDir : ""; +} + +/** + * @brief Obtains the application-specific code-cache directory on the device's internal storage. + * The system will delete any files stored in this location both when your specific application is upgraded, + * and when the entire platform is upgraded. + * + * @return Returns the application-specific code-cache directory. + */ +std::string ContextDeal::GetCodeCacheDir() +{ + return (applicationInfo_ != nullptr) + ? (applicationInfo_->dataDir + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_CODE_CACHE) + : ""; +} + +/** + * @brief Obtains the local database path. + * If the local database path does not exist, the system creates one and returns the created path. + * + * @return Returns the local database file. + */ +std::string ContextDeal::GetDatabaseDir() +{ + return (applicationInfo_ != nullptr) ? applicationInfo_->dataBaseDir : ""; +} + +/** + * @brief Obtains the absolute path where all private data files of this application are stored. + * + * @return Returns the absolute path storing all private data files of this application. + */ +std::string ContextDeal::GetDataDir() +{ + return (applicationInfo_ != nullptr) ? applicationInfo_->dataDir : ""; +} + +/** + * @brief Obtains the directory for storing custom data files of the application. + * You can use the returned File object to create and access files in this directory. The files + * can be accessible only by the current application. + * + * @param name Indicates the name of the directory to retrieve. This directory is created as part + * of your application data. + * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE. + * + * @return Returns a File object for the requested directory. + */ +std::string ContextDeal::GetDir(const std::string &name, int mode) +{ + APP_LOGI("ContextDeal::GetDir begin"); + if (applicationInfo_ == nullptr) { + APP_LOGE("ContextDeal::GetDir failed, applicationInfo_ == nullptr"); + return ""; + } + std::string dir = applicationInfo_->dataDir + CONTEXT_DEAL_FILE_SEPARATOR + name; + if (!OHOS::FileExists(dir)) { + APP_LOGI("ContextDeal::GetDir File is not exits"); + OHOS::ForceCreateDirectory(dir); + OHOS::ChangeModeDirectory(dir, mode); + } + APP_LOGI("ContextDeal::GetDir end"); + return dir; +} + +/** + * @brief Obtains the absolute path to the application-specific cache directory + * on the primary external or shared storage device. + * + * @return Returns the absolute path to the application-specific cache directory on the external or + * shared storage device; returns null if the external or shared storage device is temporarily unavailable. + */ +std::string ContextDeal::GetExternalCacheDir() +{ + return ""; +} + +/** + * @brief Obtains the absolute path to the directory for storing files for the application on the + * primary external or shared storage device. + * + * @param type Indicates the type of the file directory to return + * + * @return Returns the absolute path to the application file directory on the external or shared storage + * device; returns null if the external or shared storage device is temporarily unavailable. + */ +std::string ContextDeal::GetExternalFilesDir(std::string &type) +{ + return ""; +} + +/** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ +std::string ContextDeal::GetFilesDir() +{ + return (applicationInfo_ != nullptr) + ? (applicationInfo_->dataDir + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_Files) + : ""; +} + +/** + * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage. + * The returned path maybe changed if the application is moved to an adopted storage device. + * + * @return The path of the directory holding application files that will not be automatically backed up to remote + * storage. + */ +std::string ContextDeal::GetNoBackupFilesDir() +{ + APP_LOGI("ContextDeal::GetNoBackupFilesDir begin"); + std::string dir = applicationInfo_->dataDir + CONTEXT_DEAL_NO_BACKUP_Files; + if (!OHOS::FileExists(dir)) { + APP_LOGI("ContextDeal::GetDir GetNoBackupFilesDir is not exits"); + OHOS::ForceCreateDirectory(dir); + OHOS::ChangeModeDirectory(dir, MODE); + } + APP_LOGI("ContextDeal::GetNoBackupFilesDir end"); + return dir; +} + +/** + * @brief Checks whether the calling process for inter-process communication has the given permission. + * The calling process is not the current process. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextDeal::VerifyCallingPermission(const std::string &permission) +{ + return 0; +} + +/** + * @brief Checks whether the current process has the given permission. + * You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only + * if the current process does not have the specific permission. + * + * @param permission Indicates the permission to check. This parameter cannot be null. + * + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextDeal::VerifySelfPermission(const std::string &permission) +{ + return 0; +} + +/** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ +std::string ContextDeal::GetBundleName() +{ + return (applicationInfo_ != nullptr) ? applicationInfo_->bundleName : ""; +} + +/** + * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability. + * + * @return Returns the path of the HAP containing this ability. + */ +std::string ContextDeal::GetBundleResourcePath() +{ + return (abilityInfo_ != nullptr) ? abilityInfo_->resourcePath : ""; +} + +/** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE + * template is started. You can define the request code to identify the results returned by abilities. The value + * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE + * template. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ContextDeal::StartAbility(const AAFwk::Want &want, int requestCode) +{ + APP_LOGI("ContextDeal::StartAbility is called"); + return ERR_INVALID_VALUE; +} + +/** + * @brief Remove permissions for all users who have access to specific permissions + * + * @param permission Indicates the permission to unauth. This parameter cannot be null. + * @param uri Indicates the URI to unauth. This parameter cannot be null. + * @param uid Indicates the UID of the unauth to check. + * + */ +void ContextDeal::UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) +{} + +/** + * @brief Obtains an ability manager. + * The ability manager provides information about running processes and memory usage of an application. + * + * @return Returns an IAbilityManager instance. + */ +sptr ContextDeal::GetAbilityManager() +{ + APP_LOGI("ContextDeal::GetAbilityManager begin"); + auto remoteObject = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + APP_LOGE("failed to get ability manager service"); + return nullptr; + } + APP_LOGI("ContextDeal::SetPattern before iface_cast"); + sptr ams = iface_cast(remoteObject); + APP_LOGI("ContextDeal::SetPattern after iface_cast"); + APP_LOGI("ContextDeal::GetAbilityManager end"); + return ams; +} + +/** + * @brief Obtains the type of this application. + * + * @return Returns system if this application is a system application; + * returns normal if it is released in OHOS AppGallery; + * returns other if it is released by a third-party vendor; + * returns an empty string if the query fails. + */ +std::string ContextDeal::GetAppType() +{ + APP_LOGI("ContextDeal::GetAppType begin"); + sptr ptr = GetBundleManager(); + if (ptr == nullptr) { + APP_LOGE("GetAppType failed to get bundle manager service"); + return ""; + } + std::string retString = ptr->GetAppType(applicationInfo_->bundleName); + APP_LOGI("ContextDeal::GetAppType end"); + return retString; +} + +/** + * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult + * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode passed. + * + * @param requestCode Indicates the request code passed for starting the ability. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ContextDeal::TerminateAbility(int requestCode) +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief Confirms with the permission management module to check whether a request prompt is required for granting a + * certain permission. You need to call the current method to check whether a prompt is required before calling + * requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, permission + * request will not be initiated. + * + * @param requestCode Indicates the permission to be queried. This parameter cannot be null. + * + * @return Returns true if the current application does not have the permission and the user does not turn off further + * requests; returns false if the current application already has the permission, the permission is rejected by the + * system, or the permission is denied by the user and the user has turned off further requests. + */ +bool ContextDeal::CanRequestPermission(const std::string &permission) +{ + return false; +} + +/** + * @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has + * permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextDeal::VerifyCallingOrSelfPermission(const std::string &permission) +{ + return 0; +} + +/** + * @brief Query whether the application of the specified PID and UID has been granted a certain permission + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param pid Process id + * @param uid + * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; + * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. + */ +int ContextDeal::VerifyPermission(const std::string &permission, int pid, int uid) +{ + return 0; +} + +/** + * @brief Obtains the distributed file path. + * If the distributed file path does not exist, the system creates one and returns the created path. This method is + * applicable only to the context of an ability rather than that of an application. + * + * @return Returns the distributed file. + */ +std::string ContextDeal::GetDistributedDir() +{ + return ""; +} +/** + * @brief Sets the pattern of this Context based on the specified pattern ID. + * + * @param patternId Indicates the resource ID of the pattern to set. + */ +void ContextDeal::SetPattern(int patternId) +{ + APP_LOGI("ContextDeal::SetPattern begin"); + if (resourceManager_ != nullptr) { + if (!pattern_.empty()) { + pattern_.clear(); + } + APP_LOGI("ContextDeal::SetPattern before resourceManager_->GetPatternById"); + OHOS::Global::Resource::RState errval = resourceManager_->GetPatternById(patternId, pattern_); + APP_LOGI("ContextDeal::SetPattern after resourceManager_->GetPatternById"); + if (errval != OHOS::Global::Resource::RState::SUCCESS) { + APP_LOGE("ContextDeal::SetPattern GetPatternById(patternId:%d) retval is %u", patternId, errval); + } + } else { + APP_LOGE("ContextDeal::SetPattern resourceManager_ is nullptr"); + } + APP_LOGI("ContextDeal::SetPattern end"); +} + +/** + * @brief Obtains the Context object of this ability. + * + * @return Returns the Context object of this ability. + */ +std::shared_ptr ContextDeal::GetAbilityPackageContext() +{ + return nullptr; +} + +/** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ +std::shared_ptr ContextDeal::GetHapModuleInfo() +{ + // fix set HapModuleInfoLocal data failed, request only once + if (hapModuleInfoLocal_ == nullptr) { + HapModuleInfoRequestInit(); + } + + return hapModuleInfoLocal_; +} + +/** + * @brief Obtains the name of the current process. + * + * @return Returns the current process name. + */ +std::string ContextDeal::GetProcessName() +{ + return (processInfo_ != nullptr) ? processInfo_->GetProcessName() : ""; +} + +/** + * @brief Obtains the bundle name of the ability that called the current ability. + * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will + * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int, + * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned. + * + * @return Returns the bundle name of the calling ability; returns null if no calling ability is available. + */ +std::string ContextDeal::GetCallingBundle() +{ + return ""; +} + +/** + * @brief Requests certain permissions from the system. + * This method is called for permission request. This is an asynchronous method. When it is executed, + * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. + * + * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. + * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, + * String[], int[]) callback method. This code cannot be a negative number. + * + */ +void ContextDeal::RequestPermissionsFromUser(std::vector &permissions, int requestCode) +{} + +/** + * @brief Starts a new ability with special ability start setting. + * + * @param want Indicates the Want containing information about the target ability to start. + * @param requestCode Indicates the request code returned after the ability is started. You can define the request code + * to identify the results returned by abilities. The value ranges from 0 to 65535. + * @param abilityStartSetting Indicates the special start setting used in starting ability. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ContextDeal::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief Destroys the current ability. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ContextDeal::TerminateAbility() +{ + return ERR_INVALID_VALUE; +} + +/** + * @brief Connects the current ability to an ability + * + * @param want Indicates the want containing information about the ability to connect + * + * @param conn Indicates the callback object when the target ability is connected. + * + * @return True means success and false means failure + */ +bool ContextDeal::ConnectAbility(const Want &want, const sptr &conn) +{ + return false; +} + +/** + * @brief Disconnects the current ability from an ability + * + * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection + * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. + * + * @return errCode ERR_OK on success, others on failure. + */ +ErrCode ContextDeal::DisconnectAbility(const sptr &conn) +{ + return ERR_INVALID_VALUE; +} + +sptr ContextDeal::GetToken() +{ + return nullptr; +} + +/** + * @brief init the ResourceManager for ContextDeal. + * + * @param the ResourceManager has been inited. + * + */ +void ContextDeal::initResourceManager(const std::shared_ptr &resourceManager) +{ + APP_LOGI("ContextDeal::initResourceManager. Start."); + resourceManager_ = resourceManager; + APP_LOGI("ContextDeal::initResourceManager. End."); +} + +/** + * @brief Obtains information about the caller of this ability. + * + * @return Returns the caller information. + */ +Uri ContextDeal::GetCaller() +{ + Uri uri(uriString_); + return uri; +} + +/** + * @brief SerUriString + */ +void ContextDeal::SerUriString(const std::string &uri) +{ + uriString_ = uri; +} + +/** + * @brief Get the string of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string to get. + * + * @return Returns the string of this Context. + */ +std::string ContextDeal::GetString(int resId) +{ + APP_LOGI("ContextDeal::GetString begin"); + if (resourceManager_ == nullptr) { + APP_LOGE("ContextDeal::GetString resourceManager_ is nullptr"); + return ""; + } + + std::string ret; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetStringById"); + OHOS::Global::Resource::RState errval = resourceManager_->GetStringById(resId, ret); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetStringById"); + if (errval == OHOS::Global::Resource::RState::SUCCESS) { + return ret; + } else { + APP_LOGE("ContextDeal::GetString GetStringById(resId:%d) retval is %u", resId, errval); + return ""; + } + APP_LOGI("ContextDeal::GetString end"); +} + +/** + * @brief Get the string array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the string array to get. + * + * @return Returns the string array of this Context. + */ +std::vector ContextDeal::GetStringArray(int resId) +{ + APP_LOGI("ContextDeal::GetStringArray begin"); + if (resourceManager_ == nullptr) { + APP_LOGE("ContextDeal::GetStringArray resourceManager_ is nullptr"); + return std::vector(); + } + + std::vector retv; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetStringArrayById"); + OHOS::Global::Resource::RState errval = resourceManager_->GetStringArrayById(resId, retv); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetStringArrayById"); + if (errval == OHOS::Global::Resource::RState::SUCCESS) { + return retv; + } else { + APP_LOGE("ContextDeal::GetStringArray GetStringArrayById(resId:%d) retval is %u", resId, errval); + return std::vector(); + } + APP_LOGI("ContextDeal::GetStringArray end"); +} + +/** + * @brief Get the integer array of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the integer array to get. + * + * @return Returns the integer array of this Context. + */ +std::vector ContextDeal::GetIntArray(int resId) +{ + APP_LOGI("ContextDeal::GetIntArray begin"); + if (resourceManager_ == nullptr) { + APP_LOGE("ContextDeal::GetIntArray resourceManager_ is nullptr"); + return std::vector(); + } + + std::vector retv; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetIntArrayById"); + OHOS::Global::Resource::RState errval = resourceManager_->GetIntArrayById(resId, retv); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetIntArrayById"); + if (errval == OHOS::Global::Resource::RState::SUCCESS) { + return retv; + } else { + APP_LOGE("ContextDeal::GetIntArray GetIntArrayById(resId:%d) retval is %u", resId, errval); + return std::vector(); + } + APP_LOGI("ContextDeal::GetIntArray end"); +} + +/** + * @brief Obtains the theme of this Context. + * + * @return theme Returns the theme of this Context. + */ +std::map ContextDeal::GetTheme() +{ + APP_LOGI("ContextDeal::GetTheme begin"); + if (theme_.empty()) { + SetTheme(GetThemeId()); + } + APP_LOGI("ContextDeal::GetTheme end"); + return theme_; +} + +/** + * @brief Sets the theme of this Context based on the specified theme ID. + * + * @param themeId Indicates the resource ID of the theme to set. + */ +void ContextDeal::SetTheme(int themeId) +{ + APP_LOGI("ContextDeal::SetTheme begin"); + if (resourceManager_ == nullptr) { + APP_LOGE("ContextDeal::SetTheme resourceManager_ is nullptr"); + return; + } + + auto hapModInfo = GetHapModuleInfo(); + if (hapModInfo == nullptr) { + APP_LOGE("ContextDeal::SetTheme hapModInfo is nullptr"); + return; + } + + if (!theme_.empty()) { + theme_.clear(); + } + APP_LOGI("ContextDeal::GetString before resourceManager_->GetThemeById"); + OHOS::Global::Resource::RState errval = resourceManager_->GetThemeById(themeId, theme_); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetThemeById"); + if (errval != OHOS::Global::Resource::RState::SUCCESS) { + APP_LOGE("ContextDeal::SetTheme GetThemeById(themeId:%d) retval is %u", themeId, errval); + return; + } + + APP_LOGI("ContextDeal::SetTheme end"); + return; +} + +/** + * @brief Obtains the pattern of this Context. + * + * @return getPattern in interface Context + */ +std::map ContextDeal::GetPattern() +{ + APP_LOGI("ContextDeal::GetPattern begin"); + if (!pattern_.empty()) { + APP_LOGI("ContextDeal::GetPattern end"); + return pattern_; + } else { + APP_LOGE("ContextDeal::GetPattern pattern_ is empty"); + return std::map(); + } +} + +/** + * @brief Get the color of this Context based on the specified resource ID. + * + * @param resId Indicates the resource ID of the color to get. + * + * @return Returns the color value of this Context. + */ +int ContextDeal::GetColor(int resId) +{ + APP_LOGI("ContextDeal::GetColor begin"); + if (resourceManager_ == nullptr) { + APP_LOGE("ContextDeal::GetColor resourceManager_ is nullptr"); + return INVALID_RESOURCE_VALUE; + } + + uint32_t ret = INVALID_RESOURCE_VALUE; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetColorById"); + OHOS::Global::Resource::RState errval = resourceManager_->GetColorById(resId, ret); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetColorById"); + if (errval == OHOS::Global::Resource::RState::SUCCESS) { + return ret; + } else { + APP_LOGE("ContextDeal::GetColor GetColorById(resId:%d) retval is %u", resId, errval); + return INVALID_RESOURCE_VALUE; + } + APP_LOGI("ContextDeal::GetColor end"); +} + +/** + * @brief Obtains the theme id of this Context. + * + * @return int Returns the theme id of this Context. + */ +int ContextDeal::GetThemeId() +{ + auto hapModInfo = GetHapModuleInfo(); + if (hapModInfo != nullptr) { + return -1; + } else { + APP_LOGE("ContextDeal::GetThemeId hapModInfo is nullptr"); + return -1; + } +} + +/** + * @brief + * Destroys this Service ability if the number of times it has been started equals the number represented by the + * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service + * ability, except that this method helps you avoid destroying it if a client has requested a Service + * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it. + * + * @param startId Indicates the number of startup times of this Service ability passed to + * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is + * incremented by 1 every time this ability is started. For example, + * if this ability has been started for six times, the value of {@code startId} is {@code 6}. + * + * @return Returns {@code true} if the {@code startId} matches the number of startup times + * and this Service ability will be destroyed; returns {@code false} otherwise. + */ +bool ContextDeal::TerminateAbilityResult(int startId) +{ + return false; +} + +/** + * @brief Obtains the current display orientation of this ability. + * + * @return Returns the current display orientation. + */ +int ContextDeal::GetDisplayOrientation() +{ + APP_LOGI("ContextDeal::GetDisplayOrientation begin"); + if (abilityInfo_ != nullptr) { + APP_LOGI("ContextDeal::GetDisplayOrientation end"); + return static_cast(abilityInfo_->orientation); + } else { + APP_LOGE("ContextDeal::GetDisplayOrientation abilityInfo_ is nullptr"); + return static_cast(DisplayOrientation::UNSPECIFIED); + } +} + +/** + * @brief Obtains the path storing the preference file of the application. + * If the preference file path does not exist, the system creates one and returns the created path. + * + * @return Returns the preference file path . + */ +std::string ContextDeal::GetPreferencesDir() +{ + APP_LOGI("ContextDeal::GetPreferencesDir begin"); + if (!preferenceDir_.empty()) { + return preferenceDir_; + } + + if (abilityInfo_ == nullptr || applicationInfo_ == nullptr) { + APP_LOGE("ContextDeal::GetPreferencesDir %s is nullptr", + (abilityInfo_ == nullptr) ? "abilityInfo_" : "applicationInfo_"); + return ""; + } + + std::string abilityDirectoryName = ""; + if (abilityInfo_->isNativeAbility) { // Native Interface corresponding IX-1038 + abilityDirectoryName = abilityInfo_->name; + } else { + std::string abilityname = abilityInfo_->name; + size_t findpos = abilityname.find_last_of("."); + if (findpos == std::string::npos) { + APP_LOGE("ContextDeal::GetPreferencesDir Find last of string failed."); + return ""; + } + + abilityDirectoryName = abilityname.substr(findpos + 1, abilityname.length()); + if (abilityDirectoryName == "") { + APP_LOGE("ContextDeal::GetPreferencesDir abilityDirectoryName is nullptr"); + return ""; + } + } + + std::string dataDir = applicationInfo_->dataDir + CONTEXT_DEAL_FILE_SEPARATOR + abilityDirectoryName + + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_DIRNAME; + + if (!OHOS::FileExists(dataDir)) { + APP_LOGI("ContextDeal::GetPreferencesDir File is not exits. Bengin create"); + if (!OHOS::ForceCreateDirectory(dataDir)) { + APP_LOGE("ContextDeal::GetPreferencesDir ForceCreateDirectory return false. Create failed"); + return ""; + } + if (!OHOS::ChangeModeDirectory(dataDir, MODE)) { + APP_LOGW("ContextDeal::GetPreferencesDir ChangeModeDirectory(%s, 0771) return false. Change failed", + dataDir.c_str()); + } + APP_LOGI("ContextDeal::GetPreferencesDir File create complete"); + } + + preferenceDir_ = dataDir; + APP_LOGI("ContextDeal::GetPreferencesDir end"); + return preferenceDir_; +} + +/** + * @brief Set color mode + * + * @param the value of color mode. + */ +void ContextDeal::SetColorMode(int mode) +{ + APP_LOGI("ContextDeal::SetColorMode begin"); + auto hapModInfo = GetHapModuleInfo(); + if (hapModInfo == nullptr) { + APP_LOGE("ContextDeal::SetColorMode hapModInfo is nullptr"); + return; + } + + if (mode == static_cast(ModuleColorMode::DARK)) { + hapModInfo->colorMode = ModuleColorMode::DARK; + } else if (mode == static_cast(ModuleColorMode::LIGHT)) { + hapModInfo->colorMode = ModuleColorMode::LIGHT; + } else { // default use AUTO + hapModInfo->colorMode = ModuleColorMode::AUTO; + } + APP_LOGI("ContextDeal::SetColorMode end"); +} + +/** + * @brief Obtains color mode. + * + * @return Returns the color mode value. + */ +int ContextDeal::GetColorMode() +{ + APP_LOGI("ContextDeal::GetColorMode begin"); + auto hapModInfo = GetHapModuleInfo(); + if (hapModInfo == nullptr) { + APP_LOGE("ContextDeal::GetColorMode hapModInfo is nullptr"); + return -1; + } + APP_LOGI("ContextDeal::GetColorMode end"); + return static_cast(hapModInfo->colorMode); +} + +/** + * @brief Set the LifeCycleStateInfo to the deal. + * + * @param info the info to set. + */ +void ContextDeal::SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info) +{ + lifeCycleStateInfo_ = info; +} + +/** + * @brief Obtains the unique ID of the mission containing this ability. + * + * @return Returns the unique mission ID. + */ +int ContextDeal::GetMissionId() +{ + return lifeCycleStateInfo_.missionId; +} + +/** + * @brief Obtains the lifecycle state info. + * + * @return Returns the lifecycle state info. + */ +AAFwk::LifeCycleStateInfo ContextDeal::GetLifeCycleStateInfo() const +{ + return lifeCycleStateInfo_; +} + +/** + * @brief Call this when your ability should be closed and the mission should be completely removed as a part of + * finishing the root ability of the mission. + */ +void ContextDeal::TerminateAndRemoveMission() +{ + APP_LOGI("ContextDeal::TerminateAndRemoveMission begin"); + auto abilityManagerClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityManagerClient == nullptr) { + APP_LOGE("ContextDeal::TerminateAndRemoveMission abilityManagerClient is nullptr"); + return; + } + + std::vector removeIdList = {GetMissionId()}; + APP_LOGI("ContextDeal::TerminateAndRemoveMission before abilityManagerClient->RemoveMissions"); + ErrCode errval = abilityManagerClient->RemoveMissions(removeIdList); + APP_LOGI("ContextDeal::TerminateAndRemoveMission after abilityManagerClient->RemoveMissions"); + if (errval != ERR_OK) { + APP_LOGW("ContextDeal::TerminateAndRemoveMission RemoveMissions retval is ERROR(%d)", errval); + } + APP_LOGI("ContextDeal::TerminateAndRemoveMission end"); +} + +/** + * @brief Starts multiple abilities. + * + * @param wants Indicates the Want containing information array about the target ability to start. + */ +void ContextDeal::StartAbilities(const std::vector &wants) +{} + +/** + * @brief Checks whether this ability is the first ability in a mission. + * + * @return Returns true is first in Mission. + */ +bool ContextDeal::IsFirstInMission() +{ + return false; +} + +/** + * @brief Obtains a task dispatcher that is bound to the UI thread. + * + * @return Returns the task dispatcher that is bound to the UI thread. + */ +std::shared_ptr ContextDeal::GetUITaskDispatcher() +{ + return ContextDeal::GetMainTaskDispatcher(); +} + +/** + * @brief Obtains a task dispatcher that is bound to the application main thread. + * + * @return Returns the task dispatcher that is bound to the application main thread. + */ +std::shared_ptr ContextDeal::GetMainTaskDispatcher() +{ + APP_LOGI("ContextDeal::GetMainTaskDispatcher begin"); + if (mainTaskDispatcher_ != nullptr) { + return mainTaskDispatcher_; + } + + if (mainEventRunner_ == nullptr) { + APP_LOGE("ContextDeal::GetMainTaskDispatcher mainTaskDispatcher_ is nullptr"); + return nullptr; + } + + std::shared_ptr config = + std::make_shared(SpecDispatcherConfig::MAIN, TaskPriority::HIGH); + if (config == nullptr) { + APP_LOGE("ContextDeal::GetMainTaskDispatcher config is nullptr"); + return nullptr; + } + + mainTaskDispatcher_ = std::make_shared(config, mainEventRunner_); + APP_LOGI("ContextDeal::GetMainTaskDispatcher end"); + return mainTaskDispatcher_; +} + +/** + * @brief Creates a parallel task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. + * + * @return Returns a parallel task dispatcher. + */ +std::shared_ptr ContextDeal::CreateParallelTaskDispatcher( + const std::string &name, const TaskPriority &priority) +{ + APP_LOGI("ContextDeal::CreateParallelTaskDispatcher begin"); + if (appContext_ == nullptr) { + APP_LOGE("ContextDeal::CreateParallelTaskDispatcher appContext_ is nullptr"); + return nullptr; + } + + std::shared_ptr task = appContext_->CreateParallelTaskDispatcher(name, priority); + APP_LOGI("ContextDeal::CreateParallelTaskDispatcher end"); + return task; +} + +/** + * @brief Creates a serial task dispatcher with a specified priority. + * + * @param name Indicates the task dispatcher name. This parameter is used to locate problems. + * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. + * + * @return Returns a serial task dispatcher. + */ +std::shared_ptr ContextDeal::CreateSerialTaskDispatcher( + const std::string &name, const TaskPriority &priority) +{ + APP_LOGI("ContextDeal::CreateSerialTaskDispatcher begin"); + if (appContext_ == nullptr) { + APP_LOGE("ContextDeal::CreateSerialTaskDispatcher appContext_ is nullptr"); + return nullptr; + } + + std::shared_ptr task = appContext_->CreateSerialTaskDispatcher(name, priority); + APP_LOGI("ContextDeal::CreateSerialTaskDispatcher end"); + return task; +} + +/** + * @brief Obtains a global task dispatcher with a specified priority. + * + * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. + * + * @return Returns a global task dispatcher. + */ +std::shared_ptr ContextDeal::GetGlobalTaskDispatcher(const TaskPriority &priority) +{ + APP_LOGI("ContextDeal::GetGlobalTaskDispatcher begin"); + if (appContext_ == nullptr) { + APP_LOGE("ContextDeal::GetGlobalTaskDispatcher appContext_ is nullptr"); + return nullptr; + } + + std::shared_ptr task = appContext_->GetGlobalTaskDispatcher(priority); + APP_LOGI("ContextDeal::GetGlobalTaskDispatcher end"); + return task; +} + +/** + * @brief Set EventRunner for main thread. + * + * @param runner The EventRunner. + */ +void ContextDeal::SetRunner(const std::shared_ptr &runner) +{ + mainEventRunner_ = runner; +} + +/** + * @brief init HapModuleInfo data + * + * @return Returns true on success, others on failure. + */ +bool ContextDeal::HapModuleInfoRequestInit() +{ + APP_LOGI("ContextDeal::HapModuleInfoRequestInit begin"); + + sptr ptr = GetBundleManager(); + if (ptr == nullptr) { + APP_LOGE("GetHapModuleInfo failed to get bundle manager service"); + return false; + } + + if (abilityInfo_ == nullptr) { + APP_LOGE("GetHapModuleInfo failed for abilityInfo_ is nullptr"); + return false; + } + + hapModuleInfoLocal_ = std::make_shared(); + APP_LOGI("ContextDeal::HapModuleInfoRequestInit before IBundleMgr->GetBundleManager"); + if (!ptr->GetHapModuleInfo(*abilityInfo_.get(), *hapModuleInfoLocal_)) { + APP_LOGE("IBundleMgr::GetHapModuleInfo failed, will retval false value"); + return false; + } + APP_LOGI("ContextDeal::HapModuleInfoRequestInit after IBundleMgr->GetBundleManager"); + APP_LOGI("ContextDeal::HapModuleInfoRequestInit end"); + return true; +} + +/** + * @brief Requires that tasks associated with a given capability token be moved to the background + * + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * + * @return Returns true on success, others on failure. + */ +bool ContextDeal::MoveMissionToEnd(bool nonFirst) +{ + return false; +} + +/** + * @brief Sets the application to start its ability in lock mission mode. + */ +void ContextDeal::LockMission() +{} + +/** + * @brief Unlocks this ability by exiting the lock mission mode. + */ +void ContextDeal::UnlockMission() +{} + +/** + * @brief Sets description information about the mission containing this ability. + * + * @param MissionInformation Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns true on success, others on failure. + */ +bool ContextDeal::SetMissionInformation(const MissionInformation &missionInformation) +{ + return false; +} + +/** + * set lock screen white list + * + * @param isAllow Whether to allow lock screen. + * + */ +void ContextDeal::SetShowOnLockScreen(bool isAllow) +{ + auto abilityManagerClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityManagerClient == nullptr) { + APP_LOGE("ContextDeal::SetShowOnLockScreen abilityManagerClient is nullptr"); + return; + } + ErrCode errval = abilityManagerClient->SetShowOnLockScreen(isAllow); + if (errval != ERR_OK) { + APP_LOGE("ContextDeal::SetShowOnLockScreen SetShowOnLockScreen retval is ERROR(%d)", errval); + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/src/main.cpp b/frameworks/kits/appkit/native/app/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96355533a0a42ae9d63f395643311709e2fdbed4 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/main.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_thread.h" +#include "app_log_wrapper.h" + +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +int main(const int argc, const char *argv[]) +{ + MainThread::Start(); + return 0; +} diff --git a/frameworks/kits/appkit/native/app/src/main_thread.cpp b/frameworks/kits/appkit/native/app/src/main_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30cd950a89cae2bd96cbe1099fbd6eed76fdbd98 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/main_thread.cpp @@ -0,0 +1,1671 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_thread.h" + +#include + +#include "ability_delegator.h" +#include "ability_delegator_registry.h" +#include "ability_loader.h" +#include "ability_thread.h" +#include "app_loader.h" +#include "app_log_wrapper.h" +#include "application_env_impl.h" +#include "bytrace.h" +#include "context_deal.h" +#include "context_impl.h" +#include "extension_module_loader.h" +#include "form_extension.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "js_runtime.h" +#include "locale_config.h" +#include "ohos_application.h" +#include "resource_manager.h" +#include "runtime.h" +#include "service_extension.h" +#include "static_subscriber_extension.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" +#include "task_handler_client.h" +#include "faultloggerd_client.h" +#include "dfx_dump_catcher.h" + +#if defined(ABILITY_LIBRARY_LOADER) || defined(APPLICATION_LIBRARY_LOADER) +#include +#include +#endif + +namespace OHOS { +namespace AppExecFwk { +std::shared_ptr MainThread::applicationForAnr_ = nullptr; +namespace { +constexpr int32_t DELIVERY_TIME = 200; +constexpr int32_t DISTRIBUTE_TIME = 100; +} + +#define ACEABILITY_LIBRARY_LOADER +#ifdef ABILITY_LIBRARY_LOADER +#endif + +/** + * + * @brief Notify the AppMgrDeathRecipient that the remote is dead. + * + * @param remote The remote whitch is dead. + */ +void AppMgrDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGE("MainThread::AppMgrDeathRecipient remote died receive"); +} + +MainThread::MainThread() +{ +#ifdef ABILITY_LIBRARY_LOADER + fileEntries_.clear(); + handleAbilityLib_.clear(); +#endif // ABILITY_LIBRARY_LOADER +} + +MainThread::~MainThread() +{ +#ifdef ABILITY_LIBRARY_LOADER + CloseAbilityLibrary(); +#endif // ABILITY_LIBRARY_LOADER +} + +/** + * + * @brief Get the current MainThreadState. + * + * @return Returns the current MainThreadState. + */ +MainThreadState MainThread::GetMainThreadState() const +{ + return mainThreadState_; +} + +/** + * + * @brief Set the runner state of mainthread. + * + * @param runnerStart whether the runner is started. + */ +void MainThread::SetRunnerStarted(bool runnerStart) +{ + isRunnerStarted_ = runnerStart; +} + +/** + * + * @brief Get the runner state of mainthread. + * + * @return Returns the runner state of mainthread. + */ +bool MainThread::GetRunnerStarted() const +{ + return isRunnerStarted_; +} + +/** + * + * @brief Get the newThreadId. + * + * @return Returns the newThreadId. + */ +int MainThread::GetNewThreadId() +{ + return newThreadId_++; +} + +/** + * + * @brief Get the application. + * + * @return Returns the application. + */ +std::shared_ptr MainThread::GetApplication() const +{ + return application_; +} + +/** + * + * @brief Get the applicationInfo. + * + * @return Returns the applicationInfo. + */ +std::shared_ptr MainThread::GetApplicationInfo() const +{ + return applicationInfo_; +} + +/** + * + * @brief Get the applicationImpl. + * + * @return Returns the applicationImpl. + */ +std::shared_ptr MainThread::GetApplicationImpl() +{ + return applicationImpl_; +} + +/** + * + * @brief Connect the mainthread to the AppMgr. + * + */ +bool MainThread::ConnectToAppMgr() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::ConnectToAppMgr start"); + auto object = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); + if (object == nullptr) { + APP_LOGE("failed to get app manager service"); + return false; + } + deathRecipient_ = new (std::nothrow) AppMgrDeathRecipient(); + if (deathRecipient_ == nullptr) { + APP_LOGE("failed to new AppMgrDeathRecipient"); + return false; + } + + APP_LOGI("%{public}s, Start calling AddDeathRecipient.", __func__); + if (!object->AddDeathRecipient(deathRecipient_)) { + APP_LOGE("failed to AddDeathRecipient"); + return false; + } + APP_LOGI("%{public}s, End calling AddDeathRecipient.", __func__); + + appMgr_ = iface_cast(object); + if (appMgr_ == nullptr) { + APP_LOGE("failed to iface_cast object to appMgr_"); + return false; + } + APP_LOGI("MainThread::connectToAppMgr before AttachApplication"); + appMgr_->AttachApplication(this); + APP_LOGI("MainThread::connectToAppMgr after AttachApplication"); + return true; +} + +/** + * + * @brief Attach the mainthread to the AppMgr. + * + */ +void MainThread::Attach() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::attach called"); + if (!ConnectToAppMgr()) { + APP_LOGE("attachApplication failed"); + return; + } + mainThreadState_ = MainThreadState::ATTACH; + APP_LOGI("MainThread::attach mainThreadState: %{public}d", mainThreadState_); +} + +/** + * + * @brief remove the deathRecipient from appMgr. + * + */ +void MainThread::RemoveAppMgrDeathRecipient() +{ + APP_LOGI("MainThread::RemoveAppMgrDeathRecipient called begin"); + if (appMgr_ == nullptr) { + APP_LOGE("MainThread::RemoveAppMgrDeathRecipient failed"); + return; + } + + sptr object = appMgr_->AsObject(); + if (object != nullptr) { + APP_LOGI("%{public}s called. Start calling RemoveDeathRecipient.", __func__); + object->RemoveDeathRecipient(deathRecipient_); + APP_LOGI("%{public}s called. End calling RemoveDeathRecipient.", __func__); + } else { + APP_LOGE("appMgr_->AsObject() failed"); + } + APP_LOGI("%{public}s called end.", __func__); +} + +/** + * + * @brief Get the eventHandler of mainthread. + * + * @return Returns the eventHandler of mainthread. + */ +std::shared_ptr MainThread::GetMainHandler() const +{ + return mainHandler_; +} + +/** + * + * @brief Schedule the foreground lifecycle of application. + * + */ +void MainThread::ScheduleForegroundApplication() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::scheduleForegroundApplication called begin"); + wptr weak = this; + auto task = [weak]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleForegroundApplication failed."); + return; + } + appThread->HandleForegroundApplication(); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("PostTask task failed"); + } + APP_LOGI("MainThread::scheduleForegroundApplication called end."); +} + +/** + * + * @brief Schedule the background lifecycle of application. + * + */ +void MainThread::ScheduleBackgroundApplication() +{ + APP_LOGI("MainThread::scheduleBackgroundApplication called begin"); + wptr weak = this; + auto task = [weak]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleBackgroundApplication failed."); + return; + } + appThread->HandleBackgroundApplication(); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleBackgroundApplication PostTask task failed"); + } + APP_LOGI("MainThread::scheduleBackgroundApplication called end."); +} + +/** + * + * @brief Schedule the terminate lifecycle of application. + * + */ +void MainThread::ScheduleTerminateApplication() +{ + APP_LOGI("MainThread::scheduleTerminateApplication called begin"); + wptr weak = this; + auto task = [weak]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleTerminateApplication failed."); + return; + } + appThread->HandleTerminateApplication(); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleTerminateApplication PostTask task failed"); + } + APP_LOGI("MainThread::scheduleTerminateApplication called."); +} + +/** + * + * @brief Shrink the memory whitch used by application. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + */ +void MainThread::ScheduleShrinkMemory(const int level) +{ + APP_LOGI("MainThread::scheduleShrinkMemory level: %{public}d", level); + wptr weak = this; + auto task = [weak, level]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleShrinkMemory failed."); + return; + } + appThread->HandleShrinkMemory(level); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleShrinkMemory PostTask task failed"); + } + APP_LOGI("MainThread::scheduleShrinkMemory level: %{public}d end.", level); +} + +/** + * + * @brief Schedule the application process exit safely. + * + */ +void MainThread::ScheduleProcessSecurityExit() +{ + APP_LOGI("MainThread::ScheduleProcessSecurityExit called start"); + wptr weak = this; + auto task = [weak]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleShrinkMemory failed."); + return; + } + appThread->HandleProcessSecurityExit(); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleProcessSecurityExit PostTask task failed"); + } + APP_LOGI("MainThread::ScheduleProcessSecurityExit called end"); +} + +/** + * + * @brief Low the memory whitch used by application. + * + */ +void MainThread::ScheduleLowMemory() +{ + APP_LOGI("MainThread::scheduleLowMemory called"); +} + +/** + * + * @brief Launch the application. + * + * @param data The launchdata of the application witch launced. + * + */ +void MainThread::ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::scheduleLaunchApplication start"); + wptr weak = this; + auto task = [weak, data, config]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleLaunchApplication failed."); + return; + } + appThread->HandleLaunchApplication(data, config); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleLaunchApplication PostTask task failed"); + } + APP_LOGI("MainThread::scheduleLaunchApplication end."); +} + +void MainThread::ScheduleAbilityStage(const HapModuleInfo &abilityStage) +{ + APP_LOGI("MainThread::ScheduleAbilityStageInfo start"); + wptr weak = this; + auto task = [weak, abilityStage]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleShrinkMemory failed."); + return; + } + appThread->HandleAbilityStage(abilityStage); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleAbilityStageInfo PostTask task failed"); + } + APP_LOGI("MainThread::ScheduleAbilityStageInfo end."); +} + +/** + * + * @brief launch the application. + * + * @param info The launchdata of the application witch launced. + * @param token The launchdata of the application witch launced. + * + */ +void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) +{ + APP_LOGI("MainThread::scheduleLaunchAbility called start."); + APP_LOGI( + "MainThread::scheduleLaunchAbility AbilityInfo name:%{public}s type:%{public}d", info.name.c_str(), info.type); + + std::shared_ptr abilityInfo = std::make_shared(info); + if (abilityInfo == nullptr) { + APP_LOGE("MainThread::ScheduleLaunchAbility abilityInfo is nullptr"); + return; + } + sptr abilityToken = token; + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, abilityToken); + + std::shared_ptr contextDeal = std::make_shared(); + sptr bundleMgr = contextDeal->GetBundleManager(); + if (bundleMgr == nullptr) { + APP_LOGE("MainThread::ScheduleLaunchAbility GetBundleManager is nullptr"); + } else { + BundleInfo bundleInfo; + bundleMgr->GetBundleInfo(abilityInfo->bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + abilityRecord->SetCompatibleVersion(bundleInfo.compatibleVersion); + APP_LOGI("MainThread::ScheduleLaunchAbility compatibleVersion:%{public}d", bundleInfo.compatibleVersion); + } + + wptr weak = this; + auto task = [weak, abilityRecord]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleLaunchAbility failed."); + return; + } + appThread->HandleLaunchAbility(abilityRecord); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleLaunchAbility PostTask task failed"); + } + APP_LOGI("MainThread::scheduleLaunchAbility called end."); +} + +/** + * + * @brief clean the ability by token. + * + * @param token The token belong to the ability whitch want to be cleaned. + * + */ +void MainThread::ScheduleCleanAbility(const sptr &token) +{ + APP_LOGI("MainThread::scheduleCleanAbility called start."); + wptr weak = this; + auto task = [weak, token]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleCleanAbility failed."); + return; + } + appThread->HandleCleanAbility(token); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleCleanAbility PostTask task failed"); + } + APP_LOGI("MainThread::scheduleCleanAbility called end."); +} + +/** + * + * @brief send the new profile. + * + * @param profile The updated profile. + * + */ +void MainThread::ScheduleProfileChanged(const Profile &profile) +{ + APP_LOGI("MainThread::scheduleProfileChanged profile name: %{public}s", profile.GetName().c_str()); +} + +/** + * + * @brief send the new config to the application. + * + * @param config The updated config. + * + */ +void MainThread::ScheduleConfigurationUpdated(const Configuration &config) +{ + APP_LOGI("MainThread::ScheduleConfigurationUpdated called start."); + wptr weak = this; + auto task = [weak, config]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("appThread is nullptr, HandleConfigurationUpdated failed."); + return; + } + appThread->HandleConfigurationUpdated(config); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleConfigurationUpdated PostTask task failed"); + } + APP_LOGI("MainThread::ScheduleConfigurationUpdated called end."); +} + +/** + * + * @brief Check whether the appLaunchData is legal. + * + * @param appLaunchData The appLaunchData should be checked. + * + * @return if the appLaunchData is legal, return true. else return false. + */ +bool MainThread::CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) const +{ + APP_LOGI("MainThread::CheckLaunchApplicationParam called start."); + + ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); + ProcessInfo processInfo = appLaunchData.GetProcessInfo(); + + if (appInfo.name.empty()) { + APP_LOGE("MainThread::checkLaunchApplicationParam applicationName is empty"); + return false; + } + + if (processInfo.GetProcessName().empty()) { + APP_LOGE("MainThread::checkLaunchApplicationParam processName is empty"); + return false; + } + + APP_LOGI("MainThread::CheckLaunchApplicationParam called end."); + return true; +} + +/** + * + * @brief Check whether the record is legal. + * + * @param record The record should be checked. + * + * @return if the record is legal, return true. else return false. + */ +bool MainThread::CheckAbilityItem(const std::shared_ptr &record) const +{ + APP_LOGI("MainThread::CheckAbilityItem called start."); + if (record == nullptr) { + APP_LOGE("MainThread::checkAbilityItem record is null"); + return false; + } + + std::shared_ptr abilityInfo = record->GetAbilityInfo(); + sptr token = record->GetToken(); + + if (abilityInfo == nullptr) { + APP_LOGE("MainThread::checkAbilityItem abilityInfo is null"); + return false; + } + + if (token == nullptr) { + APP_LOGE("MainThread::checkAbilityItem token is null"); + return false; + } + + APP_LOGI("MainThread::CheckAbilityItem called end."); + return true; +} + +/** + * + * @brief Terminate the application but don't notify ams. + * + */ +void MainThread::HandleTerminateApplicationLocal() +{ + APP_LOGI("MainThread::HandleTerminateApplicationLocal called start."); + if (application_ == nullptr) { + APP_LOGE("MainThread::HandleTerminateApplicationLocal error!"); + return; + } + APP_LOGI("MainThread::HandleTerminateApplicationLocal before PerformTerminateStrong."); + applicationImpl_->PerformTerminateStrong(); + APP_LOGI("MainThread::HandleTerminateApplicationLocal after PerformTerminateStrong."); + std::shared_ptr runner = mainHandler_->GetEventRunner(); + if (runner == nullptr) { + APP_LOGE("MainThread::HandleTerminateApplicationLocal get manHandler error"); + return; + } + + if (watchDogHandler_ != nullptr) { + watchDogHandler_->Stop(); + } + int ret = runner->Stop(); + if (ret != ERR_OK) { + APP_LOGE("MainThread::HandleTerminateApplicationLocal failed. runner->Run failed ret = %{public}d", ret); + } + APP_LOGI("runner is stopped"); + SetRunnerStarted(false); + +#ifdef ABILITY_LIBRARY_LOADER + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. Start calling CloseAbilityLibrary."); + CloseAbilityLibrary(); + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. End calling CloseAbilityLibrary."); +#endif // ABILITY_LIBRARY_LOADER +#ifdef APPLICATION_LIBRARY_LOADER + if (handleAppLib_ != nullptr) { + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. Start calling dlclose."); + dlclose(handleAppLib_); + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. End calling dlclose."); + handleAppLib_ = nullptr; + } +#endif // APPLICATION_LIBRARY_LOADER + APP_LOGI("MainThread::HandleTerminateApplicationLocal called end."); +} + +/** + * + * @brief Schedule the application process exit safely. + * + */ +void MainThread::HandleProcessSecurityExit() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::HandleProcessSecurityExit called start."); + if (abilityRecordMgr_ == nullptr) { + APP_LOGE("MainThread::HandleProcessSecurityExit abilityRecordMgr_ is null"); + return; + } + + std::vector> tokens = (abilityRecordMgr_->GetAllTokens()); + + for (auto iter = tokens.begin(); iter != tokens.end(); ++iter) { + HandleCleanAbilityLocal(*iter); + } + + HandleTerminateApplicationLocal(); + APP_LOGI("MainThread::HandleProcessSecurityExit called end."); +} + +bool MainThread::InitCreate( + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo, Profile &appProfile) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + applicationInfo_ = std::make_shared(appInfo); + if (applicationInfo_ == nullptr) { + APP_LOGE("MainThread::InitCreate create applicationInfo_ failed"); + return false; + } + + processInfo_ = std::make_shared(processInfo); + if (processInfo_ == nullptr) { + APP_LOGE("MainThread::InitCreate create processInfo_ failed"); + return false; + } + + appProfile_ = std::make_shared(appProfile); + if (appProfile_ == nullptr) { + APP_LOGE("MainThread::InitCreate create appProfile_ failed"); + return false; + } + + applicationImpl_ = std::make_shared(); + if (applicationImpl_ == nullptr) { + APP_LOGE("MainThread::InitCreate create applicationImpl_ failed"); + return false; + } + + abilityRecordMgr_ = std::make_shared(); + if (abilityRecordMgr_ == nullptr) { + APP_LOGE("MainThread::InitCreate create AbilityRecordMgr failed"); + return false; + } + + contextDeal = std::make_shared(); + if (contextDeal == nullptr) { + APP_LOGE("MainThread::InitCreate create contextDeal failed"); + return false; + } + + contextDeal->SetProcessInfo(processInfo_); + contextDeal->SetApplicationInfo(applicationInfo_); + contextDeal->SetProfile(appProfile_); + contextDeal->SetBundleCodePath(applicationInfo_->codePath); // BMS need to add cpath + + return true; +} + +bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData) +{ + if (application_ != nullptr) { + APP_LOGE("MainThread::handleLaunchApplication already create application"); + return false; + } + + if (!CheckLaunchApplicationParam(appLaunchData)) { + APP_LOGE("MainThread::handleLaunchApplication appLaunchData invalid"); + return false; + } + return true; +} + +bool MainThread::InitResourceManager(std::shared_ptr &resourceManager, + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu start", + bundleInfo.moduleResPaths.size()); + for (auto moduleResPath : bundleInfo.moduleResPaths) { + if (!moduleResPath.empty()) { + APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, moduleResPath: %{public}s", + moduleResPath.length(), + moduleResPath.c_str()); + APP_LOGI("MainThread::handleLaunchApplication. before resourceManager->AddResource."); + if (!resourceManager->AddResource(moduleResPath.c_str())) { + APP_LOGE("MainThread::handleLaunchApplication AddResource failed"); + } + APP_LOGI("MainThread::handleLaunchApplication. after resourceManager->AddResource."); + } + } + APP_LOGI("MainThread::handleLaunchApplication moduleResPaths end."); + APP_LOGI("MainThread::handleLaunchApplication before Resource::CreateResConfig."); + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + APP_LOGI("MainThread::handleLaunchApplication after Resource::CreateResConfig."); + UErrorCode status = U_ZERO_ERROR; + icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); + resConfig->SetLocaleInfo(locale); + const icu::Locale *localeInfo = resConfig->GetLocaleInfo(); + if (localeInfo != nullptr) { + APP_LOGI("MainThread::handleLaunchApplication language: %{public}s, script: %{public}s, region: %{public}s,", + localeInfo->getLanguage(), + localeInfo->getScript(), + localeInfo->getCountry()); + } else { + APP_LOGI("MainThread::handleLaunchApplication localeInfo is nullptr."); + } + + APP_LOGI("MainThread::handleLaunchApplication. Start calling UpdateResConfig."); + resourceManager->UpdateResConfig(*resConfig); + APP_LOGI("MainThread::handleLaunchApplication. End calling UpdateResConfig."); + return true; +} +/** + * + * @brief Launch the application. + * + * @param appLaunchData The launchdata of the application witch launced. + * + */ +void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, const Configuration &config) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::handleLaunchApplication called start."); + if (!CheckForHandleLaunchApplication(appLaunchData)) { + APP_LOGE("MainThread::handleLaunchApplication CheckForHandleLaunchApplication failed"); + return; + } + LoadAbilityLibrary(appLaunchData.GetApplicationInfo().moduleSourceDirs); + LoadAppLibrary(); + + ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); + ProcessInfo processInfo = appLaunchData.GetProcessInfo(); + Profile appProfile = appLaunchData.GetProfile(); + + std::shared_ptr contextDeal = nullptr; + if (!InitCreate(contextDeal, appInfo, processInfo, appProfile)) { + APP_LOGE("MainThread::handleLaunchApplication InitCreate failed"); + return; + } + + // get application shared point + application_ = std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName()); + if (application_ == nullptr) { + APP_LOGE("HandleLaunchApplication::application launch failed"); + return; + } + applicationForAnr_ = application_; + + // init resourceManager. + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (resourceManager == nullptr) { + APP_LOGE("MainThread::handleLaunchApplication create resourceManager failed"); + return; + } + + APP_LOGI("MainThread::handleLaunchApplication. Start calling GetBundleManager."); + sptr bundleMgr = contextDeal->GetBundleManager(); + if (bundleMgr == nullptr) { + APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr"); + return; + } + APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager."); + + BundleInfo bundleInfo; + APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s", + appInfo.bundleName.length(), appInfo.bundleName.c_str()); + bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + + if (!InitResourceManager(resourceManager, contextDeal, appInfo, bundleInfo)) { + APP_LOGE("MainThread::handleLaunchApplication InitResourceManager failed"); + return; + } + + bool moduelJson = false; + bool isStageBased = false; + if (!bundleInfo.hapModuleInfos.empty()) { + moduelJson = bundleInfo.hapModuleInfos.back().isModuleJson; + isStageBased = bundleInfo.hapModuleInfos.back().isStageBasedModel; + } + APP_LOGI("stageBased:%{public}d moduelJson:%{public}d size:%{public}d", + isStageBased, moduelJson, (int32_t)bundleInfo.hapModuleInfos.size()); + if (isStageBased) { + // Create runtime + AbilityRuntime::Runtime::Options options; + options.codePath = appInfo.codePath; + options.eventRunner = mainHandler_->GetEventRunner(); + auto runtime = AbilityRuntime::Runtime::Create(options); + if (!runtime) { + APP_LOGE("OHOSApplication::OHOSApplication: Failed to create runtime"); + return; + } + + application_->SetRuntime(std::move(runtime)); + auto usertestInfo = appLaunchData.GetUserTestInfo(); + if (usertestInfo.observer) { + if (!AbilityDelegatorPrepare(usertestInfo)) { + return; + } + } + AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() { + return Ability::Create(application->GetRuntime()); + }); + AbilityLoader::GetInstance().RegisterExtension("FormExtension", [application = application_]() { + return AbilityRuntime::FormExtension::Create(application->GetRuntime()); + }); + AbilityLoader::GetInstance().RegisterExtension("StaticSubscriberExtension", [application = application_]() { + return AbilityRuntime::StaticSubscriberExtension::Create(application->GetRuntime()); + }); + LoadAndRegisterExtension("system/lib/libservice_extension_module.z.so", "ServiceExtension", + application_->GetRuntime()); + } + + contextDeal->initResourceManager(resourceManager); + contextDeal->SetApplicationContext(application_); + application_->AttachBaseContext(contextDeal); + application_->SetAbilityRecordMgr(abilityRecordMgr_); + application_->SetConfiguration(config); + + // create contextImpl + std::shared_ptr contextImpl = std::make_shared(); + contextImpl->SetResourceManager(resourceManager); + contextImpl->SetApplicationInfo(std::make_shared(appInfo)); + contextImpl->InitAppContext(); + application_->SetApplicationContext(contextImpl); + + applicationImpl_->SetRecordId(appLaunchData.GetRecordId()); + applicationImpl_->SetApplication(application_); + mainThreadState_ = MainThreadState::READY; + APP_LOGI("MainThread::handleLaunchApplication before PerformAppReady."); + if (!applicationImpl_->PerformAppReady()) { + APP_LOGE("HandleLaunchApplication::application applicationImpl_->PerformAppReady failed"); + return; + } + APP_LOGI("MainThread::handleLaunchApplication after PerformAppReady."); + // L1 needs to add corresponding interface + ApplicationEnvImpl *pAppEvnIml = ApplicationEnvImpl::GetInstance(); + + if (pAppEvnIml) { + pAppEvnIml->SetAppInfo(*applicationInfo_.get()); + } else { + APP_LOGE("HandleLaunchApplication::application pAppEvnIml is null"); + } + + APP_LOGI("MainThread::handleLaunchApplication called end."); +} + +void MainThread::HandleAbilityStage(const HapModuleInfo &abilityStage) +{ + APP_LOGI("MainThread::HandleAbilityStageInfo"); + if (!application_) { + APP_LOGE("application_ is nullptr"); + return; + } + + application_->AddAbilityStage(abilityStage); + + if (!appMgr_ || !applicationImpl_) { + APP_LOGE("appMgr_ is nullptr"); + return; + } + + if (!appMgr_ || !applicationImpl_) { + APP_LOGE("appMgr_ is nullptr"); + return; + } + appMgr_->AddAbilityStageDone(applicationImpl_->GetRecordId()); +} + +void MainThread::LoadAndRegisterExtension(const std::string &libName, + const std::string &extensionName, const std::unique_ptr& runtime) +{ + APP_LOGI("MainThread::LoadAndRegisterExtension.libName:%{public}s,extensionName:%{public}s,", + libName.c_str(), extensionName.c_str()); + if (application_ == nullptr) { + APP_LOGE("LoadAndRegisterExtension::application launch failed"); + return; + } + APP_LOGI("MainThread::LoadAndRegisterExtension load success."); + AbilityLoader::GetInstance().RegisterExtension(extensionName, [application = application_, libName]() { + return AbilityRuntime::ExtensionModuleLoader::GetLoader(libName.c_str()).Create(application->GetRuntime()); + }); +} + +bool MainThread::AbilityDelegatorPrepare(const UserTestRecord &record) +{ + APP_LOGI("MainThread::AbilityDelegatorPrepare"); + auto args = std::make_shared(record.want); + if (!args) { + APP_LOGE("args is null"); + return false; + } + auto testRunner = TestRunner::Create(application_->GetRuntime(), args); + if (!testRunner) { + APP_LOGE("testRunner is null"); + return false; + } + + auto delegator = std::make_shared(this, std::move(testRunner), record.observer); + if (!delegator) { + APP_LOGE("delegator is null"); + return false; + } + delegator->Init(); + AbilityDelegatorRegistry::RegisterInstance(delegator, args); + + delegator->Prepare(); + return true; +} + +int MainThread::FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) +{ + APP_LOGI("MainThread::FinishUserTest"); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->FinishUserTest( + msg, resultCode, bundleName, observer); + if (err != ERR_OK) { + APP_LOGE("MainThread::FinishUserTest is failed %{public}d", err); + } + return ERR_OK; +} + +/** + * + * @brief launch the ability. + * + * @param abilityRecord The abilityRecord whitch belongs to the ability launched. + * + */ +void MainThread::HandleLaunchAbility(const std::shared_ptr &abilityRecord) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::handleLaunchAbility called start."); + + if (applicationImpl_ == nullptr) { + APP_LOGE("MainThread::HandleLaunchAbility applicationImpl_ is null"); + return; + } + + if (abilityRecordMgr_ == nullptr) { + APP_LOGE("MainThread::HandleLaunchAbility abilityRecordMgr_ is null"); + return; + } + + if (abilityRecord == nullptr) { + APP_LOGE("MainThread::HandleLaunchAbility parameter(abilityRecord) is null"); + return; + } + + auto abilityToken = abilityRecord->GetToken(); + if (abilityToken == nullptr) { + APP_LOGE("MainThread::HandleLaunchAbility failed. abilityRecord->GetToken failed"); + return; + } + + abilityRecordMgr_->SetToken(abilityToken); + abilityRecordMgr_->AddAbilityRecord(abilityToken, abilityRecord); + + if (!IsApplicationReady()) { + APP_LOGE("MainThread::handleLaunchAbility not init OHOSApplication, should launch application first"); + return; + } + + if (!CheckAbilityItem(abilityRecord)) { + APP_LOGE("MainThread::handleLaunchAbility record is invalid"); + return; + } + + mainThreadState_ = MainThreadState::RUNNING; + std::shared_ptr stageContext = application_->AddAbilityStage(abilityRecord); +#ifdef APP_ABILITY_USE_TWO_RUNNER + APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain start."); + AbilityThread::AbilityThreadMain(application_, abilityRecord, stageContext); + APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain end."); +#else + APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain start."); + AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner(), stageContext); + APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain end."); +#endif + APP_LOGI("MainThread::handleLaunchAbility called end."); +} + +/** + * + * @brief Clean the ability but don't notify ams. + * + * @param token The token whitch belongs to the ability launched. + * + */ +void MainThread::HandleCleanAbilityLocal(const sptr &token) +{ + APP_LOGI("MainThread::HandleCleanAbilityLocal called start."); + if (!IsApplicationReady()) { + APP_LOGE("MainThread::HandleCleanAbilityLocal not init OHOSApplication, should launch application first"); + return; + } + + if (token == nullptr) { + APP_LOGE("MainThread::HandleCleanAbilityLocal token is null"); + return; + } + + std::shared_ptr record = abilityRecordMgr_->GetAbilityItem(token); + if (record == nullptr) { + APP_LOGE("MainThread::HandleCleanAbilityLocal abilityRecord not found"); + return; + } + std::shared_ptr abilityInfo = record->GetAbilityInfo(); + if (abilityInfo == nullptr) { + APP_LOGE("MainThread::HandleCleanAbilityLocal record->GetAbilityInfo() failed"); + return; + } + APP_LOGI("MainThread::HandleCleanAbilityLocal ability name: %{public}s", abilityInfo->name.c_str()); + + abilityRecordMgr_->RemoveAbilityRecord(token); +#ifdef APP_ABILITY_USE_TWO_RUNNER + std::shared_ptr runner = record->GetEventRunner(); + if (runner != nullptr) { + int ret = runner->Stop(); + if (ret != ERR_OK) { + APP_LOGE("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret); + } + abilityRecordMgr_->RemoveAbilityRecord(token); + } else { + APP_LOGW("MainThread::HandleCleanAbilityLocal runner not found"); + } +#endif + APP_LOGI("MainThread::HandleCleanAbilityLocal called end."); +} + +/** + * + * @brief Clean the ability. + * + * @param token The token whitch belongs to the ability launched. + * + */ +void MainThread::HandleCleanAbility(const sptr &token) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::handleCleanAbility called start."); + if (!IsApplicationReady()) { + APP_LOGE("MainThread::handleCleanAbility not init OHOSApplication, should launch application first"); + return; + } + + if (token == nullptr) { + APP_LOGE("MainThread::handleCleanAbility token is null"); + return; + } + + std::shared_ptr record = abilityRecordMgr_->GetAbilityItem(token); + if (record == nullptr) { + APP_LOGE("MainThread::handleCleanAbility abilityRecord not found"); + return; + } + std::shared_ptr abilityInfo = record->GetAbilityInfo(); + if (abilityInfo == nullptr) { + APP_LOGE("MainThread::handleCleanAbility record->GetAbilityInfo() failed"); + return; + } + APP_LOGI("MainThread::handleCleanAbility ability name: %{public}s", abilityInfo->name.c_str()); + + abilityRecordMgr_->RemoveAbilityRecord(token); +#ifdef APP_ABILITY_USE_TWO_RUNNER + std::shared_ptr runner = record->GetEventRunner(); + if (runner != nullptr) { + int ret = runner->Stop(); + if (ret != ERR_OK) { + APP_LOGE("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret); + } + abilityRecordMgr_->RemoveAbilityRecord(token); + } else { + APP_LOGW("MainThread::handleCleanAbility runner not found"); + } +#endif + APP_LOGI("MainThread::handleCleanAbility before AbilityCleaned."); + appMgr_->AbilityCleaned(token); + APP_LOGI("MainThread::handleCleanAbility after AbilityCleaned."); + APP_LOGI("MainThread::handleCleanAbility called end."); +} + +/** + * + * @brief Foreground the application. + * + */ +void MainThread::HandleForegroundApplication() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::handleForegroundApplication called start."); + if ((application_ == nullptr) || (appMgr_ == nullptr)) { + APP_LOGE("MainThread::handleForegroundApplication error!"); + return; + } + + if (!applicationImpl_->PerformForeground()) { + APP_LOGE("MainThread::handleForegroundApplication error!, applicationImpl_->PerformForeground() failed"); + return; + } + + APP_LOGI("MainThread::handleForegroundApplication before ApplicationForegrounded"); + appMgr_->ApplicationForegrounded(applicationImpl_->GetRecordId()); + APP_LOGI("MainThread::handleForegroundApplication after ApplicationForegrounded"); + APP_LOGI("MainThread::handleForegroundApplication called end"); +} + +/** + * + * @brief Background the application. + * + */ +void MainThread::HandleBackgroundApplication() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::handleBackgroundApplication called start."); + + if ((application_ == nullptr) || (appMgr_ == nullptr)) { + APP_LOGE("MainThread::handleBackgroundApplication error!"); + return; + } + + if (!applicationImpl_->PerformBackground()) { + APP_LOGE("MainThread::handleForegroundApplication error!, applicationImpl_->PerformBackground() failed"); + return; + } + APP_LOGI("MainThread::handleBackgroundApplication before ApplicationBackgrounded"); + appMgr_->ApplicationBackgrounded(applicationImpl_->GetRecordId()); + APP_LOGI("MainThread::handleBackgroundApplication after ApplicationBackgrounded"); + + APP_LOGI("MainThread::handleBackgroundApplication called end"); +} + +/** + * + * @brief Terminate the application. + * + */ +void MainThread::HandleTerminateApplication() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::handleTerminateApplication called start."); + if ((application_ == nullptr) || (appMgr_ == nullptr)) { + APP_LOGE("MainThread::handleTerminateApplication error!"); + return; + } + + APP_LOGI("MainThread::handleTerminateApplication before PerformTerminate"); + if (!applicationImpl_->PerformTerminate()) { + APP_LOGE("MainThread::handleForegroundApplication error!, applicationImpl_->PerformTerminate() failed"); + return; + } + APP_LOGI("MainThread::handleTerminateApplication after PerformTerminate"); + + APP_LOGI("MainThread::handleTerminateApplication before ApplicationTerminated"); + appMgr_->ApplicationTerminated(applicationImpl_->GetRecordId()); + APP_LOGI("MainThread::handleTerminateApplication after ApplicationTerminated"); + std::shared_ptr runner = mainHandler_->GetEventRunner(); + if (runner == nullptr) { + APP_LOGE("MainThread::handleTerminateApplication get manHandler error"); + return; + } + + if (watchDogHandler_ != nullptr) { + watchDogHandler_->Stop(); + } + APP_LOGI("MainThread::handleTerminateApplication before stop runner"); + int ret = runner->Stop(); + APP_LOGI("MainThread::handleTerminateApplication after stop runner"); + if (ret != ERR_OK) { + APP_LOGE("MainThread::handleTerminateApplication failed. runner->Run failed ret = %{public}d", ret); + } + SetRunnerStarted(false); + +#ifdef ABILITY_LIBRARY_LOADER + APP_LOGI("MainThread::handleTerminateApplication. Start callint CloseAbilityLibrary."); + CloseAbilityLibrary(); + APP_LOGI("MainThread::handleTerminateApplication. End callint CloseAbilityLibrary."); +#endif // ABILITY_LIBRARY_LOADER +#ifdef APPLICATION_LIBRARY_LOADER + if (handleAppLib_ != nullptr) { + dlclose(handleAppLib_); + handleAppLib_ = nullptr; + } +#endif // APPLICATION_LIBRARY_LOADER + APP_LOGI("MainThread::handleTerminateApplication called end."); +} + +/** + * + * @brief Shrink the memory whitch used by application. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + * + */ +void MainThread::HandleShrinkMemory(const int level) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::HandleShrinkMemory called start."); + + if (applicationImpl_ == nullptr) { + APP_LOGE("MainThread::HandleShrinkMemory error! applicationImpl_ is null"); + return; + } + + applicationImpl_->PerformMemoryLevel(level); + APP_LOGI("MainThread::HandleShrinkMemory called end."); +} + +/** + * + * @brief send the new config to the application. + * + * @param config The updated config. + * + */ +void MainThread::HandleConfigurationUpdated(const Configuration &config) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::HandleConfigurationUpdated called start."); + + if (applicationImpl_ == nullptr) { + APP_LOGE("MainThread::HandleConfigurationUpdated error! applicationImpl_ is null"); + return; + } + + applicationImpl_->PerformConfigurationUpdated(config); + APP_LOGI("MainThread::HandleConfigurationUpdated called end."); +} + +void MainThread::TaskTimeoutDetected() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::TaskTimeoutDetected called start."); + + auto deliveryTimeoutCallback = []() { + APP_LOGI("MainThread::TaskTimeoutDetected delivery timeout"); + }; + auto distributeTimeoutCallback = []() { + APP_LOGI("MainThread::TaskTimeoutDetected delivery timeout"); + }; + + if (mainHandler_ != nullptr) { + mainHandler_->SetDeliveryTimeout(DELIVERY_TIME); + mainHandler_->SetDeliveryTimeoutCallback(deliveryTimeoutCallback); + + mainHandler_->SetDistributeTimeout(DISTRIBUTE_TIME); + mainHandler_->SetDistributeTimeoutCallback(distributeTimeoutCallback); + } + APP_LOGI("MainThread::TaskTimeoutDetected called end."); +} + +void MainThread::Init(const std::shared_ptr &runner, const std::shared_ptr &watchDogRunner) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread:Init Start"); + mainHandler_ = std::make_shared(runner, this); + watchDogHandler_ = std::make_shared(watchDogRunner); + wptr weak = this; + auto task = [weak]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("abilityThread is nullptr, SetRunnerStarted failed."); + return; + } + APP_LOGI("MainThread:MainHandler Start"); + appThread->SetRunnerStarted(true); + }; + auto taskWatchDog = []() { + APP_LOGI("MainThread:WatchDogHandler Start"); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::Init PostTask task failed"); + } + if (!watchDogHandler_->PostTask(taskWatchDog)) { + APP_LOGE("MainThread::Init WatchDog postTask task failed"); + } + TaskTimeoutDetected(); + /* + watchDogHandler_->Init(mainHandler_, watchDogHandler_); + APP_LOGI("MainThread:Init before CreateRunner."); + */ + TaskHandlerClient::GetInstance()->CreateRunner(); + APP_LOGI("MainThread:Init after CreateRunner."); + APP_LOGI("MainThread:Init end."); +} + +void MainThread::HandleANRProcess(int sigMessage) +{ + if (sigMessage == SIGUSR1) { + int rFD = -1; + if ((rFD = RequestFileDescriptor(int32_t(FaultLoggerType::CPP_CRASH))) < 0) { + APP_LOGE("MainThread::HandleANRProcess request file eescriptor failed"); + } + auto jsRuntime = std::move((std::unique_ptr&)applicationForAnr_->GetRuntime()); + std::string mainThreadStackInfo = jsRuntime->BuildNativeAndJsBackStackTrace(); + if (write(rFD, mainThreadStackInfo.c_str(), mainThreadStackInfo.size()) != mainThreadStackInfo.size()) { + APP_LOGE("MainThread::HandleANRProcess write main thread stack info failed"); + } + OHOS::HiviewDFX::DfxDumpCatcher dumplog; + std::string proStackInfo; + if (dumplog.DumpCatch(getpid(), 0, proStackInfo) == false) { + APP_LOGE("MainThread::HandleANRProcess get process stack info failed"); + } + if (write(rFD, proStackInfo.c_str(), proStackInfo.size()) != proStackInfo.size()) { + APP_LOGE("MainThread::HandleANRProcess write process stack info failed"); + } + if (rFD != -1) { + close(rFD); + } + } +} + +void MainThread::Start() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("MainThread::main called start"); + std::shared_ptr runner = EventRunner::GetMainEventRunner(); + if (runner == nullptr) { + APP_LOGE("MainThread::main failed, runner is nullptr"); + return; + } + std::shared_ptr runnerWatchDog = EventRunner::Create("WatchDogRunner"); + if (runnerWatchDog == nullptr) { + APP_LOGE("MainThread::Start runnerWatchDog is nullptr"); + return; + } + sptr thread = sptr(new (std::nothrow) MainThread()); + if (thread == nullptr) { + APP_LOGE("MainThread::static failed. new MainThread failed"); + return; + } + + APP_LOGI("MainThread::main called start Init"); + thread->Init(runner, runnerWatchDog); + APP_LOGI("MainThread::main called end Init"); + + APP_LOGI("MainThread::main called start Attach"); + thread->Attach(); + APP_LOGI("MainThread::main called end Attach"); + + int ret = runner->Run(); + if (ret != ERR_OK) { + APP_LOGE("MainThread::main failed. runner->Run failed ret = %{public}d", ret); + } + + thread->RemoveAppMgrDeathRecipient(); + APP_LOGI("MainThread::main runner stopped"); +} + +MainThread::MainHandler::MainHandler(const std::shared_ptr &runner, const sptr &thread) + : AppExecFwk::EventHandler(runner), mainThreadObj_(thread) +{} + +/** + * + * @brief Process the event. + * + * @param event the event want to be processed. + * + */ +void MainThread::MainHandler::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event) +{ + auto eventId = event->GetInnerEventId(); + if (eventId == MAIN_THREAD_IS_ALIVE) { + WatchDog::GetCurrentHandler()->SendEvent(MAIN_THREAD_IS_ALIVE); + } +} + +/** + * + * @brief Check whether the OHOSApplication is ready. + * + * @return if the record is legal, return true. else return false. + * + */ +bool MainThread::IsApplicationReady() const +{ + APP_LOGI("MainThread::IsApplicationReady called start"); + if (application_ == nullptr || applicationImpl_ == nullptr) { + APP_LOGI("MainThread::IsApplicationReady called. application_=null or applicationImpl_=null"); + return false; + } + + APP_LOGI("MainThread::IsApplicationReady called end"); + return true; +} + +#ifdef ABILITY_LIBRARY_LOADER +/** + * + * @brief Load the ability library. + * + * @param libraryPaths the library paths. + * + */ +void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); +#ifdef ABILITY_LIBRARY_LOADER + APP_LOGI("MainThread::LoadAbilityLibrary called start"); +#ifdef ACEABILITY_LIBRARY_LOADER +#ifdef _ARM64_ + std::string acelibdir("/system/lib64/libace.z.so"); +#else + std::string acelibdir("/system/lib/libace.z.so"); +#endif + void *AceAbilityLib = nullptr; + APP_LOGI("MainThread::LoadAbilityLibrary. Start calling dlopen acelibdir."); + AceAbilityLib = dlopen(acelibdir.c_str(), RTLD_NOW | RTLD_GLOBAL); + if (AceAbilityLib == nullptr) { + APP_LOGE("Fail to dlopen %{public}s, [%{public}s]", acelibdir.c_str(), dlerror()); + } else { + APP_LOGI("Success to dlopen %{public}s", acelibdir.c_str()); + handleAbilityLib_.emplace_back(AceAbilityLib); + } + APP_LOGI("MainThread::LoadAbilityLibrary. End calling dlopen."); +#endif // ACEABILITY_LIBRARY_LOADER + int size = libraryPaths.size(); + APP_LOGI("MainThread::LoadAbilityLibrary. size=%{public}d.", size); + for (int index = 0; index < size; index++) { + std::string libraryPath = libraryPaths[index]; + APP_LOGI("MainThread::LoadAbilityLibrary Try to scanDir %{public}s", libraryPath.c_str()); + if (!ScanDir(libraryPath)) { + APP_LOGE("MainThread::LoadAbilityLibrary scanDir %{public}s not exits", libraryPath.c_str()); + } + libraryPath = libraryPath + "/libs"; + if (!ScanDir(libraryPath)) { + APP_LOGE("MainThread::LoadAbilityLibrary scanDir %{public}s not exits", libraryPath.c_str()); + } + } + + if (fileEntries_.empty()) { + APP_LOGE("No ability library"); + return; + } + + void *handleAbilityLib = nullptr; + for (auto fileEntry : fileEntries_) { + if (!fileEntry.empty()) { + APP_LOGI("MainThread::LoadAbilityLibrary. Start calling dlopen fileEntry."); + handleAbilityLib = dlopen(fileEntry.c_str(), RTLD_NOW | RTLD_GLOBAL); + APP_LOGI("MainThread::LoadAbilityLibrary. End calling dlopen fileEntry."); + if (handleAbilityLib == nullptr) { + APP_LOGE("MainThread::LoadAbilityLibrary Fail to dlopen %{public}s, [%{public}s]", + fileEntry.c_str(), + dlerror()); + exit(-1); + } else { + APP_LOGI("MainThread::LoadAbilityLibrary Success to dlopen %{public}s", fileEntry.c_str()); + } + handleAbilityLib_.emplace_back(handleAbilityLib); + } + } + APP_LOGI("MainThread::LoadAbilityLibrary called end."); +#endif // ABILITY_LIBRARY_LOADER +} + +void MainThread::LoadAppLibrary() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); +#ifdef APPLICATION_LIBRARY_LOADER + std::string appPath = applicationLibraryPath; + APP_LOGI("MainThread::handleLaunchApplication Start calling dlopen. appPath=%{public}s", appPath.c_str()); + handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL); + if (handleAppLib_ == nullptr) { + APP_LOGE("Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror()); + exit(-1); + } + APP_LOGI("MainThread::handleLaunchApplication End calling dlopen."; +#endif // APPLICATION_LIBRARY_LOADER +} + +/** + * + * @brief Close the ability library loaded. + * + */ +void MainThread::CloseAbilityLibrary() +{ + APP_LOGI("MainThread::CloseAbilityLibrary called start"); + for (auto iter : handleAbilityLib_) { + if (iter != nullptr) { + APP_LOGI("MainThread::CloseAbilityLibrary before dlclose"); + dlclose(iter); + APP_LOGI("MainThread::CloseAbilityLibrary after dlclose"); + iter = nullptr; + } + } + handleAbilityLib_.clear(); + fileEntries_.clear(); + APP_LOGI("MainThread::CloseAbilityLibrary called end"); +} + +/** + * + * @brief Scan the dir ability library loaded. + * + * @param dirPath the the path should be scan. + * + */ +bool MainThread::ScanDir(const std::string &dirPath) +{ + APP_LOGI("MainThread::ScanDir called start. dirPath: %{public}s.", dirPath.c_str()); + APP_LOGI("MainThread::ScanDir before opendir."); + DIR *dirp = opendir(dirPath.c_str()); + if (dirp == nullptr) { + APP_LOGE("MainThread::ScanDir open dir:%{public}s fail", dirPath.c_str()); + return false; + } + APP_LOGI("MainThread::ScanDir after opendir."); + struct dirent *df = nullptr; + for (;;) { + APP_LOGI("MainThread::ScanDir before readdir."); + df = readdir(dirp); + APP_LOGI("MainThread::ScanDir after readdir."); + if (df == nullptr) { + break; + } + + std::string currentName(df->d_name); + APP_LOGD("folder found:'%{public}s'", df->d_name); + if (currentName.compare(".") == 0 || currentName.compare("..") == 0) { + continue; + } + + if (CheckFileType(currentName, abilityLibraryType_)) { + APP_LOGI("MainThread::ScanDir CheckFileType == true."); + fileEntries_.emplace_back(dirPath + pathSeparator_ + currentName); + } + } + + APP_LOGI("MainThread::ScanDir before closedir."); + if (closedir(dirp) == -1) { + APP_LOGW("close dir fail"); + } + APP_LOGI("MainThread::ScanDir after closedir."); + APP_LOGI("MainThread::ScanDir called end."); + return true; +} + +/** + * + * @brief Check the fileType. + * + * @param fileName The fileName of the lib. + * @param extensionName The extensionName of the lib. + * + * @return if the FileType is legal, return true. else return false. + * + */ +bool MainThread::CheckFileType(const std::string &fileName, const std::string &extensionName) +{ + APP_LOGD("MainThread::CheckFileType path is %{public}s, support suffix is %{public}s", + fileName.c_str(), + extensionName.c_str()); + + if (fileName.empty()) { + APP_LOGE("the file name is empty"); + return false; + } + + auto position = fileName.rfind('.'); + if (position == std::string::npos) { + APP_LOGE("filename no extension name"); + return false; + } + + std::string suffixStr = fileName.substr(position); + APP_LOGD("MainThread::CheckFileType end."); + return LowerStr(suffixStr) == extensionName; +} + +void MainThread::HandleScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) +{ + APP_LOGI("MainThread::HandleScheduleAcceptWant"); + if (!application_) { + APP_LOGE("application_ is nullptr"); + return; + } + + std::string specifiedFlag; + application_->ScheduleAcceptWant(want, moduleName, specifiedFlag); + + if (!appMgr_ || !applicationImpl_) { + APP_LOGE("appMgr_ is nullptr"); + return; + } + + appMgr_->ScheduleAcceptWantDone(applicationImpl_->GetRecordId(), want, specifiedFlag); +} + +void MainThread::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) +{ + APP_LOGI("MainThread::ScheduleAcceptWant start"); + wptr weak = this; + auto task = [weak, want, moduleName]() { + auto appThread = weak.promote(); + if (appThread == nullptr) { + APP_LOGE("abilityThread is nullptr, HandleScheduleAcceptWant failed."); + return; + } + appThread->HandleScheduleAcceptWant(want, moduleName); + }; + if (!mainHandler_->PostTask(task)) { + APP_LOGE("MainThread::ScheduleAcceptWant PostTask task failed"); + } + APP_LOGI("MainThread::ScheduleAcceptWant end."); +} +#endif // ABILITY_LIBRARY_LOADER +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/ohos_application.cpp b/frameworks/kits/appkit/native/app/src/ohos_application.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d08d0e435759e43e0b306e133c735f374a23fefa --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/ohos_application.cpp @@ -0,0 +1,581 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ohos_application.h" + +#include "ability_record_mgr.h" +#include "app_loader.h" +#include "app_log_wrapper.h" +#include "application_impl.h" +#include "context_impl.h" +#include "iservice_registry.h" +#include "runtime.h" +#include "system_ability_definition.h" +#include "ability_thread.h" + +namespace OHOS { +namespace AppExecFwk { +REGISTER_APPLICATION(OHOSApplication, OHOSApplication) + +OHOSApplication::OHOSApplication() +{ + abilityLifecycleCallbacks_.clear(); + elementsCallbacks_.clear(); +} + +OHOSApplication::~OHOSApplication() = default; + +/** + * + * @brief Called when Ability#onSaveAbilityState(PacMap) was called on an ability. + * + * @param outState Indicates the PacMap object passed to Ability#onSaveAbilityState(PacMap) + * for storing user data and states. This parameter cannot be null. + */ + +void OHOSApplication::DispatchAbilitySavedState(const PacMap &outState) +{ + APP_LOGI("OHOSApplication::dispatchAbilitySavedState: called"); + for (auto callback : abilityLifecycleCallbacks_) { + if (callback != nullptr) { + callback->OnAbilitySaveState(outState); + } + } +} + +/** + * + * @brief Will be called the application foregrounds + * + */ +void OHOSApplication::OnForeground() +{} + +/** + * + * @brief Will be called the application backgrounds + * + */ +void OHOSApplication::OnBackground() +{} + +void OHOSApplication::DumpApplication() +{ + APP_LOGD("OHOSApplication::Dump called"); + // create and initialize abilityInfos + std::shared_ptr abilityInfo = nullptr; + std::shared_ptr record = nullptr; + + if (abilityRecordMgr_) { + record = abilityRecordMgr_->GetAbilityItem(abilityRecordMgr_->GetToken()); + } + + if (record) { + abilityInfo = record->GetAbilityInfo(); + } + + if (abilityInfo) { + APP_LOGD("==============AbilityInfo=============="); + APP_LOGD("abilityInfo: package: %{public}s", abilityInfo->package.c_str()); + APP_LOGD("abilityInfo: name: %{public}s", abilityInfo->name.c_str()); + APP_LOGD("abilityInfo: label: %{public}s", abilityInfo->label.c_str()); + APP_LOGD("abilityInfo: description: %{public}s", abilityInfo->description.c_str()); + APP_LOGD("abilityInfo: iconPath: %{public}s", abilityInfo->iconPath.c_str()); + APP_LOGD("abilityInfo: visible: %{public}d", abilityInfo->visible); + APP_LOGD("abilityInfo: kind: %{public}s", abilityInfo->kind.c_str()); + APP_LOGD("abilityInfo: type: %{public}d", abilityInfo->type); + APP_LOGD("abilityInfo: orientation: %{public}d", abilityInfo->orientation); + APP_LOGD("abilityInfo: launchMode: %{public}d", abilityInfo->launchMode); + for (auto permission : abilityInfo->permissions) { + APP_LOGD("abilityInfo: permission: %{public}s", permission.c_str()); + } + APP_LOGD("abilityInfo: bundleName: %{public}s", abilityInfo->bundleName.c_str()); + APP_LOGD("abilityInfo: applicationName: %{public}s", abilityInfo->applicationName.c_str()); + } + + // create and initialize applicationInfo + APP_LOGD("==============applicationInfo=============="); + std::shared_ptr applicationInfoPtr = GetApplicationInfo(); + if (applicationInfoPtr != nullptr) { + APP_LOGD("applicationInfo: name: %{public}s", applicationInfoPtr->name.c_str()); + APP_LOGD("applicationInfo: bundleName: %{public}s", applicationInfoPtr->bundleName.c_str()); + APP_LOGD("applicationInfo: signatureKey: %{public}s", applicationInfoPtr->signatureKey.c_str()); + } +} + +/** + * @brief Set Runtime + * + * @param runtime Runtime instance. + */ +void OHOSApplication::SetRuntime(std::unique_ptr&& runtime) +{ + APP_LOGI("OHOSApplication::SetRuntime begin"); + if (runtime == nullptr) { + APP_LOGE("OHOSApplication::SetRuntime failed, runtime is empty"); + return; + } + runtime_ = std::move(runtime); + APP_LOGI("OHOSApplication::SetRuntime end"); +} + +/** + * @brief Set ApplicationContext + * + * @param abilityRuntimeContext ApplicationContext instance. + */ +void OHOSApplication::SetApplicationContext(const std::shared_ptr &abilityRuntimeContext) +{ + APP_LOGI("OHOSApplication::SetApplicationContext begin"); + if (abilityRuntimeContext == nullptr) { + APP_LOGE("OHOSApplication::SetApplicationContext failed, context is empty"); + return; + } + abilityRuntimeContext_ = abilityRuntimeContext; + APP_LOGI("OHOSApplication::SetApplicationContext end"); +} + +/** + * + * @brief Set the abilityRecordMgr to the OHOSApplication. + * + * @param abilityRecordMgr + */ +void OHOSApplication::SetAbilityRecordMgr(const std::shared_ptr &abilityRecordMgr) +{ + APP_LOGI("OHOSApplication::SetAbilityRecordMgr. Start"); + if (abilityRecordMgr == nullptr) { + APP_LOGE("ContextDeal::SetAbilityRecordMgr failed, abilityRecordMgr is nullptr"); + return; + } + abilityRecordMgr_ = abilityRecordMgr; + APP_LOGI("OHOSApplication::SetAbilityRecordMgr. End"); +} + +/** + * + * Register AbilityLifecycleCallbacks with OHOSApplication + * + * @param callBack callBack When the life cycle of the ability in the application changes, + */ +void OHOSApplication::RegisterAbilityLifecycleCallbacks(const std::shared_ptr &callBack) +{ + APP_LOGI("OHOSApplication::RegisterAbilityLifecycleCallbacks: called"); + + if (callBack == nullptr) { + APP_LOGI("OHOSApplication::RegisterAbilityLifecycleCallbacks: observer is null"); + return; + } + + abilityLifecycleCallbacks_.emplace_back(callBack); +} + +/** + * + * Unregister AbilityLifecycleCallbacks with OHOSApplication + * + * @param callBack RegisterAbilityLifecycleCallbacks`s callBack + */ +void OHOSApplication::UnregisterAbilityLifecycleCallbacks(const std::shared_ptr &callBack) +{ + APP_LOGI("OHOSApplication::UnregisterAbilityLifecycleCallbacks: called"); + + if (callBack == nullptr) { + APP_LOGI("OHOSApplication::UnregisterAbilityLifecycleCallbacks: observer is null"); + return; + } + + abilityLifecycleCallbacks_.remove(callBack); +} + +/** + * + * Will be called when the given ability calls Ability->onStart + * + * @param Ability Indicates the ability object that calls the onStart() method. + */ +void OHOSApplication::OnAbilityStart(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + APP_LOGE("ContextDeal::OnAbilityStart failed, ability is nullptr"); + return; + } + + APP_LOGI("OHOSApplication::OnAbilityStart: called"); + for (auto callback : abilityLifecycleCallbacks_) { + if (callback != nullptr) { + callback->OnAbilityStart(ability); + } + } +} + +/** + * + * Will be called when the given ability calls Ability->onInactive + * + * @param Ability Indicates the Ability object that calls the onInactive() method. + */ +void OHOSApplication::OnAbilityInactive(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + APP_LOGE("ContextDeal::OnAbilityInactive failed, ability is nullptr"); + return; + } + + APP_LOGI("OHOSApplication::OnAbilityInactive: called"); + for (auto callback : abilityLifecycleCallbacks_) { + if (callback != nullptr) { + callback->OnAbilityInactive(ability); + } + } +} + +/** + * + * Will be called when the given ability calls Ability->onBackground + * + * @param Ability Indicates the Ability object that calls the onBackground() method. + */ +void OHOSApplication::OnAbilityBackground(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + APP_LOGE("ContextDeal::OnAbilityBackground failed, ability is nullptr"); + return; + } + + APP_LOGI("OHOSApplication::OnAbilityBackground: called"); + for (auto callback : abilityLifecycleCallbacks_) { + if (callback != nullptr) { + callback->OnAbilityBackground(ability); + } + } +} + +/** + * + * Will be called when the given ability calls Ability->onForeground + * + * @param Ability Indicates the Ability object that calls the onForeground() method. + */ +void OHOSApplication::OnAbilityForeground(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + APP_LOGE("ContextDeal::OnAbilityForeground failed, ability is nullptr"); + return; + } + + APP_LOGI("OHOSApplication::OnAbilityForeground: called"); + for (auto callback : abilityLifecycleCallbacks_) { + if (callback != nullptr) { + callback->OnAbilityForeground(ability); + } + } +} + +/** + * + * Will be called when the given ability calls Ability->onActive + * + * @param Ability Indicates the Ability object that calls the onActive() method. + */ +void OHOSApplication::OnAbilityActive(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + APP_LOGE("ContextDeal::OnAbilityActive failed, ability is nullptr"); + return; + } + + APP_LOGI("OHOSApplication::OnAbilityActive: called"); + for (auto callback : abilityLifecycleCallbacks_) { + if (callback != nullptr) { + callback->OnAbilityActive(ability); + } + } +} + +/** + * + * Will be called when the given ability calls Ability->onStop + * + * @param Ability Indicates the Ability object that calls the onStop() method. + */ +void OHOSApplication::OnAbilityStop(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + APP_LOGE("ContextDeal::OnAbilityStop failed, ability is nullptr"); + return; + } + + APP_LOGI("OHOSApplication::OnAbilityStop: called"); + for (auto callback : abilityLifecycleCallbacks_) { + if (callback != nullptr) { + callback->OnAbilityStop(ability); + } + } +} + +/** + * + * @brief Register ElementsCallback with OHOSApplication + * + * @param callBack callBack when the system configuration of the device changes. + */ +void OHOSApplication::RegisterElementsCallbacks(const std::shared_ptr &callback) +{ + APP_LOGI("OHOSApplication::RegisterElementsCallbacks: called"); + + if (callback == nullptr) { + APP_LOGI("OHOSApplication::RegisterElementsCallbacks: observer is null"); + return; + } + + elementsCallbacks_.emplace_back(callback); +} + +/** + * + * @brief Unregister ElementsCallback with OHOSApplication + * + * @param callback RegisterElementsCallbacks`s callback + */ +void OHOSApplication::UnregisterElementsCallbacks(const std::shared_ptr &callback) +{ + APP_LOGI("OHOSApplication::UnregisterElementsCallbacks: called"); + + if (callback == nullptr) { + APP_LOGI("OHOSApplication::UnregisterElementsCallbacks: observer is null"); + return; + } + + elementsCallbacks_.remove(callback); +} + +/** + * + * @brief Will be Called when the system configuration of the device changes. + * + * @param config Indicates the new Configuration object. + */ +void OHOSApplication::OnConfigurationUpdated(const Configuration &config) +{ + APP_LOGI("OHOSApplication::OnConfigurationUpdated: called"); + if (!abilityRecordMgr_ || !configuration_) { + APP_LOGI("abilityRecordMgr_ or configuration_ is null"); + return; + } + + // Update own object configuration_ + std::vector changeKeyV; + configuration_->CompareDifferent(changeKeyV, config); + configuration_->Merge(changeKeyV, config); + + // Notify all abilities + APP_LOGI("Number of ability to be notified : [%{public}d]", static_cast(abilityRecordMgr_->GetRecordCount())); + for (const auto &abilityToken : abilityRecordMgr_->GetAllTokens()) { + auto abilityRecord = abilityRecordMgr_->GetAbilityItem(abilityToken); + if (abilityRecord && abilityRecord->GetAbilityThread()) { + abilityRecord->GetAbilityThread()->ScheduleUpdateConfiguration(config); + } + } + + for (auto callback : elementsCallbacks_) { + if (callback != nullptr) { + callback->OnConfigurationUpdated(nullptr, config); + } + } +} + +/** + * + * @brief Called when the system has determined to trim the memory, for example, + * when the ability is running in the background and there is no enough memory for + * running as many background processes as possible. + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + */ +void OHOSApplication::OnMemoryLevel(int level) +{ + APP_LOGI("OHOSApplication::OnMemoryLevel: called"); + for (auto callback : elementsCallbacks_) { + if (callback != nullptr) { + callback->OnMemoryLevel(level); + } + } +} + +/** + * + * @brief Will be called the application starts + * + */ +void OHOSApplication::OnStart() +{ + APP_LOGI("OHOSApplication::OnStart: called"); +} + +/** + * + * @brief Will be called the application ends + * + */ +void OHOSApplication::OnTerminate() +{ + APP_LOGI("OHOSApplication::OnTerminate: called"); +} + +/** + * + * @brief Called when an ability calls Ability#onSaveAbilityState(PacMap). + * You can implement your own logic in this method. + * @param outState IIndicates the {@link PacMap} object passed to the onSaveAbilityState() callback. + * + */ +void OHOSApplication::OnAbilitySaveState(const PacMap &outState) +{ + DispatchAbilitySavedState(outState); +} + +std::shared_ptr OHOSApplication::AddAbilityStage( + const std::shared_ptr &abilityRecord) +{ + if (abilityRecord == nullptr) { + APP_LOGE("AddAbilityStage:abilityRecord is nullptr"); + return nullptr; + } + const std::shared_ptr &abilityInfo = abilityRecord->GetAbilityInfo(); + if (abilityInfo == nullptr) { + APP_LOGE("AddAbilityStage:abilityInfo is nullptr"); + return nullptr; + } + std::string moduleName = abilityInfo->moduleName; + std::shared_ptr abilityStage; + auto iterator = abilityStages_.find(moduleName); + if (iterator == abilityStages_.end()) { + std::shared_ptr stageContext = std::make_shared(); + stageContext->SetParentContext(abilityRuntimeContext_); + stageContext->InitHapModuleInfo(abilityInfo); + std::shared_ptr hapModuleInfo = stageContext->GetHapModuleInfo(); + if (hapModuleInfo == nullptr) { + APP_LOGE("AddAbilityStage:hapModuleInfo is nullptr"); + return nullptr; + } + abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *hapModuleInfo); + abilityStage->Init(stageContext); + abilityStage->OnCreate(); + abilityStages_[moduleName] = abilityStage; + } else { + abilityStage = iterator->second; + } + const sptr &token = abilityRecord->GetToken(); + if (token == nullptr) { + APP_LOGE("AddAbilityStage:token is null"); + return nullptr; + } + abilityStage->AddAbility(token, abilityRecord); + return abilityStage->GetContext(); +} + +bool OHOSApplication::AddAbilityStage(const AppExecFwk::HapModuleInfo &hapModuleInfo) +{ + APP_LOGI("OHOSApplication::AddAbilityStage"); + if (abilityRuntimeContext_ == nullptr) { + APP_LOGE("OHOSApplication::AddAbilityStage abilityRuntimeContext_ is nullptr."); + return false; + } + + if (runtime_ == nullptr) { + APP_LOGE("OHOSApplication::AddAbilityStage abilityRuntimeContext_ is nullptr."); + return false; + } + + if (abilityStages_.find(hapModuleInfo.moduleName) != abilityStages_.end()) { + APP_LOGE("OHOSApplication::%{public}s: object already exists ", __func__); + return false; + } + + auto stageContext = std::make_shared(); + stageContext->SetParentContext(abilityRuntimeContext_); + stageContext->InitHapModuleInfo(hapModuleInfo); + auto moduleInfo = stageContext->GetHapModuleInfo(); + if (moduleInfo == nullptr) { + APP_LOGE("OHOSApplication::%{public}s: moduleInfo is nullptr", __func__); + return false; + } + auto abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *moduleInfo); + abilityStage->Init(stageContext); + abilityStage->OnCreate(); + abilityStages_[hapModuleInfo.moduleName] = abilityStage; + APP_LOGE("OHOSApplication::%{public}s: abilityStage insert and initialization", __func__); + return true; +} + +void OHOSApplication::CleanAbilityStage(const sptr &token, + const std::shared_ptr &abilityInfo) +{ + if (abilityInfo == nullptr) { + APP_LOGE("CleanAbilityStage:abilityInfo is nullptr"); + return; + } + if (token == nullptr) { + APP_LOGE("CleanAbilityStage:token is nullptr"); + return; + } + std::string moduleName = abilityInfo->moduleName; + auto iterator = abilityStages_.find(moduleName); + if (iterator != abilityStages_.end()) { + auto abilityStage = iterator->second; + abilityStage->RemoveAbility(token); + if (!abilityStage->ContainsAbility()) { + abilityStage->OnDestory(); + abilityStages_.erase(moduleName); + } + } +} + +std::shared_ptr OHOSApplication::GetAppContext() const +{ + return abilityRuntimeContext_; +} + +const std::unique_ptr& OHOSApplication::GetRuntime() +{ + return runtime_; +} + +void OHOSApplication::SetConfiguration(const Configuration &config) +{ + if (!configuration_) { + configuration_ = std::make_shared(config); + } +} + +void OHOSApplication::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName, std::string &flag) +{ + APP_LOGI("OHOSApplication::ScheduleAcceptWant: called"); + auto iter = abilityStages_.find(moduleName); + if (iter != abilityStages_.end()) { + auto abilityStage = iter->second; + if (abilityStage) { + flag = abilityStage->OnAcceptWant(want); + } + } +} + +std::shared_ptr OHOSApplication::GetConfiguration() +{ + return configuration_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/sys_mgr_client.cpp b/frameworks/kits/appkit/native/app/src/sys_mgr_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5322d19cd9f98fef429e0bc3ac353f229f4acda5 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/sys_mgr_client.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "sys_mgr_client.h" + +#include "app_log_wrapper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +SysMrgClient::SysMrgClient() : abilityManager_(nullptr) +{} + +SysMrgClient::~SysMrgClient() +{} + +/** + * + * Get the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility which want to get. + */ +sptr SysMrgClient::GetSystemAbility(const int32_t systemAbilityId) +{ + // use single instance of abilityManager_ + if (abilityManager_ == nullptr) { + std::lock_guard lock(saMutex_); + if (abilityManager_ == nullptr) { + abilityManager_ = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (abilityManager_ == nullptr) { + APP_LOGE("fail to GetSystemAbility abilityManager_ == nullptr."); + return nullptr; + } + } + } + return abilityManager_->GetSystemAbility(systemAbilityId); +} + +/** + * + * Register the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility which want to register. + * @param broker The systemAbility which want to be registered. + */ +void SysMrgClient::RegisterSystemAbility( + const int32_t __attribute__((unused)) systemAbilityId, sptr __attribute__((unused)) broker) +{ + (void)servicesMap_; +} + +/** + * + * Unregister the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility which want to unregister. + */ +void SysMrgClient::UnregisterSystemAbility(const int32_t systemAbilityId) +{} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/src/watchdog.cpp b/frameworks/kits/appkit/native/app/src/watchdog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b25197344d1a199447cd181a5c7a3e1db7f59d8 --- /dev/null +++ b/frameworks/kits/appkit/native/app/src/watchdog.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "watchdog.h" + +#include +#include +#include + +#include "app_log_wrapper.h" + + +namespace OHOS { +namespace AppExecFwk { +std::shared_ptr WatchDog::appMainHandler_ = nullptr; +std::shared_ptr WatchDog::currentHandler_ = nullptr; +bool WatchDog::appMainThreadIsAlive_ = false; + +WatchDog::WatchDog(const std::shared_ptr &runner) + : AppExecFwk::EventHandler(runner), watchDogRunner_(runner) +{} + +/** + * + * @brief Process the event. + * + * @param event the event want to be processed. + * + */ +void WatchDog::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event) +{ + auto eventId = event->GetInnerEventId(); + if (eventId == MAIN_THREAD_IS_ALIVE) { + WatchDog::appMainThreadIsAlive_ = true; + currentHandler_->RemoveTask(MAIN_THREAD_IS_ALIVE_MSG); + } +} + +void WatchDog::Init(const std::shared_ptr &mainHandler, const std::shared_ptr &watchDogHandler) +{ + APP_LOGI("watchdog is run !"); + WatchDog::appMainHandler_ = mainHandler; + WatchDog::currentHandler_ = watchDogHandler; + struct itimerval tick; + tick.it_value.tv_sec = INI_TIMER_FIRST_SECOND; + tick.it_value.tv_usec = INI_ZERO; + tick.it_interval.tv_sec = INI_TIMER_SECOND; + tick.it_interval.tv_usec = INI_ZERO; + + if (signal(SIGALRM, &WatchDog::Timer) == SIG_ERR) { + APP_LOGE("WatchDog::Timer signal fail."); + } + + if (setitimer(ITIMER_REAL, &tick, NULL) < INI_ZERO) { + APP_LOGE("Init WatchDog timer failed"); + } +} + +void WatchDog::Stop() +{ + APP_LOGI("Watchdog is stop !"); + if (watchDogRunner_) { + watchDogRunner_.reset(); + } + if (currentHandler_) { + currentHandler_.reset(); + } +} + +std::shared_ptr WatchDog::GetCurrentHandler() +{ + return currentHandler_; +} + +bool WatchDog::GetAppMainThreadState() +{ + return appMainThreadIsAlive_; +} + +void WatchDog::Timer(int sig) +{ + auto timeoutTask1 = [&]() { + appMainThreadIsAlive_ = false; + APP_LOGI("Waring : main thread is not response!"); + }; + currentHandler_->PostTask(timeoutTask1, MAIN_THREAD_IS_ALIVE_MSG, MAIN_THREAD_TIMEOUT_TIME); + appMainHandler_->SendEvent(MAIN_THREAD_IS_ALIVE); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/test/BUILD.gn b/frameworks/kits/appkit/native/test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..2131b281709d9fde0495e08aa6c936e237a7520f --- /dev/null +++ b/frameworks/kits/appkit/native/test/BUILD.gn @@ -0,0 +1,389 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +module_output_path = "ability_runtime/application_test" + +#APP_INNERKITS_PATH = "//foundation/appexecfwk/standard/interfaces/innerkits" +ABILITY_INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", + "//EOSP/communication/libsoftbus/../../../foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", + "${aafwk_path}/frameworks/kits/appkit/native/test/mock/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "${aafwk_path}/common/task_dispatcher/include/dispatcher", + "${aafwk_path}/common/task_dispatcher/include/task", + "${aafwk_path}/common/task_dispatcher/include/threading", + "${aafwk_path}/frameworks/kits/appkit/native/app/include/task", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + defines = [ + "APP_LOG_TAG = \"ApplicationUnitTest\"", + "LOG_DOMAIN = 0xD001151", + ] +} + +config("module_context_config") { + visibility = [ ":*" ] + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", + "//EOSP/communication/libsoftbus/../../../foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", + "${aafwk_path}/frameworks/kits/appkit/native/test/mock/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "${aafwk_path}/common/task_dispatcher/include/dispatcher", + "${aafwk_path}/common/task_dispatcher/include/task", + "${aafwk_path}/common/task_dispatcher/include/threading", + "${aafwk_path}/frameworks/kits/appkit/native/app/include/task", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + defines = [ + "APP_LOG_TAG = \"ApplicationUnitTest\"", + "LOG_DOMAIN = 0xD001151", + ] +} + +ohos_unittest("context_deal_interface_test") { + module_out_path = module_output_path + sources = [ + "mock/include/mock_ability_manager_client_interface1.cpp", + "mock/include/mock_resourceManager_interface1.cpp", + "unittest/context_deal_interface1_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("application_test") { + module_out_path = module_output_path + sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/application_context.cpp", + "../app/src/ohos_application.cpp", + "unittest/ability_stage_test.cpp", + "unittest/application_test.cpp", + "unittest/context_impl_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "${aafwk_path}/frameworks/kits/appkit:app_context", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + + #"${aafwk_path}/frameworks/kits/appkit:appkit_native", + ] + + external_deps = [ + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("context_container_test") { + module_out_path = module_output_path + sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "../app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "unittest/context_container_test.cpp", + ] + + configs = [ ":module_context_config" ] + + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("application_context_for_task_dispacher_test") { + module_out_path = module_output_path + sources = [ "unittest/application_context_for_task_dispacher_test.cpp" ] + + configs = [ ":module_context_config" ] + + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("context_deal_for_task_dispacher_test") { + module_out_path = module_output_path + sources = [ "unittest/context_deal_for_task_dispacher_test.cpp" ] + + configs = [ ":module_context_config" ] + + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("context_deal_test") { + module_out_path = module_output_path + sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "../app/src/ohos_application.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "mock/include/mock_ability_manager_client.cpp", + "unittest/context_deal_test.cpp", + ] + + configs = [ ":module_context_config" ] + + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("application_impl_test") { + module_out_path = module_output_path + sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/app/src/app_loader.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/app/src/application_context.cpp", + "../app/src/application_impl.cpp", + "../app/src/ohos_application.cpp", + "unittest/application_impl_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +config("ability_start_setting_config") { + visibility = [ ":*" ] + include_dirs = [ + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + "//foundation/appexecfwk/common/log/include/", + "//utils/native/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + ] +} + +ohos_unittest("ability_start_setting_test") { + module_out_path = module_output_path + + configs = [ + ":module_context_config", + ":ability_start_setting_config", + ] + + sources = [ + "//foundation/aafwk/standard/services/abilitymgr/src/ability_start_setting.cpp", + "unittest/ability_start_setting_test.cpp", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsbase", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("watchdog_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//third_party/json/include", + ] + + configs = [ + ":module_context_config", + ":ability_start_setting_config", + ] + + sources = [ "unittest/watchdog_test.cpp" ] + + deps = [ + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsbase", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### + +group("unittest") { + testonly = true + deps = [] + + deps += [ + ":ability_start_setting_test", + ":application_impl_test", + ":application_test", + ":context_container_test", + ":context_deal_test", + ":watchdog_test", + ] +} +############################################################################### diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_ability_lifecycle_callbacks.h b/frameworks/kits/appkit/native/test/mock/include/mock_ability_lifecycle_callbacks.h new file mode 100644 index 0000000000000000000000000000000000000000..a2cbc2f42c3051b2997345fad0f8f27bb3ffa0c8 --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_ability_lifecycle_callbacks.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_MOCK_ABILITY_LIFECYCLE_CALLBACK_H +#define FOUNDATION_APPEXECFWK_OHOS_MOCK_ABILITY_LIFECYCLE_CALLBACK_H + +#include "want.h" +#include "ability_lifecycle_callbacks.h" +#include +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; + +class MockAbilityLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + MockAbilityLifecycleCallbacks() = default; + virtual ~MockAbilityLifecycleCallbacks() = default; + + /** + * + * Will be called when the given ability calls Ability->onStart + * + * @param Ability Indicates the ability object that calls the onStart() method. + */ + virtual void OnAbilityStart(const std::shared_ptr &ability) + { + GTEST_LOG_(INFO) << "MockAbilityLifecycleCallbacks::OnAbilityStart called"; + } + + /** + * + * Will be called when the given ability calls Ability->onInactive + * + * @param Ability Indicates the Ability object that calls the onInactive() method. + */ + virtual void OnAbilityInactive(const std::shared_ptr &ability) + { + GTEST_LOG_(INFO) << "MockAbilityLifecycleCallbacks::OnAbilityInactive called"; + } + + /** + * + * Will be called when the given ability calls Ability->onBackground + * + * @param Ability Indicates the Ability object that calls the onBackground() method. + */ + virtual void OnAbilityBackground(const std::shared_ptr &ability) + { + GTEST_LOG_(INFO) << "MockAbilityLifecycleCallbacks::OnAbilityBackground called"; + } + + /** + * + * Will be called when the given ability calls Ability->onForeground + * + * @param Ability Indicates the Ability object that calls the onForeground() method. + */ + virtual void OnAbilityForeground(const std::shared_ptr &ability) + { + GTEST_LOG_(INFO) << "MockAbilityLifecycleCallbacks::OnAbilityForeground called"; + } + + /** + * + * Will be called when the given ability calls Ability->onActive + * + * @param Ability Indicates the Ability object that calls the onActive() method. + */ + virtual void OnAbilityActive(const std::shared_ptr &ability) + { + GTEST_LOG_(INFO) << "MockAbilityLifecycleCallbacks::OnAbilityActive called"; + } + + /** + * + * Will be called when the given ability calls Ability->onStop + * + * @param Ability Indicates the Ability object that calls the onStop() method. + */ + virtual void OnAbilityStop(const std::shared_ptr &ability) + { + GTEST_LOG_(INFO) << "MockAbilityLifecycleCallbacks::OnAbilityStop called"; + } + + /** + * + * Will be Called when an ability calls Ability#onSaveAbilityState(PacMap). + * + * @param outState Indicates the PacMap object passed to the onSaveAbilityState() callback. + */ + virtual void OnAbilitySaveState(const PacMap &outState) + { + GTEST_LOG_(INFO) << "MockAbilityLifecycleCallbacks::OnAbilityStop called"; + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_ABILITY_LIFECYCLE_CALLBACK_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client.cpp b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93c1ab66e57fc68f53d47a6942f74136f41be14a --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "mock_ability_manager_client.h" + +namespace OHOS { +namespace AAFwk { +std::shared_ptr MockAbilityManagerClient::mockinstance_ = nullptr; +std::shared_ptr MockAbilityManagerClient::GetInstance() +{ + if (mockinstance_ == nullptr) { + mockinstance_ = std::make_shared(); + } + return mockinstance_; +} + +std::shared_ptr AbilityManagerClient::GetInstance() +{ + if (instance_ == nullptr) { + instance_ = MockAbilityManagerClient::GetInstance(); + } + return instance_; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client.h b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client.h new file mode 100644 index 0000000000000000000000000000000000000000..156f0cabfbfe8f5e322f3526eb5fd3e4d39feec8 --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_MOCK_ABILITY_MANAGER_CLIENT_H +#define OHOS_APPEXECFWK_MOCK_ABILITY_MANAGER_CLIENT_H + +#include "gmock/gmock.h" + +#include "iremote_object.h" +#include "iremote_stub.h" +#include "ability_connect_callback_interface.h" +#include "ability_manager_errors.h" +#include "ability_scheduler_interface.h" +#include "ability_manager_interface.h" +#include "ability_manager_client.h" +#include "ability_context.h" +#include "want.h" + +namespace OHOS { +namespace AAFwk { +class MockAbilityManagerClient : public AbilityManagerClient { +public: + MockAbilityManagerClient() = default; + virtual ~MockAbilityManagerClient() = default; + MOCK_METHOD1(SetShowOnLockScreen, void(bool)); + static std::shared_ptr mockinstance_; + static std::shared_ptr GetInstance(); +}; +} // namespace AAFwk +} // namespace OHOS + +#endif /* OHOS_APPEXECFWK_MOCK_ABILITY_MANAGER_CLIENT_H */ \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.cpp b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a86fb9e7c0dce93cfde80581fa4891cfee4cc73 --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.cpp @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "gmock/gmock.h" +#include "mock_ability_manager_client_interface1.h" + +namespace OHOS { +namespace AAFwk { +MockAbilityManagerClient::MockAbilityManagerClient() +{ + startAbility_ = ERR_INVALID_OPERATION; + terminateAbility_ = ERR_INVALID_OPERATION; + terminateAbilityResult_ = ERR_INVALID_OPERATION; + isFirstInMission_ = ERR_INVALID_OPERATION; + removeMissionsE_ = ERR_INVALID_OPERATION; + terminateAbilityValue_ = 0; + removeMissions_ = 0; +} +MockAbilityManagerClient::~MockAbilityManagerClient() +{} + +std::shared_ptr MockAbilityManagerClient::mock_instance_ = nullptr; +bool MockAbilityManagerClient::mock_intanceIsNull_ = true; + +std::shared_ptr MockAbilityManagerClient::GetInstance() +{ + if (mock_instance_ == nullptr) { + mock_instance_ = std::make_shared(); + } + + return mock_instance_; +} + +void MockAbilityManagerClient::SetInstanceNull(bool flag) +{ + mock_intanceIsNull_ = flag; +} + +std::shared_ptr AbilityManagerClient::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (instance_ == nullptr) { + instance_ = MockAbilityManagerClient::GetInstance(); + } + } + if (MockAbilityManagerClient::mock_intanceIsNull_) + return instance_; + else + return nullptr; +} + +AbilityManagerClient::AbilityManagerClient() +{} + +AbilityManagerClient::~AbilityManagerClient() +{} + +ErrCode AbilityManagerClient::AttachAbilityThread( + const sptr &scheduler, const sptr &token) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr &token, int state) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::ScheduleConnectAbilityDone( + const sptr &token, const sptr &remoteObject) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::ScheduleDisconnectAbilityDone(const sptr &token) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::ScheduleCommandAbilityDone(const sptr &token) +{ + return ERR_OK; +} + +void AbilityManagerClient::AddWindowInfo(const sptr &token, int32_t windowToken) +{ + return; +} + +ErrCode AbilityManagerClient::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::ConnectAbility( + const Want &want, const sptr &connect, const sptr &callerToken) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::DisconnectAbility(const sptr &connect) +{ + return ERR_OK; +} + +sptr AbilityManagerClient::AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) +{ + return nullptr; +} + +ErrCode AbilityManagerClient::ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector &state) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::Connect() +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::GetAllStackInfo(StackInfo &stackInfo) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::StopServiceAbility(const Want &want, const sptr &callerToken) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::GetMissionSnapshot(const int32_t missionId, MissionSnapshot &snapshot) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::MoveMissionToTop(int32_t missionId) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::RemoveMissions(std::vector missionId) +{ + ErrCode ret = MockAbilityManagerClient::GetInstance()->GetRemoveMissions(); + if (ret == ERR_OK) { + MockAbilityManagerClient::GetInstance()->ChangeRemoveMissionsValue(); + } + return ret; +} + +ErrCode AbilityManagerClient::RemoveStack(int id) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::KillProcess(const std::string &bundleName) +{ + return ERR_OK; +} + +ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode) +{ + return MockAbilityManagerClient::GetInstance()->GetStartAbility(); +} + +ErrCode AbilityManagerClient::StartAbility(const Want &want, const sptr &callerToken, int requestCode) +{ + return MockAbilityManagerClient::GetInstance()->GetStartAbility(); +} + +ErrCode AbilityManagerClient::TerminateAbility(const sptr &callerToken, int requestCode) +{ + MockAbilityManagerClient::GetInstance()->SetTerminateAbilityValue(requestCode); + return MockAbilityManagerClient::GetInstance()->GetTerminateAbility(); +} + +ErrCode AbilityManagerClient::TerminateAbilityResult(const sptr &token, int startId) +{ + return MockAbilityManagerClient::GetInstance()->GetTerminateAbilityResult(); +} + +ErrCode MockAbilityManagerClient::GetStartAbility() +{ + return startAbility_; +} +ErrCode MockAbilityManagerClient::GetTerminateAbility() +{ + return terminateAbility_; +} +ErrCode MockAbilityManagerClient::GetTerminateAbilityResult() +{ + return terminateAbilityResult_; +} +ErrCode MockAbilityManagerClient::GetIsFirstInMission() +{ + return isFirstInMission_; +} +ErrCode MockAbilityManagerClient::GetRemoveMissions() +{ + return removeMissionsE_; +} + +void MockAbilityManagerClient::SetStartAbility(ErrCode tValue) +{ + startAbility_ = tValue; +} +void MockAbilityManagerClient::SetTerminateAbility(ErrCode tValue) +{ + terminateAbility_ = tValue; +} +void MockAbilityManagerClient::SetTerminateAbilityResult(ErrCode tValue) +{ + terminateAbilityResult_ = tValue; +} +void MockAbilityManagerClient::SetIsFirstInMission(ErrCode tValue) +{ + isFirstInMission_ = tValue; +} +void MockAbilityManagerClient::SetRemoveMissions(ErrCode tValue) +{ + removeMissionsE_ = tValue; +} + +int MockAbilityManagerClient::GetTerminateAbilityValue() +{ + return terminateAbilityValue_; +} +void MockAbilityManagerClient::SetTerminateAbilityValue(int nValue) +{ + terminateAbilityValue_ = nValue; +} +int MockAbilityManagerClient::GetRemoveMissionsValue() +{ + return removeMissions_; +} +void MockAbilityManagerClient::ChangeRemoveMissionsValue() +{ + ++removeMissions_; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h new file mode 100644 index 0000000000000000000000000000000000000000..d1a6b166fa04afa3fcf4f034809301a1b9ec6134 --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_MOCK_ABILITY_MANAGER_CLIENT2_H +#define OHOS_AAFWK_MOCK_ABILITY_MANAGER_CLIENT2_H + +#include + +#include "ability_connect_callback_interface.h" +#include "ability_context.h" +#include "ability_manager_client.h" +#include "ability_manager_errors.h" +#include "ability_manager_interface.h" +#include "ability_scheduler_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" +#include "want.h" + +namespace OHOS { +namespace AAFwk { +class MockAbilityManagerClient : public AbilityManagerClient { +public: + MockAbilityManagerClient(); + virtual ~MockAbilityManagerClient(); + + ErrCode GetStartAbility(); + ErrCode GetTerminateAbility(); + ErrCode GetTerminateAbilityResult(); + ErrCode GetIsFirstInMission(); + ErrCode GetRemoveMissions(); + + void SetStartAbility(ErrCode tValue); + void SetTerminateAbility(ErrCode tValue); + void SetTerminateAbilityResult(ErrCode tValue); + void SetIsFirstInMission(ErrCode tValue); + void SetRemoveMissions(ErrCode tValue); + + int GetTerminateAbilityValue(); + void SetTerminateAbilityValue(int nValue); + + int GetRemoveMissionsValue(); + void ChangeRemoveMissionsValue(); + + static std::shared_ptr mock_instance_; + static bool mock_intanceIsNull_; + + static std::shared_ptr GetInstance(); + static void SetInstanceNull(bool flag); + +private: + ErrCode startAbility_; + ErrCode terminateAbility_; + ErrCode terminateAbilityResult_; + ErrCode isFirstInMission_; + ErrCode removeMissionsE_; + + int terminateAbilityValue_; + int removeMissions_; +}; +} // namespace AAFwk +} // namespace OHOS + +namespace OHOS { +namespace AppExecFwk { +class MockIBundleMgr : public IRemoteStub { +public: + MockIBundleMgr(){}; + virtual ~MockIBundleMgr(){}; + + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) + { + return true; + }; + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) + { + return true; + }; + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) + { + return true; + }; + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) + { + return true; + }; + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) + { + return 0; + }; + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) + { + return std::string(""); + }; + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) + { + return true; + }; + virtual bool GetBundlesForUid(const int uid, std::vector &bundleNames) + { + return true; + }; + virtual bool GetNameForUid(const int uid, std::string &name) + { + return true; + }; + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) + { + return true; + }; + virtual std::string GetAppType(const std::string &bundleName) + { + return std::string(""); + }; + virtual bool CheckIsSystemAppByUid(const int uid) + { + return true; + }; + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) + { + return true; + }; + virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) + { + return true; + }; + virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) + { + return true; + }; + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) + { + return true; + }; + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) + { + return std::string(""); + }; + virtual bool GetBundleArchiveInfo(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) + { + return true; + }; + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) + { + return true; + }; + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) + { + return true; + }; + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) + { + return 0; + }; + virtual int CheckPermission(const std::string &bundleName, const std::string &permission) + { + return 0; + }; + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) + { + return true; + }; + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) + { + return true; + }; + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) + { + return true; + }; + virtual bool HasSystemCapability(const std::string &capName) + { + return true; + }; + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) + { + return true; + }; + virtual bool IsSafeMode() + { + return true; + }; + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) + { + return true; + }; + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) + { + return true; + }; + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) + { + return true; + }; + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) + { + return true; + }; + virtual bool UnregisterBundleStatusCallback() + { + return true; + }; + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) + { + return true; + }; + virtual bool IsApplicationEnabled(const std::string &bundleName) + { + return true; + }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) + { + return true; + }; + virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) + { + return true; + }; + virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) + { + return true; + }; + virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) + { + return std::string(""); + }; + virtual bool CanRequestPermission( + const std::string &bundleName, const std::string &permissionName, const int userId) + { + return true; + }; + virtual bool RequestPermissionFromUser( + const std::string &bundleName, const std::string &permission, const int userId) + { + return true; + }; + virtual bool RegisterAllPermissionsChanged(const sptr &callback) + { + return true; + }; + virtual bool RegisterPermissionsChanged( + const std::vector &uids, const sptr &callback) + { + return true; + }; + virtual bool UnregisterPermissionsChanged(const sptr &callback) + { + return true; + }; + virtual bool GetAllFormsInfo(std::vector &formInfos) + { + return true; + }; + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfos) + { + return true; + }; + virtual bool GetFormsInfoByModule( + const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) + { + return true; + }; + virtual sptr GetBundleInstaller() + { + return nullptr; + }; + bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) + { + return true; + } + bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) + { + return true; + } + bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) + { + return true; + } + bool NotifyAbilityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) + { + return true; + } + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } +}; + +class MockAbilityContextDeal : public ContextDeal { +public: + MockAbilityContextDeal(){}; + virtual ~MockAbilityContextDeal(){}; + + sptr GetBundleManager() const override + { + return sptr(new (std::nothrow) MockIBundleMgr()); + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_AAFWK_ABILITY_MANAGER_H diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_application.h b/frameworks/kits/appkit/native/test/mock/include/mock_application.h new file mode 100644 index 0000000000000000000000000000000000000000..8626a88de9fbdde80e181297cc4c5461d75398fb --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_application.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_MOCK_APPLICATION_H +#define FOUNDATION_APPEXECFWK_OHOS_MOCK_APPLICATION_H + +#include "ohos_application.h" +#include + +namespace OHOS { +namespace AppExecFwk { +class OHOSApplication; +class MockApplication : public OHOSApplication { +public: + MockApplication() = default; + virtual ~MockApplication() = default; + + enum { + APP_STATE_CREATE = 0, + APP_STATE_READY = 1, + APP_STATE_FOREGROUND = 2, + APP_STATE_BACKGROUND = 3, + APP_STATE_TERMINATED = 4 + }; + + virtual void OnReady() + { + GTEST_LOG_(INFO) << "MockApplication::OnReady called"; + state_ = APP_STATE_READY; + } + + virtual void OnForeground() + { + GTEST_LOG_(INFO) << "MockApplication::OnForeground called"; + state_ = APP_STATE_FOREGROUND; + } + + virtual void OnBackground() + { + GTEST_LOG_(INFO) << "MockApplication::OnBackground called"; + state_ = APP_STATE_BACKGROUND; + } + + virtual void OnConfigurationUpdated(const Configuration &config) + { + GTEST_LOG_(INFO) << "MockApplication::OnConfigurationUpdated called"; + onConfigurationUpdatedCalled_ = true; + } + + virtual void OnMemoryLevel(int level) + { + GTEST_LOG_(INFO) << "MockApplication::OnMemoryLevel called"; + onMemoryLevelCalled_ = true; + } + + virtual void OnStart() + { + GTEST_LOG_(INFO) << "MockApplication::OnStart called"; + state_ = APP_STATE_READY; + } + + virtual void OnTerminate() + { + GTEST_LOG_(INFO) << "MockApplication::OnTerminate called"; + state_ = APP_STATE_TERMINATED; + } + + int state_ = APP_STATE_CREATE; + bool onMemoryLevelCalled_ = false; + bool onConfigurationUpdatedCalled_ = false; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_APPLICATION_H diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_element_callback.h b/frameworks/kits/appkit/native/test/mock/include/mock_element_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..75ac813d6acd073b1c492948a418138e7b7e48da --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_element_callback.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_MOCK_ELEMENTS_CALLBACK_H +#define FOUNDATION_APPEXECFWK_OHOS_MOCK_ELEMENTS_CALLBACK_H + +#include "mock_element_callback.h" +#include + +namespace OHOS { +namespace AppExecFwk { +class MockElementsCallback : public ElementsCallback { +public: + MockElementsCallback() = default; + virtual ~MockElementsCallback() = default; + + /** + * + * Called when the system configuration of the device changes. + * + * @param config Indicates the new Configuration object. + * @param ability Indicates the new Ability object. + */ + virtual void OnConfigurationUpdated(const std::shared_ptr &ability, const Configuration &config) + { + GTEST_LOG_(INFO) << "MockElementsCallback::OnConfigurationUpdated called"; + } + + /** + * + * Will be called when the system has determined to trim the memory + * + * @param level Indicates the memory trim level, which shows the current memory usage status. + */ + virtual void OnMemoryLevel(int level) + { + GTEST_LOG_(INFO) << "MockElementsCallback::OnMemoryLevel called"; + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_ELEMENTS_CALLBACK_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp b/frameworks/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a57281033d96b5871e2bb44b62eb71f6e4e04fda --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "gmock/gmock.h" + +#include "mock_resourceManager_interface1.h" + +#include "res_config.h" +#include +#include +#include + +namespace OHOS { +namespace Global { +namespace Resource { +class ResourceManagerTestInstance : public ResourceManager2 { +public: + ResourceManagerTestInstance(){}; + virtual ~ResourceManagerTestInstance(){}; + + virtual bool AddResource(const char *path) + { + return false; + }; + + virtual RState UpdateResConfig(ResConfig &resConfig) + { + return ERROR; + }; + + virtual void GetResConfig(ResConfig &resConfig){}; + + virtual RState GetStringById(uint32_t id, std::string &outValue) + { + auto iter = StringById_.find(id); + if (iter == StringById_.end()) { + return ERROR; + } + outValue = iter->second; + return SUCCESS; + }; + virtual void SetStringById(uint32_t id, std::string &inValue) + { + if (!StringById_.empty()) { + StringById_.clear(); + } + StringById_[id] = inValue; + }; + + virtual RState GetStringByName(const char *name, std::string &outValue) + { + return ERROR; + }; + + virtual RState GetStringFormatById(std::string &outValue, uint32_t id, ...) + { + return ERROR; + }; + virtual void SetStringFormatById(std::string &inValue, uint32_t id, ...){}; + + virtual RState GetStringFormatByName(std::string &outValue, const char *name, ...) + { + return ERROR; + }; + + virtual RState GetStringArrayById(uint32_t id, std::vector &outValue) + { + auto iter = StringArrayById_.find(id); + if (iter == StringArrayById_.end()) { + return ERROR; + } + outValue = iter->second; + return SUCCESS; + }; + virtual void SetStringArrayById(uint32_t id, std::vector &inValue) + { + if (!StringArrayById_.empty()) { + StringArrayById_.clear(); + } + StringArrayById_[id] = inValue; + }; + + virtual RState GetStringArrayByName(const char *name, std::vector &outValue) + { + return ERROR; + }; + + virtual RState GetPatternById(uint32_t id, std::map &outValue) + { + auto iter = PatternById_.find(id); + if (iter == PatternById_.end()) { + return ERROR; + } + outValue = iter->second; + return SUCCESS; + }; + virtual void SetPatternById(uint32_t id, std::map &inValue) + { + if (!PatternById_.empty()) { + PatternById_.clear(); + } + PatternById_[id] = inValue; + }; + + virtual RState GetPatternByName(const char *name, std::map &outValue) + { + return ERROR; + }; + + virtual RState GetPluralStringById(uint32_t id, int quantity, std::string &outValue) + { + return ERROR; + }; + + virtual RState GetPluralStringByName(const char *name, int quantity, std::string &outValue) + { + return ERROR; + }; + + virtual RState GetPluralStringByIdFormat(std::string &outValue, uint32_t id, int quantity, ...) + { + return ERROR; + }; + + virtual RState GetPluralStringByNameFormat(std::string &outValue, const char *name, int quantity, ...) + { + return ERROR; + }; + + virtual RState GetThemeById(uint32_t id, std::map &outValue) + { + auto iter = ThemeById_.find(id); + if (iter == ThemeById_.end()) { + return ERROR; + } + outValue = iter->second; + return SUCCESS; + }; + virtual void SetThemeById(uint32_t id, std::map &inValue) + { + if (!ThemeById_.empty()) { + ThemeById_.clear(); + } + ThemeById_[id] = inValue; + }; + + virtual RState GetThemeByName(const char *name, std::map &outValue) + { + return ERROR; + }; + + virtual RState GetBooleanById(uint32_t id, bool &outValue) + { + return ERROR; + }; + + virtual RState GetBooleanByName(const char *name, bool &outValue) + { + return ERROR; + }; + + virtual RState GetIntegerById(uint32_t id, int &outValue) + { + return ERROR; + }; + + virtual RState GetIntegerByName(const char *name, int &outValue) + { + return ERROR; + }; + + virtual RState GetFloatById(uint32_t id, float &outValue) + { + return ERROR; + }; + + virtual RState GetFloatByName(const char *name, float &outValue) + { + return ERROR; + }; + + virtual RState GetIntArrayById(uint32_t id, std::vector &outValue) + { + auto iter = IntArrayById_.find(id); + if (iter == IntArrayById_.end()) { + return ERROR; + } + outValue = iter->second; + return SUCCESS; + }; + virtual void SetIntArrayById(uint32_t id, std::vector &inValue) + { + if (!IntArrayById_.empty()) { + IntArrayById_.clear(); + } + IntArrayById_[id] = inValue; + }; + + virtual RState GetIntArrayByName(const char *name, std::vector &outValue) + { + return ERROR; + }; + + virtual RState GetColorById(uint32_t id, uint32_t &outValue) + { + auto iter = ColorById_.find(id); + if (iter == ColorById_.end()) { + return ERROR; + } + outValue = iter->second; + return SUCCESS; + }; + virtual void SetColorById(uint32_t id, uint32_t &inValue) + { + if (!ColorById_.empty()) { + ColorById_.clear(); + } + ColorById_[id] = inValue; + }; + + virtual RState GetColorByName(const char *name, uint32_t &outValue) + { + return ERROR; + }; + + virtual RState GetProfileById(uint32_t id, std::string &outValue) + { + return ERROR; + }; + + virtual RState GetProfileByName(const char *name, std::string &outValue) + { + return ERROR; + }; + + virtual RState GetMediaById(uint32_t id, std::string &outValue) + { + return ERROR; + }; + + virtual RState GetMediaByName(const char *name, std::string &outValue) + { + return ERROR; + }; + +public: + std::map StringById_; + std::map StringFormatById_; + std::map> StringArrayById_; + std::map> PatternById_; + std::map> ThemeById_; + std::map> IntArrayById_; + std::map ColorById_; + + // static ResourceManagerTestInstance* instance; + static std::shared_ptr instance; +}; + +std::shared_ptr ResourceManagerTestInstance::instance = nullptr; + +std::shared_ptr CreateResourceManager2() +{ + if (ResourceManagerTestInstance::instance == nullptr) { /* */ + ResourceManagerTestInstance::instance = std::make_shared(); + } + return ResourceManagerTestInstance::instance; +} +} // namespace Resource +} // namespace Global +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.h b/frameworks/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.h new file mode 100644 index 0000000000000000000000000000000000000000..d6104e68cd7830b7ef30f03b78f9494ffc84b0c7 --- /dev/null +++ b/frameworks/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_MOCK_RESOURCE_MANAGER_RESOURCEMANAGER1_H +#define OHOS_MOCK_RESOURCE_MANAGER_RESOURCEMANAGER1_H + +#include "res_config.h" +#include +#include +#include + +#include "resource_manager.h" + +namespace OHOS { +namespace Global { +namespace Resource { +class ResourceManager2 : public ResourceManager { +public: + ResourceManager2(){}; + virtual ~ResourceManager2(){}; + + virtual bool AddResource(const char *path) = 0; + + virtual RState UpdateResConfig(ResConfig &resConfig) = 0; + + virtual void GetResConfig(ResConfig &resConfig) = 0; + + virtual RState GetStringById(uint32_t id, std::string &outValue) = 0; + virtual void SetStringById(uint32_t id, std::string &outValue) = 0; + + virtual RState GetStringByName(const char *name, std::string &outValue) = 0; + + virtual RState GetStringFormatById(std::string &outValue, uint32_t id, ...) = 0; + virtual void SetStringFormatById(std::string &outValue, uint32_t id, ...) = 0; + + virtual RState GetStringFormatByName(std::string &outValue, const char *name, ...) = 0; + + virtual RState GetStringArrayById(uint32_t id, std::vector &outValue) = 0; + virtual void SetStringArrayById(uint32_t id, std::vector &outValue) = 0; + + virtual RState GetStringArrayByName(const char *name, std::vector &outValue) = 0; + + virtual RState GetPatternById(uint32_t id, std::map &outValue) = 0; + virtual void SetPatternById(uint32_t id, std::map &outValue) = 0; + + virtual RState GetPatternByName(const char *name, std::map &outValue) = 0; + + virtual RState GetPluralStringById(uint32_t id, int quantity, std::string &outValue) = 0; + + virtual RState GetPluralStringByName(const char *name, int quantity, std::string &outValue) = 0; + + virtual RState GetPluralStringByIdFormat(std::string &outValue, uint32_t id, int quantity, ...) = 0; + + virtual RState GetPluralStringByNameFormat(std::string &outValue, const char *name, int quantity, ...) = 0; + + virtual RState GetThemeById(uint32_t id, std::map &outValue) = 0; + virtual void SetThemeById(uint32_t id, std::map &outValue) = 0; + + virtual RState GetThemeByName(const char *name, std::map &outValue) = 0; + + virtual RState GetBooleanById(uint32_t id, bool &outValue) = 0; + + virtual RState GetBooleanByName(const char *name, bool &outValue) = 0; + + virtual RState GetIntegerById(uint32_t id, int &outValue) = 0; + + virtual RState GetIntegerByName(const char *name, int &outValue) = 0; + + virtual RState GetFloatById(uint32_t id, float &outValue) = 0; + + virtual RState GetFloatByName(const char *name, float &outValue) = 0; + + virtual RState GetIntArrayById(uint32_t id, std::vector &outValue) = 0; + virtual void SetIntArrayById(uint32_t id, std::vector &outValue) = 0; + + virtual RState GetIntArrayByName(const char *name, std::vector &outValue) = 0; + + virtual RState GetColorById(uint32_t id, uint32_t &outValue) = 0; + virtual void SetColorById(uint32_t id, uint32_t &outValue) = 0; + + virtual RState GetColorByName(const char *name, uint32_t &outValue) = 0; + + virtual RState GetProfileById(uint32_t id, std::string &outValue) = 0; + + virtual RState GetProfileByName(const char *name, std::string &outValue) = 0; + + virtual RState GetMediaById(uint32_t id, std::string &outValue) = 0; + + virtual RState GetMediaByName(const char *name, std::string &outValue) = 0; +}; + +std::shared_ptr CreateResourceManager2(); +} // namespace Resource +} // namespace Global +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/ability_stage_test.cpp b/frameworks/kits/appkit/native/test/unittest/ability_stage_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72a02cc7af9fafce2b704fe09146ce290aa70f0f --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/ability_stage_test.cpp @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_local_record.h" +#include "ability_stage.h" +#include "context.h" +#include "context_impl.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class AbilityStageTest : public testing::Test { +public: + AbilityStageTest() : abilityStage_(nullptr) + {} + ~AbilityStageTest() + {} + std::shared_ptr abilityStage_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class MockToken : public OHOS::IRemoteObject { +public: + int32_t GetObjectRefCount() override + { + return 0; + } + + int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override + { + return 0; + } + + bool AddDeathRecipient(const sptr &recipient) override + { + return true; + } + + bool RemoveDeathRecipient(const sptr &recipient) override + { + return true; + } + + int Dump(int fd, const std::vector &args) override + { + return 0; + } +}; + +void AbilityStageTest::SetUpTestCase(void) +{} + +void AbilityStageTest::TearDownTestCase(void) +{} + +void AbilityStageTest::SetUp(void) +{ + abilityStage_ = std::make_shared(); +} + +void AbilityStageTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_AbilityStage_GetContext_001 + * @tc.name: GetContext + * @tc.desc: Test whether getContext is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_GetContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_001 start"; + std::shared_ptr context = abilityStage_->GetContext(); + EXPECT_EQ(context, nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_GetContext_002 + * @tc.name: GetContext + * @tc.desc: Test whether getContext is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ71I + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_GetContext_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_002 start"; + std::shared_ptr context = std::make_shared(); + abilityStage_->Init(context); + EXPECT_NE(abilityStage_->GetContext(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_002 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_AddAbility_001 + * @tc.name: AddAbility + * @tc.desc: Test whether AddAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_001, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_001 start"; + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_AddAbility_002 + * @tc.name: AddAbility + * @tc.desc: Test whether AddAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 start"; + sptr token = new MockToken(); + abilityStage_->AddAbility(token, std::make_shared(nullptr, nullptr)); + EXPECT_TRUE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_RemoveAbility_001 + * @tc.name: RemoveAbility + * @tc.desc: Test whether RemoveAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_RemoveAbility_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_001 start"; + EXPECT_FALSE(abilityStage_->ContainsAbility()); + abilityStage_->RemoveAbility(nullptr); + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_RemoveAbility_002 + * @tc.name: RemoveAbility + * @tc.desc: Test whether RemoveAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_RemoveAbility_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_002 start"; + sptr token = new MockToken(); + abilityStage_->AddAbility(token, std::make_shared(nullptr, nullptr)); + EXPECT_TRUE(abilityStage_->ContainsAbility()); + abilityStage_->RemoveAbility(token); + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_002 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_ContainsAbility_001 + * @tc.name: ContainsAbility + * @tc.desc: Test whether ContainsAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_ContainsAbility_001, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_001 start"; + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_ContainsAbility_002 + * @tc.name: ContainsAbility + * @tc.desc: Test whether ContainsAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_ContainsAbility_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_002 start"; + sptr token = new MockToken(); + abilityStage_->AddAbility(token, std::make_shared(nullptr, nullptr)); + EXPECT_TRUE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_002 end"; +} +} // namespace AppExecFwk +} \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/ability_start_setting_test.cpp b/frameworks/kits/appkit/native/test/unittest/ability_start_setting_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..1720b1739250b91ea2714f537e5982e65c45eebe --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/ability_start_setting_test.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "ability_start_setting.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +class AbilityStartSettingTest : public testing::Test { +public: + AbilityStartSettingTest() : abilityStartSetting_(nullptr) + {} + ~AbilityStartSettingTest() + {} + std::shared_ptr abilityStartSetting_ = nullptr; + + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AbilityStartSettingTest::SetUpTestCase(void) +{} + +void AbilityStartSettingTest::TearDownTestCase(void) +{} + +void AbilityStartSettingTest::SetUp(void) +{ + abilityStartSetting_ = AbilityStartSetting::GetEmptySetting(); +} + +void AbilityStartSettingTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ContextDeal_StartAbility_0100 + * @tc.name: IsEmpty + * @tc.desc: Test whether startability is called normally. + */ +HWTEST_F(AbilityStartSettingTest, AppExecFwk_IsEmpty_0100, Function | MediumTest | Level1) +{ + if (abilityStartSetting_ == nullptr) { + return; + } + EXPECT_EQ(true, abilityStartSetting_->IsEmpty()); + abilityStartSetting_->AddProperty(AbilityStartSetting::BOUNDS_KEY, std::string("system_bounds_test")); + abilityStartSetting_->AddProperty( + AbilityStartSetting::WINDOW_DISPLAY_ID_KEY, std::string("system_window_display_key_test")); + abilityStartSetting_->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, std::string("system_mode_key_test")); + EXPECT_EQ(false, abilityStartSetting_->IsEmpty()); + std::set set = abilityStartSetting_->GetPropertiesKey(); + EXPECT_EQ((unsigned int)3, set.size()); + std::set::iterator it = set.begin(); + if (it != set.end()) { + EXPECT_EQ(*it, AbilityStartSetting::BOUNDS_KEY.c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStartSetting_0100 test 1"; + } + it++; + if (it != set.end()) { + EXPECT_EQ(*it, AbilityStartSetting::WINDOW_DISPLAY_ID_KEY.c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStartSetting_0100 test 2"; + } + it++; + if (it != set.end()) { + EXPECT_EQ(*it, AbilityStartSetting::WINDOW_MODE_KEY.c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStartSetting_0100 test 3"; + } + Parcel parcel; + EXPECT_EQ(true, abilityStartSetting_->Marshalling(parcel)); + + AbilityStartSetting *setting = AbilityStartSetting::Unmarshalling(parcel); + std::shared_ptr startSetting(setting); + + if (startSetting == nullptr) { + return; + } + std::set unmarshallingSet = startSetting->GetPropertiesKey(); + EXPECT_EQ((unsigned int)3, unmarshallingSet.size()); + it = unmarshallingSet.begin(); + if (it != unmarshallingSet.end()) { + EXPECT_EQ(*it, AbilityStartSetting::BOUNDS_KEY.c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStartSetting_0100 test 4"; + } + it++; + if (it != unmarshallingSet.end()) { + EXPECT_EQ(*it, AbilityStartSetting::WINDOW_DISPLAY_ID_KEY.c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStartSetting_0100 test 5"; + } + it++; + if (it != unmarshallingSet.end()) { + EXPECT_EQ(*it, AbilityStartSetting::WINDOW_MODE_KEY.c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStartSetting_0100 test 6"; + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/application_context_for_task_dispacher_test.cpp b/frameworks/kits/appkit/native/test/unittest/application_context_for_task_dispacher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b33c8e042df9b22f4e870e0166984c3592c8e424 --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/application_context_for_task_dispacher_test.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_context.h" +#include "event_runner.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class ApplicationContextForTaskDispatcherTest : public testing::Test { +public: + ApplicationContextForTaskDispatcherTest() + {} + ~ApplicationContextForTaskDispatcherTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ApplicationContextForTaskDispatcherTest::SetUpTestCase(void) +{} + +void ApplicationContextForTaskDispatcherTest::TearDownTestCase(void) +{} + +void ApplicationContextForTaskDispatcherTest::SetUp(void) +{} + +void ApplicationContextForTaskDispatcherTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ApplicationContext_CreateParallelTaskDispatcher_0100 + * @tc.name: CreateParallelTaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ApplicationContextForTaskDispatcherTest, AppExecFwk_ApplicationContext_CreateParallelTaskDispatcher_0100, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationContext_CreateParallelTaskDispatcher_0100 start"; + std::shared_ptr appcontext = std::make_shared(); + std::string name("ParalleTest"); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr != appcontext->CreateParallelTaskDispatcher(name, high))); + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationContext_CreateParallelTaskDispatcher_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationContext_CreateSerialTaskDispatcher_0100 + * @tc.name: CreateSerialTaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ApplicationContextForTaskDispatcherTest, AppExecFwk_ApplicationContext_CreateSerialTaskDispatcher_0100, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationContext_CreateSerialTaskDispatcher_0100 start"; + std::shared_ptr appcontext = std::make_shared(); + std::string name("ParalleTest"); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr != appcontext->CreateSerialTaskDispatcher(name, high))); + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationContext_CreateSerialTaskDispatcher_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationContext_GetGlobalTaskDispatcher_0100 + * @tc.name: GetGlobalTaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ApplicationContextForTaskDispatcherTest, AppExecFwk_ApplicationContext_GetGlobalTaskDispatcher_0100, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationContext_GetGlobalTaskDispatcher_0100 start"; + std::shared_ptr appcontext = std::make_shared(); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr != appcontext->GetGlobalTaskDispatcher(high))); + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationContext_GetGlobalTaskDispatcher_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/application_impl_test.cpp b/frameworks/kits/appkit/native/test/unittest/application_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7896d1ec62ab39996444e89ea38f71bc0cfeaaf6 --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/application_impl_test.cpp @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_impl.h" +#include "mock_application.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class ApplicationImplTest : public testing::Test { +public: + ApplicationImplTest() + {} + ~ApplicationImplTest() + {} + std::shared_ptr applicationImpl_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ApplicationImplTest::SetUpTestCase(void) +{} + +void ApplicationImplTest::TearDownTestCase(void) +{} + +void ApplicationImplTest::SetUp(void) +{ + applicationImpl_ = std::make_shared(); +} + +void ApplicationImplTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformAppReady_0100 + * @tc.name: PerformAppReady + * @tc.desc: Test whether the performapready return value is false. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformAppReady_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformAppReady_0100 start"; + + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_CREATE); + bool ret = applicationImpl_->PerformAppReady(); + EXPECT_EQ(MockApplication::APP_STATE_READY, applicationImpl_->GetState()); + EXPECT_EQ(MockApplication::APP_STATE_READY, application->state_); + EXPECT_EQ(true, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformAppReady_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformAppReady_0200 + * @tc.name: PerformAppReady + * @tc.desc: Test whether the performapready return value is false. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformAppReady_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformAppReady_0200 start"; + + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_BACKGROUND); + bool ret = applicationImpl_->PerformAppReady(); + EXPECT_EQ(false, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformAppReady_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformForeground_0100 + * @tc.name: PerformForeground + * @tc.desc: Test whether setapplication and setstate are called normally, + * and verify whether the return value of performforegroup is true. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformForeground_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformForeground_0100 start"; + + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_READY); + bool ret = applicationImpl_->PerformForeground(); + EXPECT_EQ(MockApplication::APP_STATE_FOREGROUND, applicationImpl_->GetState()); + EXPECT_EQ(MockApplication::APP_STATE_FOREGROUND, application->state_); + EXPECT_EQ(true, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformForeground_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformForeground_0200 + * @tc.name: PerformForeground + * @tc.desc: Test whether setapplication and setstate are called normally, + * and verify whether the return value of performforegroup is false. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformForeground_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformForeground_0200 start"; + + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_CREATE); + bool ret = applicationImpl_->PerformForeground(); + EXPECT_EQ(false, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformForeground_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformForeground_0300 + * @tc.name: PerformForeground + * @tc.desc: Test whether setapplication and setstate are called normally, + * and verify whether the return value of performforegroup is true. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformForeground_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformForeground_0300 start"; + + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_BACKGROUND); + bool ret = applicationImpl_->PerformForeground(); + EXPECT_EQ(MockApplication::APP_STATE_FOREGROUND, applicationImpl_->GetState()); + EXPECT_EQ(MockApplication::APP_STATE_FOREGROUND, application->state_); + EXPECT_EQ(true, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformForeground_0300 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformBackground_0100 + * @tc.name: PerformBackground + * @tc.desc: Test whether setapplication and setstate are called normally, + * and verify whether the return value of performbackground is false. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformBackground_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformBackground_0100 start"; + + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_CREATE); + bool ret = applicationImpl_->PerformBackground(); + EXPECT_EQ(false, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformBackground_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformBackground_0200 + * @tc.name: PerformBackground + * @tc.desc: Test whether setapplication and setstate are called normally, + * and verify whether the return value of performbackground is true. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformBackground_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformBackground_0200 start"; + + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_FOREGROUND); + bool ret = applicationImpl_->PerformBackground(); + EXPECT_EQ(MockApplication::APP_STATE_BACKGROUND, applicationImpl_->GetState()); + EXPECT_EQ(MockApplication::APP_STATE_BACKGROUND, application->state_); + EXPECT_EQ(true, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformBackground_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformTerminate_0100 + * @tc.name: PerformTerminate + * @tc.desc: Test whether setapplication and setstate are called normally, + * and verify whether the return value of performterminate is false. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformTerminate_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformTerminate_0100 start"; + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_CREATE); + bool ret = applicationImpl_->PerformTerminate(); + EXPECT_EQ(false, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformTerminate_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformTerminate_0200 + * @tc.name: PerformTerminate + * @tc.desc: Test whether setapplication and setstate are called normally, + * and verify whether the return value of performterminate is true. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformTerminate_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformTerminate_0200 start"; + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->SetState(MockApplication::APP_STATE_BACKGROUND); + bool ret = applicationImpl_->PerformTerminate(); + EXPECT_EQ(MockApplication::APP_STATE_TERMINATED, applicationImpl_->GetState()); + EXPECT_EQ(MockApplication::APP_STATE_TERMINATED, application->state_); + EXPECT_EQ(true, ret); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformTerminate_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformMemoryLevel_0100 + * @tc.name: PerformMemoryLevel + * @tc.desc: Test whether setapplication and performmemorylevel are called normally. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformMemoryLevel_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformMemoryLevel_0100 start"; + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + applicationImpl_->PerformMemoryLevel(1); + EXPECT_EQ(true, application->onMemoryLevelCalled_); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformMemoryLevel_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_PerformConfigurationUpdated_0100 + * @tc.name: PerformConfigurationUpdated + * @tc.desc: Test whether setapplication and performmemorylevel are called normally. + */ +HWTEST_F( + ApplicationImplTest, AppExecFwk_ApplicationImpl_PerformConfigurationUpdated_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformConfigurationUpdated_0100 start"; + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + std::shared_ptr application = std::make_shared(); + applicationImpl_->SetApplication(application); + Configuration config; + applicationImpl_->PerformConfigurationUpdated(config); + EXPECT_EQ(true, application->onConfigurationUpdatedCalled_); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_PerformConfigurationUpdated_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ApplicationImpl_GetRecordId_0100 + * @tc.name: GetRecordId + * @tc.desc: Test whether setrecordid is called normally, and verify whether the return value of getrecordid is correct. + */ +HWTEST_F(ApplicationImplTest, AppExecFwk_ApplicationImpl_GetRecordId_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_GetRecordId_0100 start"; + EXPECT_NE(applicationImpl_, nullptr); + if (applicationImpl_ != nullptr) { + applicationImpl_->SetRecordId(1); + EXPECT_EQ(1, applicationImpl_->GetRecordId()); + } + GTEST_LOG_(INFO) << "AppExecFwk_ApplicationImpl_GetRecordId_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/application_test.cpp b/frameworks/kits/appkit/native/test/unittest/application_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c476997376b357b051d7d3721f41f3cf925d598 --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/application_test.cpp @@ -0,0 +1,476 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ohos_application.h" +#include "ability.h" +#include "mock_ability_lifecycle_callbacks.h" +#include "mock_element_callback.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace AppExecFwk { +class ApplicationTest : public testing::Test { +public: + ApplicationTest() + {} + ~ApplicationTest() + {} + std::shared_ptr ApplicationTest_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ApplicationTest::SetUpTestCase(void) +{} + +void ApplicationTest::TearDownTestCase(void) +{} + +void ApplicationTest::SetUp(void) +{ + ApplicationTest_ = std::make_shared(); +} + +void ApplicationTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0100 + * @tc.name: RegisterAbilityLifecycleCallbacks + * @tc.desc: Test whether registerabilitylifecyclecallbacks and are called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityActive(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0200 + * @tc.name: RegisterAbilityLifecycleCallbacks + * @tc.desc: Test the abnormal state of registerabilitylifecyclecallbacks. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0200 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + ApplicationTest_->RegisterAbilityLifecycleCallbacks(nullptr); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityActive(ability); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0200 end"; +} + +/** + * @tc.number: AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0100 + * @tc.name: UnregisterAbilityLifecycleCallbacks + * @tc.desc: Test whether unregisterabilitylife callbacks is successfully called. + */ +HWTEST_F( + ApplicationTest, AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityActive(ability); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0200 + * @tc.name: UnregisterAbilityLifecycleCallbacks + * @tc.desc: Test the abnormal state of unregisterability lifecycle callbacks. + */ +HWTEST_F( + ApplicationTest, AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0200 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(nullptr); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityActive(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterAbilityLifecycleCallbacks_0200 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnAbilityStart_0100 + * @tc.name: OnAbilityStart + * @tc.desc: Test whether onabilitystart is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnAbilityStart_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityStart_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityStart(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityStart_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnAbilityInactive_0100 + * @tc.name: OnAbilityInactive + * @tc.desc: Test whether onabilityinactive is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnAbilityInactive_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityInactive_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityInactive(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityInactive_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnAbilityBackground_0100 + * @tc.name: OnAbilityBackground + * @tc.desc: Test whether onabilitybackground is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnAbilityBackground_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityBackground_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityBackground(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityBackground_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnAbilityForeground_0100 + * @tc.name: OnAbilityForeground + * @tc.desc: Test whether onabilityforegroup is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnAbilityForeground_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityForeground_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityForeground(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityForeground_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnAbilityActive_0100 + * @tc.name: OnAbilityActive + * @tc.desc: Test whether onabilityactive is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnAbilityActive_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityActive_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityActive(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityActive_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnAbilityStop_0100 + * @tc.name: OnAbilityStop + * @tc.desc: Test whether onabilitystop is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnAbilityStop_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityStop_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + std::shared_ptr ability = std::make_shared(); + ApplicationTest_->OnAbilityStop(ability); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilityStop_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnConfigurationUpdated_0100 + * @tc.name: OnConfigurationUpdated + * @tc.desc: Test whether onconfigurationupdated is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnConfigurationUpdated_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnConfigurationUpdated_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterElementsCallbacks(callback); + + Configuration configuration; + ApplicationTest_->OnConfigurationUpdated(configuration); + + ApplicationTest_->UnregisterElementsCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnConfigurationUpdated_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnMemoryLevel_0100 + * @tc.name: OnMemoryLevel + * @tc.desc: Test whether onmemorylevel is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnMemoryLevel_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnMemoryLevel_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterElementsCallbacks(callback); + + ApplicationTest_->OnMemoryLevel(1); + + ApplicationTest_->UnregisterElementsCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnMemoryLevel_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnStart_0100 + * @tc.name: OnStart + * @tc.desc: Test whether OnStart is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnStart_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnStart_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + ApplicationTest_->OnStart(); + } + + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnStart_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnTerminate_0100 + * @tc.name: OnTerminate + * @tc.desc: Test whether OnTerminate is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnTerminate_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnTerminate_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + ApplicationTest_->OnTerminate(); + } + + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnTerminate_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_DispatchAbilitySavedState_0100 + * @tc.name: DispatchAbilitySavedState + * @tc.desc: Test whether dispatchabilitysavedstate is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_DispatchAbilitySavedState_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_DispatchAbilitySavedState_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + PacMap outState; + ApplicationTest_->DispatchAbilitySavedState(outState); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_DispatchAbilitySavedState_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnAbilitySaveState_0100 + * @tc.name: OnAbilitySaveState + * @tc.desc: Test whether the onablitysavestate is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_OnAbilitySaveState_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilitySaveState_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterAbilityLifecycleCallbacks(callback); + + PacMap outState; + ApplicationTest_->OnAbilitySaveState(outState); + + ApplicationTest_->UnregisterAbilityLifecycleCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_OnAbilitySaveState_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnMemoryLevel_0100 + * @tc.name: OnMemoryLevel + * @tc.desc: Test whether onmemorylevel is called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_RegisterElementsCallbacks_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterElementsCallbacks_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterElementsCallbacks(callback); + + ApplicationTest_->OnMemoryLevel(1); + + ApplicationTest_->UnregisterElementsCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterElementsCallbacks_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_OnMemoryLevel_0200 + * @tc.name: OnMemoryLevel + * @tc.desc: Test the abnormal state of onmemorylevel. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_RegisterElementsCallbacks_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterElementsCallbacks_0200 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterElementsCallbacks(nullptr); + + ApplicationTest_->OnMemoryLevel(1); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_RegisterElementsCallbacks_0200 end"; +} + +/** + * @tc.number: AppExecFwk_Application_UnregisterElementsCallbacks_0100 + * @tc.name: UnregisterElementsCallbacks + * @tc.desc: Test whether unregisterelementcallbacks are called normally. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_UnregisterElementsCallbacks_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterElementsCallbacks_0100 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterElementsCallbacks(callback); + ApplicationTest_->UnregisterElementsCallbacks(callback); + ApplicationTest_->OnMemoryLevel(1); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterElementsCallbacks_0100 end"; +} + +/** + * @tc.number: AppExecFwk_Application_UnregisterElementsCallbacks_0200 + * @tc.name: UnregisterElementsCallbacks + * @tc.desc: Test the unregisterelementcallbacks exception state. + */ +HWTEST_F(ApplicationTest, AppExecFwk_Application_UnregisterElementsCallbacks_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterElementsCallbacks_0200 start"; + + EXPECT_NE(ApplicationTest_, nullptr); + if (ApplicationTest_ != nullptr) { + std::shared_ptr callback = std::make_shared(); + ApplicationTest_->RegisterElementsCallbacks(callback); + ApplicationTest_->UnregisterElementsCallbacks(nullptr); + ApplicationTest_->OnMemoryLevel(1); + + ApplicationTest_->UnregisterElementsCallbacks(callback); + } + GTEST_LOG_(INFO) << "AppExecFwk_Application_UnregisterElementsCallbacks_0200 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9a1cda312b5d30edeccde4783b9f0306889108f --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp @@ -0,0 +1,578 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ohos_application.h" +#include "system_ability_definition.h" +#include "sys_mgr_client.h" +#include "ability_context.h" +#include "ability.h" +#include "context_container.h" +#include "context_deal.h" +#include "mock_bundle_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class ContextContainerTest : public testing::Test { +public: + ContextContainerTest() : context_(nullptr), contextDeal_(nullptr) + {} + ~ContextContainerTest() + {} + std::shared_ptr context_ = nullptr; + std::shared_ptr contextDeal_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ContextContainerTest::SetUpTestCase(void) +{} + +void ContextContainerTest::TearDownTestCase(void) +{} + +void ContextContainerTest::SetUp(void) +{ + OHOS::sptr bundleObject = new (std::nothrow) BundleMgrService(); + + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::ABILITY_MGR_SERVICE_ID, bundleObject); + context_ = std::make_shared(); + contextDeal_ = std::make_shared(); +} + +void ContextContainerTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleName_0100 + * @tc.name: GetBundleName + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleName_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string bundleName = "BundleName"; + info->bundleName = bundleName; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetBundleName().c_str(), bundleName.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleName_0200 + * @tc.name: GetBundleName + * @tc.desc: Test getbundlename exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleName_0200, Function | MediumTest | Level3) +{ + std::string bundleName = ""; + + EXPECT_STREQ(context_->GetBundleName().c_str(), bundleName.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleManager_0100 + * @tc.name: GetBundleManager + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlemanager is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleManager_0100, Function | MediumTest | Level1) +{ + context_->AttachBaseContext(contextDeal_); + + sptr ptr = context_->GetBundleManager(); + + EXPECT_NE(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleManager_0200 + * @tc.name: GetBundleManager + * @tc.desc: Test getbundlemanager exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleManager_0200, Function | MediumTest | Level3) +{ + sptr ptr = context_->GetBundleManager(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleCodePath_0100 + * @tc.name: GetBundleCodePath + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlecodepath is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleCodePath_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string codePath = "CodePath"; + info->codePath = codePath; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetBundleCodePath().c_str(), codePath.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleCodePath_0200 + * @tc.name: GetBundleCodePath + * @tc.desc: Test getbundlecodepath exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleCodePath_0200, Function | MediumTest | Level3) +{ + std::string codePath = ""; + std::string path = context_->GetBundleCodePath(); + + EXPECT_STREQ(path.c_str(), codePath.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetApplicationInfo_0100 + * @tc.name: GetApplicationInfo + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getapplicationinfo is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetApplicationInfo_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string bundleName = "BundleName"; + info->bundleName = bundleName; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetApplicationInfo()->bundleName.c_str(), bundleName.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetApplicationInfo_0200 + * @tc.name: GetApplicationInfo + * @tc.desc: Test getapplicationinfo exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetApplicationInfo_0200, Function | MediumTest | Level3) +{ + std::shared_ptr info = context_->GetApplicationInfo(); + EXPECT_EQ(info, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleResourcePath_0100 + * @tc.name: GetBundleResourcePath + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetBundleResourcePath is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleResourcePath_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string resourcePath = "ResourcePath"; + info->resourcePath = resourcePath; + contextDeal_->SetAbilityInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetBundleResourcePath().c_str(), resourcePath.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetBundleResourcePath_0200 + * @tc.name: GetBundleResourcePath + * @tc.desc: Test GetBundleResourcePath exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetBundleResourcePath_0200, Function | MediumTest | Level3) +{ + std::string path = context_->GetBundleResourcePath(); + std::string empty = ""; + EXPECT_STREQ(context_->GetBundleResourcePath().c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetAppType_0100 + * @tc.name: GetAppType + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetAppType is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetAppType_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + info->bundleName = "hello"; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + std::string path = context_->GetAppType(); + std::string appType = "system"; + + EXPECT_STREQ(context_->GetAppType().c_str(), appType.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetAppType_0200 + * @tc.name: GetAppType + * @tc.desc: Test GetAppType exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetAppType_0200, Function | MediumTest | Level3) +{ + std::string path = context_->GetAppType(); + std::string empty = ""; + EXPECT_STREQ(context_->GetAppType().c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetAbilityManager_0100 + * @tc.name: GetAbilityManager + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetAbilityManager is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetAbilityManager_0100, Function | MediumTest | Level1) +{ + context_->AttachBaseContext(contextDeal_); + + sptr ptr = context_->GetAbilityManager(); + EXPECT_NE(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetAbilityManager_0200 + * @tc.name: GetAbilityManager + * @tc.desc: Test GetAbilityManager exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetAbilityManager_0200, Function | MediumTest | Level3) +{ + sptr ptr = context_->GetAbilityManager(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetCodeCacheDir_0100 + * @tc.name: GetCodeCacheDir + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetCodeCacheDir is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetCodeCacheDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "CodeCacheDir"; + info->dataDir = dir; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + std::string dirCompare = "CodeCacheDir/code_cache"; + EXPECT_STREQ(context_->GetCodeCacheDir().c_str(), dirCompare.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetCodeCacheDir_0200 + * @tc.name: GetCodeCacheDir + * @tc.desc: Test GetCodeCacheDir exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetCodeCacheDir_0200, Function | MediumTest | Level3) +{ + std::string empty = ""; + EXPECT_STREQ(context_->GetCodeCacheDir().c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetCacheDir_0100 + * @tc.name: GetCacheDir + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetCacheDir is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetCacheDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "CacheDir"; + info->cacheDir = dir; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetCacheDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetCacheDir_0200 + * @tc.name: GetCacheDir + * @tc.desc: Test GetCacheDir exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetCacheDir_0200, Function | MediumTest | Level3) +{ + std::string empty = ""; + EXPECT_STREQ(context_->GetCacheDir().c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetDatabaseDir_0100 + * @tc.name: GetDatabaseDir + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetDatabaseDir is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetDatabaseDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "dataBaseDir"; + info->dataBaseDir = dir; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetDatabaseDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetCacheDir_0200 + * @tc.name: GetDatabaseDir + * @tc.desc: Test GetDatabaseDir exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetDatabaseDir_0200, Function | MediumTest | Level3) +{ + std::string empty = ""; + EXPECT_STREQ(context_->GetDatabaseDir().c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetDataDir_0100 + * @tc.name: GetDataDir + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetDataDir is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetDataDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "dataDir"; + info->dataDir = dir; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetDataDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetDataDir_0200 + * @tc.name: GetDataDir + * @tc.desc: Test GetDataDir exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetDataDir_0200, Function | MediumTest | Level3) +{ + std::string empty = ""; + EXPECT_STREQ(context_->GetDataDir().c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetDir_0100 + * @tc.name: GetDir + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetDir is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "dataDir"; + info->dataDir = dir; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + + std::string name = "name"; + std::string dirCompare = "dataDir/name"; + int mode = 0; + EXPECT_STREQ(context_->GetDir(name, mode).c_str(), dirCompare.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetDir_0200 + * @tc.name: GetDir + * @tc.desc: Test GetDir exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetDir_0200, Function | MediumTest | Level3) +{ + std::string empty = ""; + std::string name = "name"; + int mode = 0; + EXPECT_STREQ(context_->GetDir(name, mode).c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetFilesDir_0100 + * @tc.name: GetFilesDir + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetFilesDir is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetFilesDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "codePath"; + info->dataDir = dir; + contextDeal_->SetApplicationInfo(info); + context_->AttachBaseContext(contextDeal_); + std::string dirCompare = "codePath/files"; + EXPECT_STREQ(context_->GetFilesDir().c_str(), dirCompare.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetFilesDir_0200 + * @tc.name: GetFilesDir + * @tc.desc: Test GetFilesDir exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetFilesDir_0200, Function | MediumTest | Level3) +{ + std::string empty = ""; + EXPECT_STREQ(context_->GetFilesDir().c_str(), empty.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetAbilityInfo_0100 + * @tc.name: GetAbilityInfo + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetAbilityInfo is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetAbilityInfo_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string resourcePath = "ResourcePath"; + info->resourcePath = resourcePath; + contextDeal_->SetAbilityInfo(info); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(context_->GetAbilityInfo()->resourcePath.c_str(), resourcePath.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetAbilityInfo_0200 + * @tc.name: GetAbilityInfo + * @tc.desc: Test GetAbilityInfo exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetAbilityInfo_0200, Function | MediumTest | Level3) +{ + std::shared_ptr ptr = context_->GetAbilityInfo(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetContext_0100 + * @tc.name: GetContext + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetContext is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetContext_0100, Function | MediumTest | Level1) +{ + std::shared_ptr ability = std::make_shared(); + std::shared_ptr context(ability); + contextDeal_->SetContext(context); + context_->AttachBaseContext(contextDeal_); + + EXPECT_NE(context_->GetContext(), nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetContext_0200 + * @tc.name: GetContext + * @tc.desc: Test GetContext exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetContext_0200, Function | MediumTest | Level3) +{ + std::shared_ptr ptr = context_->GetContext(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetApplicationContext_0100 + * @tc.name: GetApplicationContext + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetApplicationContext is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetApplicationContext_0100, Function | MediumTest | Level1) +{ + std::shared_ptr application = std::make_shared(); + contextDeal_->SetApplicationContext(application); + context_->AttachBaseContext(contextDeal_); + + EXPECT_NE(nullptr, context_->GetApplicationContext()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetApplicationContext_0200 + * @tc.name: GetApplicationContext + * @tc.desc: Test GetApplicationContext exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetApplicationContext_0200, Function | MediumTest | Level3) +{ + std::shared_ptr ptr = context_->GetApplicationContext(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetProcessInfo_0100 + * @tc.name: GetProcessInfo + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetProcessInfo is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetProcessInfo_0100, Function | MediumTest | Level1) +{ + std::string name = "OHOS"; + pid_t id = 0; + ProcessInfo info(name, id); + std::shared_ptr processinfo = std::make_shared(info); + contextDeal_->SetProcessInfo(processinfo); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(name.c_str(), context_->GetProcessInfo()->GetProcessName().c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetProcessInfo_0200 + * @tc.name: GetProcessInfo + * @tc.desc: Test GetProcessInfo exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetProcessInfo_0200, Function | MediumTest | Level3) +{ + std::shared_ptr ptr = context_->GetProcessInfo(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetProcessName_0100 + * @tc.name: GetProcessName + * @tc.desc: Test whether AttachBaseContext is called normally, + * and verify whether the return value of GetProcessName is correct. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextDeal_GetProcessName_0100, Function | MediumTest | Level1) +{ + std::string name = "OHOS"; + pid_t id = 0; + ProcessInfo info(name, id); + std::shared_ptr processinfo = std::make_shared(info); + contextDeal_->SetProcessInfo(processinfo); + context_->AttachBaseContext(contextDeal_); + + EXPECT_STREQ(name.c_str(), context_->GetProcessName().c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextContainer_GetProcessName_0200 + * @tc.name: GetProcessName + * @tc.desc: Test GetProcessName exception status. + */ +HWTEST_F(ContextContainerTest, AppExecFwk_ContextContainer_GetProcessName_0200, Function | MediumTest | Level3) +{ + std::string empty = ""; + std::string name = context_->GetProcessName(); + EXPECT_STREQ(empty.c_str(), name.c_str()); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/context_deal_for_task_dispacher_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_deal_for_task_dispacher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec6ff8f756b9a71666ae74898b4266b27cd3ac24 --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/context_deal_for_task_dispacher_test.cpp @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_context.h" +#include "context_deal.h" +#include "event_runner.h" + + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class ContextDealForTaskDispatcherTest : public testing::Test { +public: + ContextDealForTaskDispatcherTest() + {} + ~ContextDealForTaskDispatcherTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ContextDealForTaskDispatcherTest::SetUpTestCase(void) +{} + +void ContextDealForTaskDispatcherTest::TearDownTestCase(void) +{} + +void ContextDealForTaskDispatcherTest::SetUp(void) +{} + +void ContextDealForTaskDispatcherTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetUITaskDispatcher_0100 + * @tc.name: GetUITaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_GetUITaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetUITaskDispatcher_0100 start"; + std::shared_ptr runner = EventRunner::Create(false); + std::shared_ptr contextdeal = std::make_shared(); + contextdeal->SetRunner(runner); + EXPECT_TRUE((nullptr != contextdeal->GetUITaskDispatcher())); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetUITaskDispatcher_0100 end"; +} +/** + * @tc.number: AppExecFwk_ContextDeal_GetUITaskDispatcher_0200 + * @tc.name: GetUITaskDispatcher + * @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_GetUITaskDispatcher_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetUITaskDispatcher_0200 start"; + std::shared_ptr contextdeal = std::make_shared(); + EXPECT_TRUE((nullptr == contextdeal->GetUITaskDispatcher())); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetUITaskDispatcher_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetMainTaskDispatcher_0100 + * @tc.name: GetMainTaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_GetMainTaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetMainTaskDispatcher_0100 start"; + std::shared_ptr runner = EventRunner::Create(false); + std::shared_ptr contextdeal = std::make_shared(); + contextdeal->SetRunner(runner); + EXPECT_TRUE((nullptr != contextdeal->GetMainTaskDispatcher())); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetMainTaskDispatcher_0100 end"; +} +/** + * @tc.number: AppExecFwk_ContextDeal_GetMainTaskDispatcher_0200 + * @tc.name: GetMainTaskDispatcher + * @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_GetMainTaskDispatcher_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetMainTaskDispatcher_0200 start"; + std::shared_ptr contextdeal = std::make_shared(); + EXPECT_TRUE((nullptr == contextdeal->GetMainTaskDispatcher())); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetMainTaskDispatcher_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0100 + * @tc.name: CreateParallelTaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0100 start"; + std::shared_ptr appcontext = std::make_shared(); + std::shared_ptr contextdeal = std::make_shared(); + contextdeal->SetApplicationContext(appcontext); + std::string name("ParalleTest"); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr != contextdeal->CreateParallelTaskDispatcher(name, high))); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0100 end"; +} +/** + * @tc.number: AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0200 + * @tc.name: CreateParallelTaskDispatcher + * @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0200 start"; + std::shared_ptr contextdeal = std::make_shared(); + std::string name("ParalleTest"); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr == contextdeal->CreateParallelTaskDispatcher(name, high))); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateParallelTaskDispatcher_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0100 + * @tc.name: CreateSerialTaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0100 start"; + std::shared_ptr appcontext = std::make_shared(); + std::shared_ptr contextdeal = std::make_shared(); + contextdeal->SetApplicationContext(appcontext); + std::string name("ParalleTest"); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr != contextdeal->CreateSerialTaskDispatcher(name, high))); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0100 end"; +} +/** + * @tc.number: AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0200 + * @tc.name: CreateSerialTaskDispatcher + * @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0200 start"; + std::shared_ptr contextdeal = std::make_shared(); + std::string name("Serial"); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr == contextdeal->CreateSerialTaskDispatcher(name, high))); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_CreateSerialTaskDispatcher_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0100 + * @tc.name: GetGlobalTaskDispatcher + * @tc.desc: Test whether attachbasecontext is called normally, + * and verify whether the return value of getbundlename is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0100 start"; + std::shared_ptr appcontext = std::make_shared(); + std::shared_ptr contextdeal = std::make_shared(); + contextdeal->SetApplicationContext(appcontext); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr != contextdeal->GetGlobalTaskDispatcher(high))); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0100 end"; +} +/** + * @tc.number: AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0200 + * @tc.name: GetGlobalTaskDispatcher + * @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct. + */ +HWTEST_F(ContextDealForTaskDispatcherTest, AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0200 start"; + std::shared_ptr contextdeal = std::make_shared(); + TaskPriority high = TaskPriority::HIGH; + EXPECT_TRUE((nullptr == contextdeal->GetGlobalTaskDispatcher(high))); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetGlobalTaskDispatcher_0200 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cba43f8fd1cb6e88387307ec123f7b69ba6d4fa0 --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp @@ -0,0 +1,511 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "gmock/gmock.h" +#include +#include + +#include "ability_handler.h" +#include "ability_info.h" +#include "ability.h" +#include "context_deal.h" +#include "ohos_application.h" + +#include "mock_ability_manager_client_interface1.h" +#include "mock_resourceManager_interface1.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; + +class ContextDealInterfaceTest : public testing::Test { +public: + ContextDealInterfaceTest() + {} + ~ContextDealInterfaceTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ContextDealInterfaceTest::SetUpTestCase(void) +{} +void ContextDealInterfaceTest::TearDownTestCase(void) +{} +void ContextDealInterfaceTest::SetUp() +{} +void ContextDealInterfaceTest::TearDown() +{} + +/** + * @tc.number: AppExecFwk_ContextDeal_SetColorMode_0100 + * @tc.name: SetColorMode + * @tc.desc: Test the attachbasecontext call to verify that the return value of SetColorMode is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetColorMode_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetColorMode_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + int testValue = static_cast(OHOS::AppExecFwk::ModuleColorMode::DARK); + contextDeal->SetAbilityInfo(abilityInfo); + contextDeal->SetColorMode(testValue); + EXPECT_EQ(testValue, contextDeal->GetColorMode()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetColorMode_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_SetColorMode_0200 + * @tc.name: SetColorMode + * @tc.desc: Test the attachbasecontext call to verify that the return value of SetColorMode is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetColorMode_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetColorMode_0200 start"; + std::shared_ptr contextDeal = std::make_shared(); + int testValue = static_cast(OHOS::AppExecFwk::ModuleColorMode::DARK); + contextDeal->SetColorMode(testValue); + EXPECT_GT(testValue, contextDeal->GetColorMode()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetColorMode_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetColorMode_0100 + * @tc.name: GetColorMode + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetColorMode is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetColorMode_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColorMode_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + int testValue = static_cast(OHOS::AppExecFwk::ModuleColorMode::DARK); + contextDeal->SetAbilityInfo(abilityInfo); + contextDeal->SetColorMode(testValue); + EXPECT_EQ(testValue, contextDeal->GetColorMode()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColorMode_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetColorMode_0200 + * @tc.name: GetColorMode + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetColorMode is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetColorMode_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColorMode_0200 start"; + std::shared_ptr contextDeal = std::make_shared(); + int testValue = static_cast(OHOS::AppExecFwk::ModuleColorMode::DARK); + contextDeal->SetColorMode(testValue); + EXPECT_GT(testValue, contextDeal->GetColorMode()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColorMode_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_SetTheme_0100 + * @tc.name: SetTheme + * @tc.desc: Test the attachbasecontext call to verify that the return value of SetTheme is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetTheme_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0100 start"; + int testValue = 1; + std::map testList = { + {"Pattern1", "PatternA"}, {"Pattern2", "PatternB"}, {"Pattern3", "PatternC"}}; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + resourceManager->SetThemeById(testValue, testList); + contextDeal->initResourceManager(resourceManager); + contextDeal->SetTheme(testValue); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_SetTheme_0200 + * @tc.name: SetTheme + * @tc.desc: Test the attachbasecontext call to verify that the return value of SetTheme is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetTheme_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0200 start"; + int testValue = 1; + std::shared_ptr contextDeal = std::make_shared(); + contextDeal->SetTheme(testValue); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetPreferencesDir_0100 + * @tc.name: GetPreferencesDir + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetPreferencesDir is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetPreferencesDir_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPreferencesDir_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + const std::string testValue = "./1234test/preferences"; + abilityInfo->name = "test1234.1234test"; + applicationInfo->dataDir = "."; + contextDeal->SetAbilityInfo(abilityInfo); + contextDeal->SetApplicationInfo(applicationInfo); + EXPECT_STREQ(testValue.c_str(), contextDeal->GetPreferencesDir().c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPreferencesDir_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetPreferencesDir_0101 + * @tc.name: GetPreferencesDir + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetPreferencesDir is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetPreferencesDir_0101, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPreferencesDir_0101 start"; + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + const std::string testValue = "./1234test/preferences"; + abilityInfo->name = "1234test"; + abilityInfo->isNativeAbility = true; + applicationInfo->dataDir = "."; + contextDeal->SetAbilityInfo(abilityInfo); + contextDeal->SetApplicationInfo(applicationInfo); + EXPECT_STREQ(testValue.c_str(), contextDeal->GetPreferencesDir().c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPreferencesDir_0101 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetPreferencesDir_0200 + * @tc.name: GetPreferencesDir + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetPreferencesDir is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetPreferencesDir_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPreferencesDir_0200 start"; + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + const std::string testValue = ""; + abilityInfo->name = "1234test"; + abilityInfo->isNativeAbility = false; + applicationInfo->dataDir = "."; + contextDeal->SetAbilityInfo(abilityInfo); + contextDeal->SetApplicationInfo(applicationInfo); + EXPECT_STREQ(testValue.c_str(), contextDeal->GetPreferencesDir().c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPreferencesDir_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetPattern_0100 + * @tc.name: GetPattern + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetPattern is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetPattern_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPattern_0100 start"; + int testValue = 0; + std::map testList = { + {"Pattern1", "PatternA"}, {"Pattern2", "PatternB"}, {"Pattern3", "PatternC"}}; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + resourceManager->SetPatternById(testValue, testList); + contextDeal->initResourceManager(resourceManager); + contextDeal->SetPattern(testValue); + std::map retVal = contextDeal->GetPattern(); + EXPECT_TRUE((retVal == testList)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetPattern_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetTheme_0100 + * @tc.name: GetTheme + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetTheme is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetTheme_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetTheme_0100 start"; + int testValue = 0; + std::map testList = {{"Theme1", "ThemeA"}, {"Theme2", "ThemeB"}, {"Theme3", "ThemeC"}}; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + resourceManager->SetThemeById(testValue, testList); + contextDeal->initResourceManager(resourceManager); + std::map retVal = contextDeal->GetTheme(); + + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetTheme_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetString_ById_0100 + * @tc.name: GetString + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetString is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetString_ById_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ById_0100 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + std::string testValue = "GetString test"; + resourceManager->SetStringById(testCount, testValue); + contextDeal->initResourceManager(resourceManager); + EXPECT_STREQ(testValue.c_str(), contextDeal->GetString(testCount).c_str()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ById_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100 + * @tc.name: GetString + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetString is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100 start"; + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetStringArray_0100 + * @tc.name: GetStringArray + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetStringArray is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetStringArray_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetStringArray_0100 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + std::vector testValue = {"123", "456", "789"}; + resourceManager->SetStringArrayById(testCount, testValue); + contextDeal->initResourceManager(resourceManager); + std::vector retVal = contextDeal->GetStringArray(testCount); + EXPECT_TRUE((retVal == testValue)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetStringArray_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetStringArray_0200 + * @tc.name: GetStringArray + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetStringArray is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetStringArray_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetStringArray_0200 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + std::vector testValue = {"123", "456", "789"}; + resourceManager->SetStringArrayById(testCount + 1, testValue); + contextDeal->initResourceManager(resourceManager); + std::vector retVal = contextDeal->GetStringArray(testCount); + EXPECT_FALSE((retVal == testValue)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetStringArray_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetIntArray_0100 + * @tc.name: GetIntArray + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetIntArray is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetIntArray_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetIntArray_0100 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + std::vector testValue = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; + resourceManager->SetIntArrayById(testCount, testValue); + contextDeal->initResourceManager(resourceManager); + std::vector retVal = contextDeal->GetIntArray(testCount); + EXPECT_TRUE((retVal == testValue)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetIntArray_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetIntArray_0200 + * @tc.name: GetIntArray + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetIntArray is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetIntArray_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetIntArray_0200 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + std::vector testValue = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; + resourceManager->SetIntArrayById(testCount + 1, testValue); + contextDeal->initResourceManager(resourceManager); + std::vector retVal = contextDeal->GetIntArray(testCount); + EXPECT_FALSE((retVal == testValue)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetIntArray_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetColor_0100 + * @tc.name: GetColor + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetColor is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetColor_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColor_0100 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + uint32_t testValue = 1; + const int testVal = static_cast(testValue); + resourceManager->SetColorById(testCount, testValue); + contextDeal->initResourceManager(resourceManager); + EXPECT_EQ(testVal, contextDeal->GetColor(testCount)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColor_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetColor_0200 + * @tc.name: GetColor + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetColor is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetColor_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColor_0200 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + uint32_t testValue = 1; + const int testVal = static_cast(testValue); + resourceManager->SetColorById(testCount + 1, testValue); + contextDeal->initResourceManager(resourceManager); + EXPECT_NE(testVal, contextDeal->GetColor(testCount)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetColor_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetThemeId_0100 + * @tc.name: GetThemeId + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetThemeId is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetThemeId_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetThemeId_0100 start"; + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetThemeId_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetDisplayOrientation_0100 + * @tc.name: GetDisplayOrientation + * @tc.desc: Test the attachbasecontext call to verify that the return value of GetDisplayOrientation is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetDisplayOrientation_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetDisplayOrientation_0100 start"; + std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + int testValue = 1; + abilityInfo->orientation = static_cast(testValue); + contextDeal->SetAbilityInfo(abilityInfo); + EXPECT_EQ(testValue, contextDeal->GetDisplayOrientation()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetDisplayOrientation_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_SetPattern_0100 + * @tc.name: SetPattern + * @tc.desc: Test the attachbasecontext call to verify that the return value of SetPattern is correct. + */ +HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetPattern_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetPattern_0100 start"; + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); + std::shared_ptr contextDeal = std::make_shared(); + int testCount = 0; + std::map testList = {{"123", "abc"}, {"456", "def"}}; + resourceManager->SetPatternById(testCount, testList); + contextDeal->initResourceManager(resourceManager); + contextDeal->SetPattern(testCount); + std::map retVal; + EXPECT_FALSE((retVal == testList)); + retVal = contextDeal->GetPattern(); + EXPECT_TRUE((retVal == testList)); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetPattern_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_TerminateAndRemoveMission_0100 + * @tc.name: TerminateAndRemoveMission + * @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbility is correct. + */ +HWTEST_F( + ContextDealInterfaceTest, AppExecFwk_ContextDeal_TerminateAndRemoveMission_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_TerminateAndRemoveMission_0100 start"; + const ErrCode mockValue = ERR_OK; + OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetRemoveMissions(mockValue); + std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr lifeCycleStateInfo = std::make_shared(); + int testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue(); + lifeCycleStateInfo->missionId = 0; + contextDeal->SetLifeCycleStateInfo(*lifeCycleStateInfo); + contextDeal->TerminateAndRemoveMission(); + EXPECT_NE(testValue, AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_TerminateAndRemoveMission_0100 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_TerminateAndRemoveMission_0200 + * @tc.name: TerminateAndRemoveMission + * @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbility is correct. + */ +HWTEST_F( + ContextDealInterfaceTest, AppExecFwk_ContextDeal_TerminateAndRemoveMission_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_TerminateAndRemoveMission_0200 start"; + const ErrCode mockValue = ERR_OK; + OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetRemoveMissions(mockValue); + OHOS::AAFwk::MockAbilityManagerClient::SetInstanceNull(false); + std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr lifeCycleStateInfo = std::make_shared(); + int testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue(); + lifeCycleStateInfo->missionId = 0; + contextDeal->SetLifeCycleStateInfo(*lifeCycleStateInfo); + contextDeal->TerminateAndRemoveMission(); + EXPECT_EQ(testValue, AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue()); + OHOS::AAFwk::MockAbilityManagerClient::SetInstanceNull(true); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_TerminateAndRemoveMission_0200 end"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_TerminateAndRemoveMission_0300 + * @tc.name: TerminateAndRemoveMission + * @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbility is correct. + */ +HWTEST_F( + ContextDealInterfaceTest, AppExecFwk_ContextDeal_TerminateAndRemoveMission_0300, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_TerminateAndRemoveMission_0300 start"; + const ErrCode mockValue = ERR_INVALID_VALUE; + OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetRemoveMissions(mockValue); + std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr lifeCycleStateInfo = std::make_shared(); + int testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue(); + lifeCycleStateInfo->missionId = 0; + contextDeal->SetLifeCycleStateInfo(*lifeCycleStateInfo); + contextDeal->TerminateAndRemoveMission(); + EXPECT_EQ(testValue, AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue()); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_TerminateAndRemoveMission_0300 end"; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/native/test/unittest/context_deal_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_deal_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d994d0b5ad2cd4107fe7aeb3d20fc12e8794c565 --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/context_deal_test.cpp @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ohos_application.h" +#include "ability.h" +#include "context_deal.h" +#include "process_info.h" +#include "system_ability_definition.h" +#include "sys_mgr_client.h" +#include "mock_bundle_manager.h" +#include "mock_ability_manager_client.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class ContextDealTest : public testing::Test { +public: + ContextDealTest() : context_(nullptr) + {} + ~ContextDealTest() + {} + std::shared_ptr context_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ContextDealTest::SetUpTestCase(void) +{} + +void ContextDealTest::TearDownTestCase(void) +{} + +void ContextDealTest::SetUp(void) +{ + OHOS::sptr bundleObject = new (std::nothrow) BundleMgrService(); + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::ABILITY_MGR_SERVICE_ID, bundleObject); + context_ = std::make_shared(); +} + +void ContextDealTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ContextDeal_StartAbility_0100 + * @tc.name: StartAbility + * @tc.desc: Test whether startability is called normally. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_StartAbility_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_StartAbility_0100 start"; + AAFwk::Want want; + int requestCode = 0; + context_->StartAbility(want, requestCode); + GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_StartAbility_0100 end, StartAbility is empty"; +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetBundleName_0100 + * @tc.name: GetBundleName + * @tc.desc: Verify that the GetBundleName return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetBundleName_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string bundleName = "BundleName"; + info->bundleName = bundleName; + context_->SetApplicationInfo(info); + + EXPECT_STREQ(context_->GetBundleName().c_str(), bundleName.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetBundleManager_0100 + * @tc.name: GetBundleManager + * @tc.desc: Verify that the GetBundleManager return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetBundleManager_0100, Function | MediumTest | Level3) +{ + sptr ptr = context_->GetBundleManager(); + EXPECT_NE(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetBundleCodePath_0100 + * @tc.name: GetBundleCodePath + * @tc.desc: Verify that the GetBundleCodePath return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetBundleCodePath_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string codePath = "CodePath"; + info->codePath = codePath; + context_->SetApplicationInfo(info); + + EXPECT_STREQ(context_->GetBundleCodePath().c_str(), codePath.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetApplicationInfo_0100 + * @tc.name: GetApplicationInfo + * @tc.desc: Verify that the GetApplicationInfo return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetApplicationInfo_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string bundleName = "BundleName"; + info->bundleName = bundleName; + context_->SetApplicationInfo(info); + + EXPECT_STREQ(context_->GetApplicationInfo()->bundleName.c_str(), bundleName.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetBundleResourcePath_0100 + * @tc.name: GetBundleResourcePath + * @tc.desc: Verify that the GetBundleResourcePath return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetBundleResourcePath_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string resourcePath = "ResourcePath"; + info->resourcePath = resourcePath; + context_->SetAbilityInfo(info); + + EXPECT_STREQ(context_->GetBundleResourcePath().c_str(), resourcePath.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetAbilityManager_0100 + * @tc.name: GetAbilityManager + * @tc.desc: Verify that the GetAbilityManager return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetAbilityManager_0100, Function | MediumTest | Level3) +{ + sptr ptr = context_->GetAbilityManager(); + EXPECT_NE(ptr, nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetCodeCacheDir_0100 + * @tc.name: GetCodeCacheDir + * @tc.desc: Verify that the GetCodeCacheDir return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetCodeCacheDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "CodeCacheDir"; + info->dataDir = dir; + context_->SetApplicationInfo(info); + dir = dir + "/" + "code_cache"; + + EXPECT_STREQ(context_->GetCodeCacheDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetCacheDir_0100 + * @tc.name: GetCacheDir + * @tc.desc: Verify that the GetCacheDir return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetCacheDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "CacheDir"; + info->cacheDir = dir; + context_->SetApplicationInfo(info); + + EXPECT_STREQ(context_->GetCacheDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetDatabaseDir_0100 + * @tc.name: GetDatabaseDir + * @tc.desc: Verify that the GetDatabaseDir return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetDatabaseDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "dataBaseDir"; + info->dataBaseDir = dir; + context_->SetApplicationInfo(info); + + EXPECT_STREQ(context_->GetDatabaseDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetFilesDir_0100 + * @tc.name: GetFilesDir + * @tc.desc: Verify that the GetFilesDir return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetFilesDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "codePath"; + info->dataDir = dir; + context_->SetApplicationInfo(info); + dir = dir + "/" + "files"; + + EXPECT_STREQ(context_->GetFilesDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetDataDir_0100 + * @tc.name: GetDataDir + * @tc.desc: Verify that the GetDataDir return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetDataDir_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string dir = "dataDir"; + info->dataDir = dir; + context_->SetApplicationInfo(info); + + EXPECT_STREQ(context_->GetDataDir().c_str(), dir.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetAppType_0100 + * @tc.name: GetAppType + * @tc.desc: Verify that the GetAppType return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetAppType_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + info->bundleName = "hello"; + context_->SetApplicationInfo(info); + + std::string path = context_->GetAppType(); + std::string AppType = "system"; + + EXPECT_NE(path.c_str(), AppType.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetAbilityInfo_0100 + * @tc.name: GetAbilityInfo + * @tc.desc: Verify that the GetAbilityInfo return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetAbilityInfo_0100, Function | MediumTest | Level1) +{ + std::shared_ptr info = std::make_shared(); + std::string codePath = "CodePath"; + info->codePath = codePath; + context_->SetAbilityInfo(info); + + EXPECT_STREQ(context_->GetAbilityInfo()->codePath.c_str(), codePath.c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetContext_0100 + * @tc.name: GetContext + * @tc.desc: Verify that the GetContext return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetContext_0100, Function | MediumTest | Level3) +{ + std::shared_ptr ability = std::make_shared(); + std::shared_ptr context(ability); + context_->SetContext(context); + + EXPECT_NE(context_->GetContext(), nullptr); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetApplicationContext_0100 + * @tc.name: GetApplicationContext + * @tc.desc: Verify that the GetApplicationContext return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetApplicationContext_0100, Function | MediumTest | Level3) +{ + std::shared_ptr application = std::make_shared(); + context_->SetApplicationContext(application); + EXPECT_NE(nullptr, context_->GetApplicationContext()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetProcessInfo_0100 + * @tc.name: GetProcessInfo + * @tc.desc: Verify that the GetProcessInfo return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetProcessInfo_0100, Function | MediumTest | Level1) +{ + std::string name = "OHOS"; + pid_t id = 0; + ProcessInfo info(name, id); + std::shared_ptr processinfo = std::make_shared(info); + context_->SetProcessInfo(processinfo); + EXPECT_STREQ(name.c_str(), context_->GetProcessInfo()->GetProcessName().c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_GetProcessName_0100 + * @tc.name: GetProcessName + * @tc.desc: Verify that the GetProcessName return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_GetProcessName_0100, Function | MediumTest | Level1) +{ + std::string name = "OHOS"; + pid_t id = 0; + ProcessInfo info(name, id); + std::shared_ptr processinfo = std::make_shared(info); + context_->SetProcessInfo(processinfo); + EXPECT_STREQ(name.c_str(), context_->GetProcessName().c_str()); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_SetShowOnLockScreen_0100 + * @tc.name: SetShowOnLockScreen + * @tc.desc: Verify that the SetShowOnLockScreen return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_SetShowOnLockScreen_0100, Function | MediumTest | Level1) +{ + auto abilityMgrClient = MockAbilityManagerClient::GetInstance(); + auto returnGetFileTypes = [](bool isAwakenScreen) { + EXPECT_TRUE(isAwakenScreen); + }; + EXPECT_CALL(*abilityMgrClient, SetShowOnLockScreen(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnGetFileTypes)); + + context_->SetShowOnLockScreen(true); +} + +/** + * @tc.number: AppExecFwk_ContextDeal_SetShowOnLockScreen_0200 + * @tc.name: SetShowOnLockScreen + * @tc.desc: Verify that the SetShowOnLockScreen return value is correct. + */ +HWTEST_F(ContextDealTest, AppExecFwk_ContextDeal_SetShowOnLockScreen_0200, Function | MediumTest | Level1) +{ + auto abilityMgrClient = MockAbilityManagerClient::GetInstance(); + auto returnGetFileTypes = [](bool isAwakenScreen) { + EXPECT_FALSE(isAwakenScreen); + }; + EXPECT_CALL(*abilityMgrClient, SetShowOnLockScreen(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnGetFileTypes)); + + context_->SetShowOnLockScreen(false); + testing::Mock::AllowLeak(abilityMgrClient.get()); +} +} // namespace AppExecFwk +} \ No newline at end of file diff --git a/frameworks/kits/appkit/native/test/unittest/context_impl_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..014a504d80afc264117f2db3bccca232d70417c0 --- /dev/null +++ b/frameworks/kits/appkit/native/test/unittest/context_impl_test.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_local_record.h" +#include "context_impl.h" +#include "context.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class ContextImplTest : public testing::Test { +public: + ContextImplTest() : contextImpl_(nullptr) + {} + ~ContextImplTest() + {} + std::shared_ptr contextImpl_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ContextImplTest::SetUpTestCase(void) +{} + +void ContextImplTest::TearDownTestCase(void) +{} + +void ContextImplTest::SetUp(void) +{ + contextImpl_ = std::make_shared(); +} + +void ContextImplTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetBundleName_001 + * @tc.name: GetBundleName + * @tc.desc: Test whether GetBundleName is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_001 start"; + std::string bundleName = contextImpl_->GetBundleName(); + EXPECT_STREQ(bundleName.c_str(), ""); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetBundleName_002 + * @tc.name: GetBundleName + * @tc.desc: Test whether GetBundleName is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_002 start"; + std::shared_ptr applicationInfo = std::make_shared(); + applicationInfo->bundleName = "com.test"; + contextImpl_->SetApplicationInfo(applicationInfo); + std::string bundleName = contextImpl_->GetBundleName(); + EXPECT_STREQ(bundleName.c_str(), "com.test"); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_002 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_SetApplicationInfo_001 + * @tc.name: SetApplicationInfo + * @tc.desc: Test whether SetApplicationInfo is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetApplicationInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetApplicationInfo_001 start"; + std::shared_ptr applicationInfo = std::make_shared(); + contextImpl_->SetApplicationInfo(applicationInfo); + EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetApplicationInfo_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetApplicationInfo_001 + * @tc.name: GetApplicationInfo + * @tc.desc: Test whether GetApplicationInfo is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 start"; + EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetApplicationContext_001 + * @tc.name: GetApplicationContext + * @tc.desc: Test whether GetApplicationContext is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 start"; + EXPECT_EQ(contextImpl_->GetApplicationContext(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_SetParentContext_001 + * @tc.name: SetParentContext + * @tc.desc: Test whether SetParentContext is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetParentContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 start"; + std::shared_ptr contextImpl_ = std::make_shared(); + contextImpl_->SetParentContext(contextImpl_); + EXPECT_NE(contextImpl_->GetApplicationContext(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetHapModuleInfo_001 + * @tc.name: GetHapModuleInfo + * @tc.desc: Test whether GetHapModuleInfo is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetHapModuleInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetHapModuleInfo_001 start"; + EXPECT_EQ(contextImpl_->GetHapModuleInfo(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetHapModuleInfo_001 end"; +} +} // namespace AppExecFwk +} \ No newline at end of file diff --git a/tools/zip/test/unittest/zip_test.cpp b/frameworks/kits/appkit/native/test/unittest/watchdog_test.cpp similarity index 31% rename from tools/zip/test/unittest/zip_test.cpp rename to frameworks/kits/appkit/native/test/unittest/watchdog_test.cpp index 1c5bde1ea26e384a038930c3349b003edada9ae3..aa89cd87831026336055f36f0e0fa1f19fb9709d 100644 --- a/tools/zip/test/unittest/zip_test.cpp +++ b/frameworks/kits/appkit/native/test/unittest/watchdog_test.cpp @@ -12,106 +12,69 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include -#include #include -#include "zip.h" +#include "main_thread.h" +#include "watchdog.h" -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; -class ZipTest : public testing::Test { +namespace OHOS { +namespace AppExecFwk { +const int USleepTime = 16000; +class WatchDogTest : public testing::Test { public: - ZipTest() + WatchDogTest() {} - ~ZipTest() + ~WatchDogTest() {} - static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); }; -void ZipTest::SetUpTestCase(void) +void WatchDogTest::SetUpTestCase(void) {} -void ZipTest::TearDownTestCase(void) +void WatchDogTest::TearDownTestCase(void) {} -void ZipTest::SetUp() +void WatchDogTest::SetUp(void) {} -void ZipTest::TearDown() +void WatchDogTest::TearDown(void) {} -void ZipCallBack(int result) -{ - printf("--Zip--callback--result=%d--\n", result); -} -void UnzipCallBack(int result) -{ - printf("--UnZip--callback--result=%d--\n", result); -} - -/** - * @tc.number: - * @tc.name: - * @tc.desc: - */ -HWTEST_F(ZipTest, AAFwk_LIBZIP_zip_0100_fourfile, Function | MediumTest | Level1) -{ - std::string src = "/ziptest/zipdata/"; - std::string dest = "/ziptest/result/fourfile.zip"; - - OPTIONS options; - Zip(FilePath(src), FilePath(dest), options, ZipCallBack, false); - std::this_thread::sleep_for(std::chrono::milliseconds(5000)); -} - /** - * @tc.number: - * @tc.name: - * @tc.desc: + * @tc.number: AppExecFwk_WatchDog_GetAppMainThreadState_0100 + * @tc.name: GetAppMainThreadState + * @tc.desc: Test the abnormal state of GetAppMainThreadState. */ -HWTEST_F(ZipTest, AAFwk_LIBZIP_zip_0200_singlefile, Function | MediumTest | Level1) +HWTEST_F(WatchDogTest, AppExecFwk_WatchDog_GetAppMainThreadState_0100, Function | MediumTest | Level3) { - std::string src = "/ziptest/zipdata/zip1/zip1-1/zip1-1.cpp"; - std::string dest = "/ziptest/result/singlefile.zip"; - - OPTIONS options; - Zip(FilePath(src), FilePath(dest), options, ZipCallBack, false); - std::this_thread::sleep_for(std::chrono::milliseconds(5000)); + bool ret = WatchDog::GetAppMainThreadState(); + EXPECT_FALSE(ret); } /** - * @tc.number: - * @tc.name: - * @tc.desc: + * @tc.number: AppExecFwk_WatchDog_GetAppMainThreadState_0200 + * @tc.name: GetAppMainThreadState + * @tc.desc: Test whether GetAppMainThreadState are called normally. */ -HWTEST_F(ZipTest, AAFwk_LIBZIP_unzip_0100, Function | MediumTest | Level1) +HWTEST_F(WatchDogTest, AppExecFwk_WatchDog_GetAppMainThreadState_0200, Function | MediumTest | Level3) { - std::string dest = "/ziptest/unzipdir/fourfile/"; - std::string src = "/ziptest/result/fourfile.zip"; - - OPTIONS options; - Unzip(FilePath(src), FilePath(dest), options, UnzipCallBack); - std::this_thread::sleep_for(std::chrono::milliseconds(5000)); + std::thread mainthread([&]() { + MainThread::Start(); + }); + mainthread.detach(); + std::this_thread::sleep_for(std::chrono::milliseconds(USleepTime)); + bool ret = WatchDog::GetAppMainThreadState(); + EXPECT_TRUE(ret); } - -HWTEST_F(ZipTest, AAFwk_LIBZIP_unzip_single_0200, Function | MediumTest | Level1) -{ - std::string src = "/ziptest/result/singlefile.zip"; - std::string dest = "/ziptest/unzipdir/single/"; - - OPTIONS options; - Unzip(FilePath(src), FilePath(dest), options, UnzipCallBack); - std::this_thread::sleep_for(std::chrono::milliseconds(5000)); -} - -} // namespace LIBZIP -} // namespace AAFwk +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/test/BUILD.gn b/frameworks/kits/appkit/test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..5aa5d62faf9d0c552bc36aa31aeb54cf837c72f7 --- /dev/null +++ b/frameworks/kits/appkit/test/BUILD.gn @@ -0,0 +1,222 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +module_output_path = "ability_runtime/moduletest/application_test/" + +#APP_INNERKITS_PATH = "//foundation/appexecfwk/standard/interfaces/innerkits" +ABILITY_INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", + "//EOSP/communication/libsoftbus/../../../foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/test/mock/include", + + #"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/test/Mock/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + + #"//foundation/communication/utils/include", + #"//foundation/communication/ipc/ipc/native/src/core/include", + #"//foundation/communication/ipc/utils/include", + ] + + defines = [ + "APP_LOG_TAG = \"ApplicationModuleTest\"", + "LOG_DOMAIN = 0xD001152", + ] +} + +ohos_moduletest("appexecfwk_appkit_native_app_module_test_first") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp", + "Mock/include/mock_app_thread.cpp", + "Mock/include/mock_application.cpp", + + #"Mock/include/mock_ipc_object_stub.cpp", + "Mock/include/sys_mgr_client_mock.cpp", + "moduletest/appexecfwk_appkit_native_app_module_test_first.cpp", + ] + + configs = [ ":module_private_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_moduletest("appexecfwk_appkit_native_app_module_test_second") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp", + "Mock/include/mock_app_thread.cpp", + "Mock/include/mock_application.cpp", + + #"Mock/include/mock_ipc_object_stub.cpp", + "Mock/include/sys_mgr_client_mock.cpp", + "moduletest/appexecfwk_appkit_native_app_module_test_second.cpp", + ] + + configs = [ ":module_private_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_moduletest("appexecfwk_appkit_native_app_module_test_third") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp", + "Mock/include/mock_app_thread.cpp", + "Mock/include/mock_application.cpp", + + #"Mock/include/mock_ipc_object_stub.cpp", + "Mock/include/sys_mgr_client_mock.cpp", + "moduletest/appexecfwk_appkit_native_app_module_test_third.cpp", + ] + + configs = [ ":module_private_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_moduletest("appexecfwk_appkit_native_app_module_test_fourth") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp", + "Mock/include/mock_app_thread.cpp", + "Mock/include/mock_application.cpp", + + #"Mock/include/mock_ipc_object_stub.cpp", + "Mock/include/sys_mgr_client_mock.cpp", + "moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp", + ] + + configs = [ ":module_private_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ABILITY_INNERKITS_PATH}/want:want", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### + +group("moduletest") { + testonly = true + deps = [] + + deps += [ + # ":appexecfwk_appkit_native_app_module_test_first", + # ":appexecfwk_appkit_native_app_module_test_fourth", + # ":appexecfwk_appkit_native_app_module_test_second", + # ":appexecfwk_appkit_native_app_module_test_third", + ] +} +############################################################################### diff --git a/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h new file mode 100644 index 0000000000000000000000000000000000000000..f53ce738e032cb1419c6ee36a623a62e308f3338 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_ABILITY_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_ABILITY_MGR_SERVICE_H + +#include "gmock/gmock.h" +#include "semaphore_ex.h" +#include "ability_manager_stub.h" + +namespace OHOS { +namespace AAFwk { +class MockAbilityMgrService : public AbilityManagerStub { +public: + MOCK_METHOD2(StartAbility, int(const Want &want, int requestCode)); + MOCK_METHOD3(StartAbility, int(const Want &want, const sptr &callerToken, int requestCode)); + MOCK_METHOD4(StartAbility, + int(const Want &want, const sptr &callerToken, int requestCode, int requestUid)); + MOCK_METHOD3(TerminateAbility, int(const sptr &token, int resultCode, const Want *resultWant)); + MOCK_METHOD3(ConnectAbility, + int(const Want &want, const sptr &connect, const sptr &callerToken)); + MOCK_METHOD1(DisconnectAbility, int(const sptr &connect)); + MOCK_METHOD3(AcquireDataAbility, sptr(const Uri &, bool, const sptr &)); + MOCK_METHOD2(ReleaseDataAbility, int(sptr, const sptr &)); + MOCK_METHOD2(AddWindowInfo, void(const sptr &token, int32_t windowToken)); + MOCK_METHOD2(AttachAbilityThread, int(const sptr &scheduler, const sptr &token)); + MOCK_METHOD3(AbilityTransitionDone, int(const sptr &token, int state, const PacMap &saveData)); + MOCK_METHOD2( + ScheduleConnectAbilityDone, int(const sptr &token, const sptr &remoteObject)); + MOCK_METHOD1(ScheduleDisconnectAbilityDone, int(const sptr &token)); + MOCK_METHOD1(ScheduleCommandAbilityDone, int(const sptr &token)); + void DumpState(const std::string &args, std::vector &state) + { + GTEST_LOG_(INFO) << "MockAbilityMgrService::DumpState called"; + DumpStateCalled_ = true; + EXPECT_TRUE(DumpStateCalled_); + return; + } + MOCK_METHOD2(TerminateAbilityResult, int(const sptr &, int startId)); + MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); + MOCK_METHOD2(StopServiceAbility, int(const Want &, const sptr &callerToken)); + MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); + MOCK_METHOD3(GetRecentMissions, int(const int32_t, const int32_t, std::vector &)); + MOCK_METHOD2(GetMissionSnapshot, int(const int32_t, MissionPixelMap &)); + MOCK_METHOD1(RemoveMission, int(int)); + MOCK_METHOD1(RemoveStack, int(int)); + MOCK_METHOD4(OnRemoteRequest, int(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)); + + MOCK_METHOD1(MoveMissionToTop, int(int32_t)); + MOCK_METHOD1(KillProcess, int(const std::string &bundleName)); + MOCK_METHOD2(UninstallApp, int(const std::string &bundleName, const int userId)); + MOCK_METHOD1(TerminateAbilityByRecordId, int(const int64_t recordId)); + + MOCK_METHOD1(LockMissionForCleanup, int(int32_t missionId)); + MOCK_METHOD1(UnlockMissionForCleanup, int(int32_t missionId)); + MOCK_METHOD1(RegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD1(UnRegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD3( + GetMissionInfos, int(const std::string& deviceId, int32_t numMax, std::vector &missionInfos)); + MOCK_METHOD3(GetMissionInfo, int(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo)); + MOCK_METHOD1(CleanMission, int(int32_t missionId)); + MOCK_METHOD0(CleanAllMissions, int()); + MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + + void Wait() + { + sem_.Wait(); + } + + int Post() + { + sem_.Post(); + return 0; + } + + void PostVoid() + { + sem_.Post(); + } + +private: + bool DumpStateCalled_ = false; + Semaphore sem_; +}; + +} // namespace AAFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_ABILITY_MGR_SERVICE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_ability_token.h b/frameworks/kits/appkit/test/Mock/include/mock_ability_token.h new file mode 100644 index 0000000000000000000000000000000000000000..e2957c579485f13fb3005fa6c7f61cc91d1fdce7 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_ability_token.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_ABILITY_TOKEN_H +#define FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_ABILITY_TOKEN_H + +#include "nocopyable.h" +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +class IAbilityToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AbilityToken"); +}; + +class MockAbilityToken : public IRemoteStub { +public: + MockAbilityToken() = default; + virtual ~MockAbilityToken() = default; + + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + return 0; + } + +private: + DISALLOW_COPY_AND_MOVE(MockAbilityToken); +}; + +class AbilityTokenProxy : public IRemoteProxy { +public: + explicit AbilityTokenProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~AbilityTokenProxy() = default; + +private: + DISALLOW_COPY_AND_MOVE(AbilityTokenProxy); +}; + +DECLARE_INTERFACE_DESCRIPTOR(u"IAbilityToken"); +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_ABILITY_TOKEN_H diff --git a/frameworks/kits/appkit/test/Mock/include/mock_app_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_app_mgr_service.h new file mode 100755 index 0000000000000000000000000000000000000000..23d946e750aad5d801d18d74db31a2c15e762873 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_app_mgr_service.h @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_APP_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_APP_MGR_SERVICE_H + +#include +#include "gmock/gmock.h" +#include "semaphore_ex.h" +#include "app_scheduler_interface.h" +#include "app_mgr_stub.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppMgrService : public AppMgrStub { +public: + MOCK_METHOD4(LoadAbility, + void(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + MOCK_METHOD1(TerminateAbility, void(const sptr &token)); + MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); + MOCK_METHOD1(SetAppFreezingTime, void(int time)); + MOCK_METHOD1(GetAppFreezingTime, void(int &time)); + MOCK_METHOD2(GetSystemMemoryAttr, void(SystemMemoryAttr &memoryInfo, std::string &strConfig)); + MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId)); + MOCK_METHOD0(StartupResidentProcess, void()); + + virtual void AttachApplication(const sptr &app) override + { + GTEST_LOG_(INFO) << "MockAppMgrService::AttachApplication called"; + Attached_ = true; + EXPECT_TRUE(Attached_); + Appthread_ = iface_cast(app); + } + + virtual void ApplicationForegrounded(const int32_t recordId) + { + GTEST_LOG_(INFO) << "MockAppMgrService::ApplicationForegrounded called"; + Foregrounded_ = true; + EXPECT_TRUE(Foregrounded_); + } + + virtual void ApplicationBackgrounded(const int32_t recordId) + { + GTEST_LOG_(INFO) << "MockAppMgrService::ApplicationBackgrounded called"; + Backgrounded_ = true; + EXPECT_TRUE(Backgrounded_); + } + + virtual void ApplicationTerminated(const int32_t recordId) + { + GTEST_LOG_(INFO) << "MockAppMgrService::ApplicationTerminated called"; + Terminated_ = true; + EXPECT_TRUE(Terminated_); + } + MOCK_METHOD2(CheckPermission, int32_t(const int32_t recordId, const std::string &permission)); + + virtual void AbilityCleaned(const sptr &token) + { + GTEST_LOG_(INFO) << "MockAppMgrService::AbilityCleaned called"; + Cleaned_ = true; + EXPECT_TRUE(Cleaned_); + } + + MOCK_METHOD1(KillApplication, int(const std::string &appName)); + MOCK_METHOD2(KillApplicationByUid, int(const std::string &, const int uid)); + + virtual sptr GetAmsMgr() override + { + return nullptr; + }; + virtual int32_t ClearUpApplicationData(const std::string &appName) override + { + return 0; + } + + virtual int IsBackgroundRunningRestricted(const std::string &appName) override + { + return 0; + }; + virtual int GetAllRunningProcesses(std::vector &info) override + { + return 0; + }; + + virtual void RegisterAppStateCallback(const sptr &callback) + { + callback_ = callback; + } + + int32_t CheckPermissionImpl([[maybe_unused]] const int32_t recordId, const std::string &data) + { + data_ = data; + return 0; + } + + void KillApplicationImpl(const std::string &data) + { + data_ = data; + } + + const std::string &GetData() const + { + return data_; + } + + void Wait() + { + sem_.Wait(); + } + + void Post() + { + sem_.Post(); + } + + void UpdateState() const + { + if (!callback_) { + return; + } + AppProcessData processData; + processData.appName = ""; + processData.pid = 1; + processData.appState = ApplicationState::APP_STATE_BEGIN; + callback_->OnAppStateChanged(processData); + } + + void Terminate(const sptr &token) const + { + if (!callback_) { + return; + } + AbilityState st = AbilityState::ABILITY_STATE_BEGIN; + callback_->OnAbilityRequestDone(token, st); + } + + void ScheduleTerminateApplication() + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleTerminateApplication(); + } + } + + void ScheduleLaunchApplication(const AppLaunchData &lanchdata) + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleLaunchApplication(lanchdata); + } + } + + void ScheduleForegroundApplication() + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleForegroundApplication(); + } + } + + void ScheduleBackgroundApplication() + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleBackgroundApplication(); + } + } + + void ScheduleShrinkMemory(const int32_t level) + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleShrinkMemory(level); + } + } + + void ScheduleLowMemory() + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleLowMemory(); + } + } + + void ScheduleLaunchAbility(const AbilityInfo &abilityinf, const sptr &token) + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleLaunchAbility(abilityinf, token); + } + } + + void ScheduleCleanAbility(const sptr &token) + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleCleanAbility(token); + } + } + + void ScheduleProfileChanged(const Profile &profile) + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleProfileChanged(profile); + } + } + + void ScheduleConfigurationUpdated(const Configuration &config) + { + if (Appthread_ != nullptr) { + Appthread_->ScheduleConfigurationUpdated(config); + } + } + + sptr GetAppthread() + { + return Appthread_; + } + + bool IsAttached() + { + APP_LOGI("MockAppMgrService::IsAttached Attached_ = %{public}d", Attached_); + return Attached_; + } + + bool IsForegrounded() + { + APP_LOGI("MockAppMgrService::IsForegrounded Foregrounded_ = %{public}d", Foregrounded_); + return Foregrounded_; + } + + bool IsBackgrounded() + { + APP_LOGI("MockAppMgrService::IsBackgrounded Backgrounded_ = %{public}d", Backgrounded_); + return Backgrounded_; + } + + bool IsTerminated() + { + APP_LOGI("MockAppMgrService::IsTerminated Terminated_ = %{public}d", Terminated_); + return Terminated_; + } + + void init() + { + APP_LOGI("MockAppMgrService::init called"); + Attached_ = false; + } + + bool AddDeathRecipient(const sptr &recipient) + { + return true; + } + +private: + bool Attached_ = false; + bool Foregrounded_ = false; + bool Backgrounded_ = false; + bool Terminated_ = false; + bool Cleaned_ = false; + sptr Appthread_ = nullptr; + Semaphore sem_; + std::string data_; + sptr callback_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_APP_MGR_SERVICE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_app_thread.cpp b/frameworks/kits/appkit/test/Mock/include/mock_app_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2e0df081c37d544abbf48d6e13cccf714188683 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_app_thread.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "mock_app_thread.h" + +namespace OHOS { +namespace AppExecFwk { +MockHandler::MockHandler(const std::shared_ptr &runner) : EventHandler(runner) +{} + +void MockHandler::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer &event) +{} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_app_thread.h b/frameworks/kits/appkit/test/Mock/include/mock_app_thread.h new file mode 100644 index 0000000000000000000000000000000000000000..48413e74c2d724bccd03aaf9112f498080c88d31 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_app_thread.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_APP_THREAD_H +#define FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_APP_THREAD_H + +#include +#include "event_handler.h" +#include "refbase.h" +#include "ohos_application.h" +#include "ability_local_record.h" + +namespace OHOS { +namespace AppExecFwk { +class MockHandler : public EventHandler { +public: + explicit MockHandler(const std::shared_ptr &runner); + ~MockHandler() + {} + void ProcessEvent(const InnerEvent::Pointer &event) override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_APP_THREAD_H \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_application.cpp b/frameworks/kits/appkit/test/Mock/include/mock_application.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09972a836d3b573c4bb6094389a50461afd3b212 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_application.cpp @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "mock_application.h" +#include "ability.h" +#include "app_loader.h" + +const int INMOCKAPPLICATION_ONE = 9996; +const int INMOCKAPPLICATION_TWO = 9997; +const int INMOCKAPPLICATION_THREE = 9998; +#define NUMBER (10) + +namespace OHOS { +namespace AppExecFwk { +REGISTER_APPLICATION("MockTestApplication", MockApplication) + +MockApplication::MockApplication() +{ + elementCallBack_ = std::make_shared(); + lifecycleCallBack_ = std::make_shared(); +} + +void MockApplication::OnConfigurationUpdated(const Configuration &config) +{ + GTEST_LOG_(INFO) << "MockApplication::OnConfigurationUpdated called"; + bool iscalled = true; + EXPECT_TRUE(iscalled); + if (INMOCKAPPLICATION_TWO == GetProcessInfo()->GetPid()) { + RegisterElementsCallbacks(elementCallBack_); + OHOSApplication::OnConfigurationUpdated(config); + UnregisterElementsCallbacks(elementCallBack_); + OHOSApplication::OnConfigurationUpdated(config); + } +} + +void MockApplication::OnMemoryLevel(int level) +{ + GTEST_LOG_(INFO) << "MockApplication::OnMemoryLevel called"; + bool iscalled = true; + EXPECT_TRUE(iscalled); + level_ = level; + EXPECT_EQ(level, level_); + if (INMOCKAPPLICATION_TWO == GetProcessInfo()->GetPid()) { + RegisterElementsCallbacks(elementCallBack_); + OHOSApplication::OnMemoryLevel(level); + UnregisterElementsCallbacks(elementCallBack_); + OHOSApplication::OnMemoryLevel(level); + } +} + +void MockApplication::OnForeground() +{ + GTEST_LOG_(INFO) << "MockApplication::OnForeground called"; + bool iscalled = true; + EXPECT_TRUE(iscalled); +} + +void MockApplication::OnBackground() +{ + GTEST_LOG_(INFO) << "MockApplication::OnBackground called"; + bool iscalled = true; + EXPECT_TRUE(iscalled); +} + +void MockApplication::OnStart() +{ + GTEST_LOG_(INFO) << "MockApplication::OnStart called"; + bool iscalled = true; + EXPECT_TRUE(iscalled); + int a = 1; + EXPECT_EQ(1, a); + + if (INMOCKAPPLICATION_THREE == GetProcessInfo()->GetPid()) { + EXPECT_STREQ("TestProcess", GetProcessInfo()->GetProcessName().c_str()); + EXPECT_STREQ("/hos/lib/cacheDir", GetCacheDir().c_str()); + EXPECT_STREQ("/hos/lib/cacheDir", GetCodeCacheDir().c_str()); + EXPECT_STREQ("/hos/lib/dataBaseDir", GetDatabaseDir().c_str()); + EXPECT_STREQ("/hos/lib/dataDir", GetDataDir().c_str()); + EXPECT_STREQ("/hos/lib/dataDir", GetDir("test", 1).c_str()); + EXPECT_STREQ("MockBundleName", GetBundleName().c_str()); + EXPECT_STREQ("MockTestApplication", GetApplicationInfo()->name.c_str()); + + EXPECT_STREQ("", GetBundleCodePath().c_str()); + EXPECT_STREQ("", GetBundleResourcePath().c_str()); + EXPECT_EQ(nullptr, GetContext()); + EXPECT_EQ(nullptr, GetAbilityInfo()); + EXPECT_STREQ("/hos/lib/dataDir", GetApplicationContext()->GetDir("test", 1).c_str()); + std::vector state; + EXPECT_NE(nullptr, GetAbilityManager()); + if (nullptr != GetAbilityManager()) { + GetAbilityManager()->DumpState("test", state); + } + + EXPECT_NE(nullptr, GetBundleManager()); + if (nullptr != GetBundleManager()) { + EXPECT_STREQ("ModuleTestType", GetBundleManager()->GetAppType("test").c_str()); + } + } else if (INMOCKAPPLICATION_ONE == GetProcessInfo()->GetPid()) { + RegisterAbilityLifecycleCallbacks(lifecycleCallBack_); + + std::shared_ptr ability = std::make_shared(); + PacMap pacmap; + + OHOSApplication::OnAbilityStart(ability); + OHOSApplication::OnAbilityInactive(ability); + OHOSApplication::OnAbilityBackground(ability); + OHOSApplication::OnAbilityForeground(ability); + OHOSApplication::OnAbilityActive(ability); + OHOSApplication::OnAbilityStop(ability); + OHOSApplication::OnAbilitySaveState(pacmap); + + UnregisterAbilityLifecycleCallbacks(lifecycleCallBack_); + + OHOSApplication::OnAbilityStart(ability); + OHOSApplication::OnAbilityInactive(ability); + OHOSApplication::OnAbilityBackground(ability); + OHOSApplication::OnAbilityForeground(ability); + OHOSApplication::OnAbilityActive(ability); + OHOSApplication::OnAbilityStop(ability); + OHOSApplication::OnAbilitySaveState(pacmap); + } +} + +void MockApplication::OnTerminate() +{ + GTEST_LOG_(INFO) << "MockApplication::OnTerminate called"; + bool iscalled = true; + EXPECT_TRUE(iscalled); +} + +void MockModuleElementsCallback::OnConfigurationUpdated( + const std::shared_ptr &ability, const Configuration &config) +{ + GTEST_LOG_(INFO) << "MockModuleElementsCallback::OnConfigurationUpdated called"; + EXPECT_STREQ(config.GetName().c_str(), "testConfig"); +} + +void MockModuleElementsCallback::OnMemoryLevel(int level) +{ + GTEST_LOG_(INFO) << "MockModuleElementsCallback::OnMemoryLevel called"; + EXPECT_EQ(level, NUMBER); +} + +void MockModuleLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + GTEST_LOG_(INFO) << "MockModuleLifecycleCallbacks::OnAbilityStart called"; +} + +void MockModuleLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + GTEST_LOG_(INFO) << "MockModuleLifecycleCallbacks::OnAbilityInactive called"; +} + +void MockModuleLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + GTEST_LOG_(INFO) << "MockModuleLifecycleCallbacks::OnAbilityBackground called"; +} + +void MockModuleLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + GTEST_LOG_(INFO) << "MockModuleLifecycleCallbacks::OnAbilityForeground called"; +} + +void MockModuleLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + GTEST_LOG_(INFO) << "MockModuleLifecycleCallbacks::OnAbilityActive called"; +} + +void MockModuleLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + GTEST_LOG_(INFO) << "MockModuleLifecycleCallbacks::OnAbilityStop called"; +} + +void MockModuleLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + GTEST_LOG_(INFO) << "MockModuleLifecycleCallbacks::OnAbilitySaveState called"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_application.h b/frameworks/kits/appkit/test/Mock/include/mock_application.h new file mode 100644 index 0000000000000000000000000000000000000000..7af4a03eb11915b0ae0578313ca38047fe7c42aa --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_application.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_APPLICATION_H +#define FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_APPLICATION_H + +#include +#include "ohos_application.h" + +namespace OHOS { +namespace AppExecFwk { +class MockModuleLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + MockModuleLifecycleCallbacks() = default; + virtual ~MockModuleLifecycleCallbacks() = default; + + void OnAbilityStart(const std::shared_ptr &ability); + void OnAbilityInactive(const std::shared_ptr &ability); + void OnAbilityBackground(const std::shared_ptr &ability); + void OnAbilityForeground(const std::shared_ptr &ability); + void OnAbilityActive(const std::shared_ptr &ability); + void OnAbilityStop(const std::shared_ptr &ability); + void OnAbilitySaveState(const PacMap &outState); +}; + +class MockModuleElementsCallback : public ElementsCallback { +public: + MockModuleElementsCallback() = default; + virtual ~MockModuleElementsCallback() = default; + + virtual void OnConfigurationUpdated(const std::shared_ptr &ability, const Configuration &config); + + virtual void OnMemoryLevel(int level); +}; + +class MockApplication : public OHOSApplication { +public: + MockApplication(); + virtual ~MockApplication() = default; + + virtual void OnConfigurationUpdated(const Configuration &config); + virtual void OnMemoryLevel(int level); + virtual void OnForeground(); + virtual void OnBackground(); + virtual void OnStart(); + virtual void OnTerminate(); + +private: + std::shared_ptr elementCallBack_ = nullptr; + std::shared_ptr lifecycleCallBack_ = nullptr; + int level_ = 0; + std::shared_ptr config_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_APPLICATION_H \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h new file mode 100644 index 0000000000000000000000000000000000000000..f7a06c00d72fee5393a977776aab46203c7f1376 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_BUNDLE_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_BUNDLE_MGR_SERVICE_H + +#include "gmock/gmock.h" +#include "semaphore_ex.h" +#include "bundle_mgr_host.h" + +namespace OHOS { +namespace AppExecFwk { +class MockBundleMgrService : public BundleMgrHost { +public: + MOCK_METHOD4(GetApplicationInfo, + bool(const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo)); + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return false; + } + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override + { + return false; + } + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override + { + return false; + } + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override + { + return 0; + } + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override + { + return ""; + } + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + return false; + } + MOCK_METHOD2(GetBundleGids, bool(const std::string &bundleName, std::vector &gids)); + std::string GetAppType(const std::string &bundleName) + { + GTEST_LOG_(INFO) << "MockBundleMgrService::GetAppType called"; + return "ModuleTestType"; + } + virtual bool CheckIsSystemAppByUid(const int uid) override + { + return false; + } + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } + MOCK_METHOD2(GetBundleInfosByMetaData, bool(const std::string &metaData, std::vector &bundleInfos)); + MOCK_METHOD2(QueryAbilityInfo, bool(const Want &want, AbilityInfo &abilityInfo)); + MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector &abilityInfos)); + MOCK_METHOD2(QueryAbilityInfoByUri, bool(const std::string &abilityUri, AbilityInfo &abilityInfo)); + MOCK_METHOD1(QueryKeepAliveBundleInfos, bool(std::vector &bundleInfos)); + MOCK_METHOD2(GetAbilityLabel, std::string(const std::string &bundleName, const std::string &className)); + MOCK_METHOD3( + GetBundleArchiveInfo, bool(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo)); + MOCK_METHOD2(GetHapModuleInfo, bool(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo)); + MOCK_METHOD2(GetHapModuleInfo, bool(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo)); + MOCK_METHOD2(GetLaunchWantForBundle, bool(const std::string &bundleName, Want &want)); + MOCK_METHOD2(CheckPublicKeys, int(const std::string &firstBundleName, const std::string &secondBundleName)); + MOCK_METHOD2(CheckPermission, int(const std::string &bundleName, const std::string &permission)); + MOCK_METHOD2(GetPermissionDef, bool(const std::string &permissionName, PermissionDef &permissionDef)); + MOCK_METHOD1(GetAllPermissionGroupDefs, bool(std::vector &permissionDefs)); + MOCK_METHOD2(GetAppsGrantedPermissions, + bool(const std::vector &permissions, std::vector &appNames)); + MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); + MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); + MOCK_METHOD0(IsSafeMode, bool()); + MOCK_METHOD2(CleanBundleCacheFiles, + bool(const std::string &bundleName, const sptr &cleanCacheCallback)); + MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); + MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); + MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); + MOCK_METHOD0(UnregisterBundleStatusCallback, bool()); + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override + { + return false; + } + MOCK_METHOD0(GetBundleInstaller, sptr()); + MOCK_METHOD1(GetBundleInstaller, bool(const std::string &)); + MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &, bool)); + MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &)); + + virtual bool CanRequestPermission( + const std::string &bundleName, const std::string &permissionName, const int userId) override + { + return true; + } + virtual bool RequestPermissionFromUser( + const std::string &bundleName, const std::string &permission, const int userId) override + { + return true; + } + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); + MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + void Wait() + { + sem_.Wait(); + } + + int Post() + { + sem_.Post(); + return 0; + } + + void PostVoid() + { + sem_.Post(); + } + +private: + Semaphore sem_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_BUNDLE_MGR_SERVICE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_ipc_object_stub.cpp b/frameworks/kits/appkit/test/Mock/include/mock_ipc_object_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..417838e5caffd916120050d30f0f591b7b5c8af0 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/mock_ipc_object_stub.cpp @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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_object_stub.h" +#include +#include "ipc_types.h" +#include "ipc_debug.h" +#include "ipc_process_skeleton.h" +#include "ipc_thread_skeleton.h" +#include "log_tags.h" +#include "ipc_skeleton.h" +#include "app_log_wrapper.h" + +#ifdef CONFIG_IPC_RPC +#include "dbinder_databus_invoker.h" +#include "dbinder_error_code.h" +#include "ISessionService.h" +#endif + +namespace OHOS { +using namespace OHOS::AppExecFwk; +using namespace OHOS::HiviewDFX; +#ifdef CONFIG_IPC_RPC +static constexpr HiLogLabel LABEL = {LOG_CORE, LOG_ID_IPC, "IPCObjectStub"}; +// Authentication information can be added only for processes with system permission. +static constexpr pid_t ALLOWED_UID = 10000; +// Only the samgr can obtain the UID and PID. +static constexpr pid_t SYSTEM_SERVER_UID = 1000; +#endif +IPCObjectStub::IPCObjectStub(std::u16string descriptor) : IRemoteObject(descriptor) +{} + +IPCObjectStub::~IPCObjectStub() +{ + APP_LOGI("IPCObjectStub destroyed"); +} + +bool IPCObjectStub::IsDeviceIdIllegal(const std::string &deviceID) +{ + if (deviceID.empty() || deviceID.length() > DEVICEID_LENGTH) { + return true; + } + return false; +} + +int32_t IPCObjectStub::GetObjectRefCount() +{ + int kRefCount = 0; + int refCount = GetSptrRefCount(); + IRemoteInvoker *invoker = IPCThreadSkeleton::GetRemoteInvoker(IRemoteObject::IF_PROT_DEFAULT); + + if (invoker != nullptr) { + kRefCount = invoker->GetObjectRefCount(this); + } + + /* the kernel has already acquire the reference + * on this object, so we need to decrement by 1. + */ + if (kRefCount > 0) { + refCount += kRefCount - 1; + } + + return refCount; +} + +int IPCObjectStub::Dump(int fd, const std::vector &args) +{ + const size_t numArgs = args.size(); + APP_LOGI("Invalid call on Stub:fd:%{public}d, args:%{public}zu", fd, numArgs); + return ERR_NONE; +} + +int IPCObjectStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int result = ERR_NONE; + switch (code) { +#ifdef CONFIG_IPC_RPC + case DBINDER_OBITUARY_TRANSACTION: { + if (IPCSkeleton::GetCallingUid() != SYSTEM_SERVER_UID) { + APP_LOGI(LABEL, "%s: DBINDER_OBITUARY_TRANSACTION unauthenticated user ", __func__); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + if (data.ReadInt32() == IRemoteObject::DeathRecipient::NOTICE_DEATH_RECIPIENT) { + result = NoticeServiceDie(data, reply, option); + } else { + result = IPC_STUB_INVALID_DATA_ERR; + } + break; + } +#endif + default: + result = IPC_STUB_UNKNOW_TRANS_ERR; + APP_LOGI("unknown OnRemoteRequest code = %{public}u", code); + break; + } + + return result; +} + +int IPCObjectStub::OnRemoteDump(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int result = ERR_NONE; + int fd = data.ReadFileDescriptor(); + std::vector args; + if (fd != INVALID_FD) { + if (data.ReadString16Vector(&args)) { + result = Dump(fd, args); + } + ::close(fd); + } else { + result = IPC_STUB_INVALID_DATA_ERR; + } + return result; +} + +int IPCObjectStub::SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int result = ERR_NONE; + switch (code) { + case PING_TRANSACTION: { + if (!reply.WriteInt32(ERR_NONE)) { + result = IPC_STUB_WRITE_PARCEL_ERR; + } + break; + } + case INTERFACE_TRANSACTION: { + std::u16string descriptor = GetObjectDescriptor(); + if (!reply.WriteString16(descriptor)) { + APP_LOGI("write to parcel fail"); + result = IPC_STUB_WRITE_PARCEL_ERR; + } + break; + } + case SYNCHRONIZE_REFERENCE: { + int refCount = GetObjectRefCount(); + // when handle transaction the invoker would try to acquire + // the object's reference to defense the object being released + // so the actual we should decrement the temporary reference. + --refCount; + reply.WriteInt32(refCount); + break; + } + case DUMP_TRANSACTION: { + if (!IPCSkeleton::IsLocalCalling()) { + APP_LOGI("do not allow dump"); + break; + } + result = OnRemoteDump(code, data, reply, option); + break; + } +#ifdef CONFIG_IPC_RPC + case INVOKE_LISTEN_THREAD: { + if (!IPCSkeleton::IsLocalCalling() || IPCSkeleton::GetCallingUid() >= ALLOWED_UID) { + APP_LOGI("%s: INVOKE_LISTEN_THREAD unauthenticated user ", __func__); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + result = InvokerThread(code, data, reply, option); + break; + } + case GET_PROTO_INFO: { + result = ProcessProto(code, data, reply, option); + break; + } + case DBINDER_INCREFS_TRANSACTION: { + if (IPCSkeleton::IsLocalCalling()) { + APP_LOGI("%s: cannot be called in same device", __func__); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + result = IncStubRefs(data, reply); + break; + } + case DBINDER_DECREFS_TRANSACTION: { + if (IPCSkeleton::IsLocalCalling()) { + APP_LOGI("%s: cannot be called in same device", __func__); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + result = DecStubRefs(data, reply); + break; + } + case DBINDER_ADD_COMMAUTH: { + if (IPCSkeleton::IsLocalCalling() || IPCSkeleton::GetCallingUid() >= ALLOWED_UID) { + APP_LOGI("%s: DBINDER_ADD_COMMAUTH unauthenticated user ", __func__); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + result = AddAuthInfo(data, reply); + break; + } + case GET_UIDPID_INFO: { + if (!IPCSkeleton::IsLocalCalling()) { + APP_LOGI("GET_UIDPID_INFO message is not from sa manager"); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + std::string sessionName = GetDataBusName(); + if (sessionName.empty()) { + APP_LOGI("sessionName is empty"); + result = IPC_STUB_CREATE_BUS_SERVER_ERR; + break; + } + if (!reply.WriteString(sessionName)) { + APP_LOGI("write to parcel fail"); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + break; + } + case GRANT_DATABUS_NAME: { + if (!IPCSkeleton::IsLocalCalling() || getuid() != SYSTEM_SERVER_UID) { + APP_LOGI("GRANT_DATABUS_NAME message is excluded in sa manager"); + result = IPC_STUB_INVALID_DATA_ERR; + break; + } + result = GrantDataBusName(code, data, reply, option); + break; + } +#endif + default: + result = OnRemoteRequest(code, data, reply, option); + break; + } + + return result; +} + +void IPCObjectStub::OnFirstStrongRef(const void *objectId) +{ + IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent(); + + if (current != nullptr) { + current->AttachObject(this); + } +} + +void IPCObjectStub::OnLastStrongRef(const void *objectId) +{ + IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent(); + + if (current != nullptr) { + current->DetachObject(this); +#ifdef CONFIG_IPC_RPC + current->DetachStubRecvRefInfo(this); + current->DetachStubSendRefInfo(this); + (void)current->DetachStubRefTimes(this); + current->DetachCommAuthInfoByStub(this); + uint64_t stubIndex = current->EraseStubIndex(reinterpret_cast(this)); + current->DetachAppInfoToStubIndex(stubIndex); +#endif + } +} + +bool IPCObjectStub::AddDeathRecipient(const sptr &recipient) +{ + return true; +} + +bool IPCObjectStub::RemoveDeathRecipient(const sptr &recipient) +{ + return false; +} + +pid_t IPCObjectStub::GetCallingPid() +{ + return IPCSkeleton::GetCallingPid(); +} + +pid_t IPCObjectStub::GetCallingUid() +{ + return IPCSkeleton::GetCallingUid(); +} + +int32_t IPCObjectStub::ProcessProto(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int result = ERR_NONE; + APP_LOGI("IPCObjectStub::ProcessProto called, type = 0, normal stub object"); + if (!reply.WriteUint32(IRemoteObject::IF_PROT_BINDER)) { + APP_LOGI("write to parcel fail"); + result = IPC_STUB_WRITE_PARCEL_ERR; + } + return result; +} + +#ifdef CONFIG_IPC_RPC +int32_t IPCObjectStub::InvokerThread(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + switch (data.ReadUint32()) { + case IRemoteObject::DATABUS_TYPE: { + if (InvokerDataBusThread(data, reply) != ERR_NONE) { + APP_LOGI("Invoker databus thread fail"); + return IPC_STUB_INVOKE_THREAD_ERR; + } + break; + } + default: { + APP_LOGI("InvokerThread Invalid Type"); + return IPC_STUB_INVALID_DATA_ERR; + } + } + + return ERR_NONE; +} + +int32_t IPCObjectStub::InvokerDataBusThread(MessageParcel &data, MessageParcel &reply) +{ + std::string deviceId = data.ReadString(); + uint32_t remotePid = data.ReadUint32(); + uint32_t remoteUid = data.ReadUint32(); + std::string remoteDeviceId = data.ReadString(); + std::string sessionName = data.ReadString(); + if (IsDeviceIdIllegal(deviceId) || IsDeviceIdIllegal(remoteDeviceId) || sessionName.empty()) { + APP_LOGI("%s: device ID is invalid or session name nil", __func__); + return IPC_STUB_INVALID_DATA_ERR; + } + + IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent(); + if (current == nullptr) { + APP_LOGI("IPCProcessSkeleton is nullptr"); + return IPC_STUB_CURRENT_NULL_ERR; + } + if (!current->CreateSoftbusServer(sessionName)) { + APP_LOGI("%s: fail to create databus server", __func__); + return IPC_STUB_CREATE_BUS_SERVER_ERR; + } + + uint64_t stubIndex = current->AddStubByIndex(this); + if (stubIndex == 0) { + APP_LOGI("%s: add stub fail", __func__); + return IPC_STUB_INVALID_DATA_ERR; + } + if (!reply.WriteUint64(stubIndex) || !reply.WriteString(sessionName) || !reply.WriteString(deviceId)) { + APP_LOGI("%s: write to parcel fail", __func__); + return IPC_STUB_INVALID_DATA_ERR; + } + if (!current->AttachAppInfoToStubIndex(remotePid, remoteUid, remoteDeviceId, stubIndex)) { + APP_LOGI("fail to attach appinfo to stubIndex, maybe attach already"); + } + if (!current->AttachCommAuthInfo(this, remotePid, remoteUid, remoteDeviceId)) { + APP_LOGI("fail to attach comm auth info"); + } + + return ERR_NONE; +} + +int32_t IPCObjectStub::NoticeServiceDie(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent(); + if (current == nullptr) { + APP_LOGI("%s: current is null", __func__); + return IPC_STUB_CURRENT_NULL_ERR; + } + + IPCObjectProxy *ipcProxy = current->QueryCallbackProxy(this); + if (ipcProxy == nullptr) { + APP_LOGI("%s: ipc proxy is null", __func__); + return IPC_STUB_INVALID_DATA_ERR; + } + + ipcProxy->SendObituary(); + + if (!current->DetachCallbackStub(this)) { + APP_LOGI("%s: fail to detach callback stub", __func__); + // do nothing, RemoveDeathRecipient can delete this too + } + + return ERR_NONE; +} + +int32_t IPCObjectStub::IncStubRefs(MessageParcel &data, MessageParcel &reply) +{ + IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent(); + if (current == nullptr) { + APP_LOGI("%s: current is null", __func__); + return IPC_STUB_CURRENT_NULL_ERR; + } + + std::string deviceId = IPCSkeleton::GetCallingDeviceID(); + if (deviceId.empty()) { + APP_LOGI("%s: calling error", __func__); + return IPC_STUB_INVALID_DATA_ERR; + } + if (!current->AttachStubRecvRefInfo(this, IPCSkeleton::GetCallingPid(), deviceId)) { + APP_LOGI("%s: attach stub ref info err, already in", __func__); + return ERR_NONE; + } + + if (!current->DecStubRefTimes(this)) { + this->IncStrongRef(this); + } + + return ERR_NONE; +} + +int32_t IPCObjectStub::DecStubRefs(MessageParcel &data, MessageParcel &reply) +{ + IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent(); + if (current == nullptr) { + APP_LOGI("%s: current is null", __func__); + return IPC_STUB_CURRENT_NULL_ERR; + } + + std::string deviceId = IPCSkeleton::GetCallingDeviceID(); + current->DetachStubRefInfo(this, IPCSkeleton::GetCallingPid(), deviceId); + return ERR_NONE; +} + +int32_t IPCObjectStub::AddAuthInfo(MessageParcel &data, MessageParcel &reply) +{ + uint32_t remotePid = data.ReadUint32(); + uint32_t remoteUid = data.ReadUint32(); + std::string remoteDeviceId = data.ReadString(); + if (IsDeviceIdIllegal(remoteDeviceId)) { + APP_LOGI("%s: remote deviceId is null", __func__); + return IPC_STUB_INVALID_DATA_ERR; + } + + IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent(); + if (current == nullptr) { + APP_LOGI("%s: current is null", __func__); + return IPC_STUB_CURRENT_NULL_ERR; + } + + if (!current->AttachCommAuthInfo(this, remotePid, remoteUid, remoteDeviceId)) { + APP_LOGI("fail to attach comm auth info fail"); + return IPC_STUB_INVALID_DATA_ERR; + } + return ERR_NONE; +} + +std::string IPCObjectStub::GetDataBusName() +{ + sptr object = IPCProcessSkeleton::GetCurrent()->GetSAMgrObject(); + if (object == nullptr) { + APP_LOGI("get object is null"); + return std::string(""); + } + + IPCObjectProxy *samgr = reinterpret_cast(object.GetRefPtr()); + return samgr->GetDataBusName(); +} + +int32_t IPCObjectStub::GrantDataBusName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int pid = IPCSkeleton::GetCallingPid(); + int uid = IPCSkeleton::GetCallingUid(); + std::string sessionName = CreateDatabusName(uid, pid); + if (sessionName.empty()) { + APP_LOGI("pid/uid is invalid, pid = {public}%d, uid = {public}%d", pid, uid); + return IPC_STUB_INVALID_DATA_ERR; + } + if (!reply.WriteUint32(IRemoteObject::IF_PROT_DATABUS) || !reply.WriteString(sessionName)) { + APP_LOGI("write to parcel fail"); + return IPC_STUB_INVALID_DATA_ERR; + } + + return ERR_NONE; +} + +std::string IPCObjectStub::CreateDatabusName(int uid, int pid) +{ + std::shared_ptr softbusManager = ISessionService::GetInstance(); + if (softbusManager == nullptr) { + APP_LOGI("fail to get softbus service"); + return ""; + } + + std::string sessionName = "DBinder" + std::to_string(uid) + std::string("_") + std::to_string(pid); + if (softbusManager->GrantPermission(uid, pid, sessionName) != ERR_NONE) { + APP_LOGI("fail to Grant Permission softbus name"); + return ""; + } + + return sessionName; +} +#endif +} // namespace OHOS diff --git a/frameworks/kits/appkit/test/Mock/include/sys_mgr_client_mock.cpp b/frameworks/kits/appkit/test/Mock/include/sys_mgr_client_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e87e056082f61fb541049eedaeef1663939fd26 --- /dev/null +++ b/frameworks/kits/appkit/test/Mock/include/sys_mgr_client_mock.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "sys_mgr_client.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "ipc_skeleton.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +sptr SysMrgClient::GetSystemAbility(const int32_t systemAbilityId) +{ + if (servicesMap_[systemAbilityId] == nullptr) { + OHOS::sptr abilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (abilityManager == nullptr) { + HILOG_ERROR("%s:fail to get Registry", __func__); + return nullptr; + } + OHOS::sptr object = abilityManager->GetSystemAbility(systemAbilityId); + servicesMap_[systemAbilityId] = object; + } + + return servicesMap_[systemAbilityId]; +} + +void SysMrgClient::RegisterSystemAbility(const int32_t systemAbilityId, sptr broker) +{ + servicesMap_[systemAbilityId] = broker; +} + +void SysMrgClient::UnregisterSystemAbility(const int32_t systemAbilityId) +{ + servicesMap_[systemAbilityId] = nullptr; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3284e86ac4b49e735ac06e77aaf2d6052736e9d8 --- /dev/null +++ b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_thread.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" +#include "mock_app_mgr_service.h" +#include "mock_app_thread.h" +#include "mock_ability_token.h" +#include "mock_ability_mgr_service.h" +#include "mock_bundle_mgr_service.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; +using namespace OHOS::AAFwk; +const int TestProcessInfo = 9999; +const int USleepTime = 200; + +class AppkitNativeModuleTestFirst : public testing::Test { +public: + AppkitNativeModuleTestFirst() : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) + {} + ~AppkitNativeModuleTestFirst() + {} + OHOS::sptr AppMgrObject_ = nullptr; + MockAppMgrService *mockAppMgr = nullptr; + std::shared_ptr mockHandler_ = nullptr; + std::shared_ptr runner_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AppkitNativeModuleTestFirst::SetUpTestCase(void) +{} + +void AppkitNativeModuleTestFirst::TearDownTestCase(void) +{} + +void AppkitNativeModuleTestFirst::SetUp(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestFirst SetUp"; + AppMgrObject_ = new (std::nothrow) MockAppMgrService(); + mockAppMgr = iface_cast(AppMgrObject_); + + runner_ = EventRunner::Create("AppkitNativeModuleTestMockHandlerFirst"); + mockHandler_ = std::make_shared(runner_); + + auto task = [abilityThread = this]() { MainThread::Start(); }; + mockHandler_->PostTask(task); +} + +void AppkitNativeModuleTestFirst::TearDown(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestFirst TearDown"; + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); +} + +/** + * @tc.number: App_Start_0100 + * @tc.name: Start Appfwk + * @tc.desc: Mock appmgr and register it into the systemmanager. + * Start the Appfwk and the Appfwk attach the AppMgr. + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_Start_0100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_Start_0100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + mockAppMgr->ScheduleTerminateApplication(); + usleep(USleepTime); + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + usleep(USleepTime); + GTEST_LOG_(INFO) << "App_Start_0100 end"; +} + +/** + * @tc.number: App_Start_0200 + * @tc.name: Start Appfwk + * @tc.desc: Didn't register Mock appmgr into the systemmanager. + * Start the Appfwk and the Appfwk attach the AppMgr failed. + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_Start_0200, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_Start_0200 start"; + runner_->Run(); + usleep(USleepTime); + EXPECT_EQ(false, mockAppMgr->IsAttached()); + runner_->Stop(); + GTEST_LOG_(INFO) << "App_Start_0200 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0100 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * Verifying when the correct App lifecycle flows, whether the corresponding + * callback function will be called. + * (StartAppfwk->LaunchApp->Foreground->Background->Terminate) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleBackgroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0100 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0200 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->Foreground) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0200, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0200 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0200 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0300 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->Background) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0300, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0300 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + mockAppMgr->ScheduleBackgroundApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0300 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0400 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->Terminate) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0400, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0400 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0400 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0500 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Foreground) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0500, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0500 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleBackgroundApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0500 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0600 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Terminate) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0600, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0600 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0600 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0700 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->LaunchApp) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0700, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0700 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0700 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0800 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Foreground->Terminate) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0800, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0800 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0800 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_0900 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Foreground->LaunchApp) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0900, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0900 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0900 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_1000 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Foreground->LaunchApp) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1000, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1000 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1000 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_1100 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Foreground->Background->LaunchApp) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleBackgroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1100 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_1200 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Foreground->Background->Foreground) + */ +HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1200, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1200 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleBackgroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1200 end"; + + mockAppMgr->ScheduleBackgroundApplication(); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b53fbae6c2f73db7a7fb35771e790a1beccce186 --- /dev/null +++ b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_thread.h" +#include "mock_ability_mgr_service.h" +#include "mock_ability_token.h" +#include "mock_app_mgr_service.h" +#include "mock_app_thread.h" +#include "mock_bundle_mgr_service.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; +using namespace OHOS::AAFwk; +const int TestProcessInfo = 9999; +const int USleepTime = 50; +class AppkitNativeModuleTestThird : public testing::Test { +public: + AppkitNativeModuleTestThird() : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) + {} + ~AppkitNativeModuleTestThird() + {} + OHOS::sptr AppMgrObject_ = nullptr; + MockAppMgrService *mockAppMgr = nullptr; + std::shared_ptr mockHandler_ = nullptr; + std::shared_ptr runner_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AppkitNativeModuleTestThird::SetUpTestCase(void) +{} + +void AppkitNativeModuleTestThird::TearDownTestCase(void) +{} + +void AppkitNativeModuleTestThird::SetUp(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird SetUp"; + AppMgrObject_ = new (std::nothrow) MockAppMgrService(); + mockAppMgr = iface_cast(AppMgrObject_); + + runner_ = EventRunner::Create("AppkitNativeModuleTestMockHandlerSecond"); + mockHandler_ = std::make_shared(runner_); + + auto task = [abilityThread = this]() { MainThread::Start(); }; + mockHandler_->PostTask(task); +} + +void AppkitNativeModuleTestThird::TearDown(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird TearDown"; + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); +} + +/** + * @tc.number: App_CleanAbility_0100 + * @tc.name: App CleanAbility + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * The ability has been launched successfully. + * Clean the ability which has been launched before. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_CleanAbility_0100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + AbilityInfo abilityinf; + sptr token = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + + usleep(USleepTime); + + mockAppMgr->ScheduleCleanAbility(token); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_CleanAbility_0100 end"; +} + +/** + * @tc.number: App_CleanAbility_0200 + * @tc.name: App CleanAbility + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * The application has not been launched successfully. + * Clean the ability before launch the application. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0200, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_CleanAbility_0200 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + sptr token = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleCleanAbility(token); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_CleanAbility_0200 end"; +} + +/** + * @tc.number: App_CleanAbility_0300 + * @tc.name: App CleanAbility + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * The ability has not been launched successfully. + * Clean the ability before launch the ability. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0300, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_CleanAbility_0300 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + sptr token = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleCleanAbility(token); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_CleanAbility_0300 end"; +} + +/** + * @tc.number: App_CleanAbility_0400 + * @tc.name: App CleanAbility + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * The ability has been launched successfully. + * Clean the ability with a null token. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0400, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_CleanAbility_0400 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + AbilityInfo abilityinf; + sptr token = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + + usleep(USleepTime); + + mockAppMgr->ScheduleCleanAbility(nullptr); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_CleanAbility_0400 end"; +} + +/** + * @tc.number: App_CleanAbility_0500 + * @tc.name: App CleanAbility + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * The ability has been launched successfully. + * Clean the ability with a wrong token. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0500, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_CleanAbility_0500 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + AbilityInfo abilityinf; + sptr token = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + + usleep(USleepTime); + sptr tokenOhter = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleCleanAbility(tokenOhter); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_CleanAbility_0500 end"; +} + +/** + * @tc.number: App_ElementsCallbacks_0100 + * @tc.name: Application ElementsCallbacks + * @tc.desc: Mock application Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The Appfwk has started successfully. + * Verifying whether ElementsCallbacks registration, unregister, and its observer mechanism are valid. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_ElementsCallbacks_0100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ElementsCallbacks_0100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", 9997); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleShrinkMemory(10); + + usleep(USleepTime); + OHOS::AppExecFwk::Configuration config; + config.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "ZH-HANS"); + + mockAppMgr->ScheduleConfigurationUpdated(config); + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ElementsCallbacks_0100 end"; +} + +/** + * @tc.number: App_AbilityLifecycleCallbacks_0100 + * @tc.name: Application AbilityLifecycleCallbacks + * @tc.desc: Mock ability + * Mock application + * Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * The ability has been launched successfully. + * Verifying whether AbilityLifecycleCallbacks registration, unregister, and its observer mechanism are + valid. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_AbilityLifecycleCallbacks_0100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_AbilityLifecycleCallbacks_0100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", 9996); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_AbilityLifecycleCallbacks_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65edcd5018d528e2ee579b99356696d4e25f496d --- /dev/null +++ b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_thread.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" +#include "mock_app_mgr_service.h" +#include "mock_app_thread.h" +#include "mock_ability_token.h" +#include "mock_ability_mgr_service.h" +#include "mock_bundle_mgr_service.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; +using namespace OHOS::AAFwk; +const int TestProcessInfo = 9999; +const int USleepTime = 50; +class AppkitNativeModuleTestSecond : public testing::Test { +public: + AppkitNativeModuleTestSecond() + : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) + {} + ~AppkitNativeModuleTestSecond() + {} + OHOS::sptr AppMgrObject_ = nullptr; + MockAppMgrService *mockAppMgr = nullptr; + std::shared_ptr mockHandler_ = nullptr; + std::shared_ptr runner_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AppkitNativeModuleTestSecond::SetUpTestCase(void) +{} + +void AppkitNativeModuleTestSecond::TearDownTestCase(void) +{} + +void AppkitNativeModuleTestSecond::SetUp(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestSecond SetUp"; + AppMgrObject_ = new (std::nothrow) MockAppMgrService(); + mockAppMgr = iface_cast(AppMgrObject_); + + runner_ = EventRunner::Create("AppkitNativeModuleTestMockHandlerSecond"); + mockHandler_ = std::make_shared(runner_); + + auto task = [abilityThread = this]() { MainThread::Start(); }; + mockHandler_->PostTask(task); +} + +void AppkitNativeModuleTestSecond::TearDown(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestSecond TearDown"; + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); +} + +/** + * @tc.number: App_ApplicationLifeCycle_1300 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when the wrong App lifecycle flows, whether the corresponding callback function will not + * be called. (StartAppfwk->LaunchApp->Foreground->Background->Background) + */ +HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1300, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1300 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleForegroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleBackgroundApplication(); + + usleep(USleepTime); + + mockAppMgr->ScheduleBackgroundApplication(); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1300 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_1400 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when launch the application with a null appInfo.name, whether the corresponding callback + * function will not be called. + */ +HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1400, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1400 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1400 end"; +} + +/** + * @tc.number: App_ApplicationLifeCycle_1500 + * @tc.name: Application lifecycle switch + * @tc.desc: Mock appmgr and register it into the systemmanager. The Appfwk has started successfully. + * Verifying when launch the application with a null processInfo.ProcessName, whether the corresponding + * callback function will not be called. + */ +HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1500, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1500 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1500 end"; +} + +/** + * @tc.number: App_LaunchAblity_0100 + * @tc.name: App LaunchAblity + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * Launch the ability for the application. + */ +HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_LaunchAblity_0100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + AbilityInfo abilityinf; + sptr token = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_LaunchAblity_0100 end"; +} + +/** + * @tc.number: App_LaunchAblity_0200 + * @tc.name: App LaunchAblity + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has not been launched successfully. + * Launch the ability for the application, before the application has not been launched. + */ +HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0200, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_LaunchAblity_0200 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AbilityInfo abilityinf; + sptr token = new (std::nothrow) MockAbilityToken(); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_LaunchAblity_0200 end"; +} + +/** + * @tc.number: App_LaunchAblity_0300 + * @tc.name: App LaunchAblity + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * The tocken should be null. + * Launch the ability for the application with a null token. + */ +HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0300, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_LaunchAblity_0300 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + AbilityInfo abilityinf; + mockAppMgr->ScheduleLaunchAbility(abilityinf, nullptr); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + GTEST_LOG_(INFO) << "App_LaunchAblity_0300 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e45f2b80baafe1cb69f120fedae717dd49d7247 --- /dev/null +++ b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_thread.h" +#include "mock_ability_mgr_service.h" +#include "mock_ability_token.h" +#include "mock_app_mgr_service.h" +#include "mock_app_thread.h" +#include "mock_bundle_mgr_service.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS; +using namespace OHOS::AAFwk; +const int TestProcessInfo = 9999; +const int USleepTime = 50; +class AppkitNativeModuleTestThird : public testing::Test { +public: + AppkitNativeModuleTestThird() : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) + {} + ~AppkitNativeModuleTestThird() + {} + OHOS::sptr AppMgrObject_ = nullptr; + MockAppMgrService *mockAppMgr = nullptr; + std::shared_ptr mockHandler_ = nullptr; + std::shared_ptr runner_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AppkitNativeModuleTestThird::SetUpTestCase(void) +{} + +void AppkitNativeModuleTestThird::TearDownTestCase(void) +{} + +void AppkitNativeModuleTestThird::SetUp(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird SetUp"; + AppMgrObject_ = new (std::nothrow) MockAppMgrService(); + mockAppMgr = iface_cast(AppMgrObject_); + + runner_ = EventRunner::Create("AppkitNativeModuleTestMockHandlerSecond"); + mockHandler_ = std::make_shared(runner_); + + auto task = [abilityThread = this]() { MainThread::Start(); }; + mockHandler_->PostTask(task); +} + +void AppkitNativeModuleTestThird::TearDown(void) +{ + GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird TearDown"; + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", TestProcessInfo); + appinf.name = "MockTestApplication"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + mockAppMgr->ScheduleTerminateApplication(); +} + +/** + * @tc.number: App_Context_ApplicationContext_0100 + * @tc.name: Application Context + * @tc.desc: Mock appmgr and register it into the systemmanager. + * The Appfwk has started successfully. + * The application has been launched successfully. + * Verifying the interface about getting context infos when the OnStart function of application is called. + */ +HWTEST_F(AppkitNativeModuleTestThird, App_Context_ApplicationContext_0100, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "App_Context_ApplicationContext_0100 start"; + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); + runner_->Run(); + usleep(USleepTime); + + AppLaunchData lanchdate; + ApplicationInfo appinf; + ProcessInfo processinf("TestProcess", 9998); + appinf.name = "MockTestApplication"; + appinf.cacheDir = "/hos/lib/cacheDir"; + appinf.dataBaseDir = "/hos/lib/dataBaseDir"; + appinf.dataDir = "/hos/lib/dataDir"; + appinf.bundleName = "MockBundleName"; + appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); + lanchdate.SetApplicationInfo(appinf); + lanchdate.SetProcessInfo(processinf); + mockAppMgr->ScheduleLaunchApplication(lanchdate); + + usleep(USleepTime); + + runner_->Stop(); + OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); + + usleep(USleepTime); + GTEST_LOG_(INFO) << "App_Context_ApplicationContext_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp index 97488a565c448e3437f81504bcaf1211bf732620..f8aa58e926c6ad518c8cb3927be7952e5c476540 100644 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp +++ b/frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp @@ -35,7 +35,7 @@ bool UserObject::Equals(IObject &other) UserObject *otherObj = static_cast(IUserObject::Query(&other)); if (otherObj == nullptr) { - return false; + return false; } if (value_->GetClassName() == otherObj->value_->GetClassName()) { return otherObj->value_->Equals(value_); diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp index ffe84090a3ac8739e5fa5f45d0171bdd6fa8a488..8b0488a35eb05bc863ccddee248a2820df0de8bd 100644 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp @@ -66,6 +66,11 @@ const std::string Want::OCT_SEMICOLON("073"); // ';' const std::string Want::MIME_TYPE("mime-type"); const std::string Want::WANT_HEADER("#Intent;"); +const std::string Want::PARAM_RESV_WINDOW_MODE("ohos.aafwk.param.windowMode"); +const std::string Want::PARAM_RESV_CALLER_TOKEN("ohos.aafwk.param.callerToken"); +const std::string Want::PARAM_RESV_CALLER_UID("ohos.aafwk.param.callerUid"); +const std::string Want::PARAM_RESV_CALLER_PID("ohos.aafwk.param.callerPid"); + /** * @description:Default construcotr of Want class, which is used to initialzie flags and URI. * @param None diff --git a/frameworks/kits/content/cpp/test/BUILD.gn b/frameworks/kits/content/cpp/test/BUILD.gn index 1d4348288ff8d5af609b90e84df897cb8aeedfa9..0532001e85e3a30bdbddf812faacf934f4e0007a 100644 --- a/frameworks/kits/content/cpp/test/BUILD.gn +++ b/frameworks/kits/content/cpp/test/BUILD.gn @@ -13,7 +13,7 @@ import("//build/test.gni") -module_output_path = "aafwk_standard/intent_test" +module_output_path = "ability_runtime/intent_test" ############################################################################### config("module_private_config") { @@ -63,7 +63,7 @@ ohos_unittest("intent_parcelable_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "ipc:ipc_core", ] } @@ -84,7 +84,7 @@ ohos_unittest("intent_base_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "ipc:ipc_core", ] } @@ -105,7 +105,7 @@ ohos_unittest("intent_parse_to_uri_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "ipc:ipc_core", ] } @@ -130,7 +130,7 @@ ohos_unittest("intent_parameters_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "ipc:ipc_core", ] } @@ -151,7 +151,7 @@ ohos_unittest("intent_params_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "ipc:ipc_core", ] } @@ -176,7 +176,7 @@ ohos_unittest("intent_filter_test") { "//utils/native/base:utils", ] - external_deps = [ "appexecfwk_standard:appexecfwk_base" ] + external_deps = [ "bundle_framework:appexecfwk_base" ] } ohos_unittest("operation_test") { @@ -200,7 +200,7 @@ ohos_unittest("operation_test") { "//utils/native/base:utils", ] - external_deps = [ "appexecfwk_standard:appexecfwk_base" ] + external_deps = [ "bundle_framework:appexecfwk_base" ] } ohos_unittest("patterns_matcher_test") { @@ -223,7 +223,7 @@ ohos_unittest("patterns_matcher_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", ] } @@ -250,7 +250,7 @@ ohos_unittest("skills_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", ] } @@ -276,7 +276,7 @@ ohos_unittest("want_params_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", ] } @@ -301,7 +301,7 @@ ohos_unittest("want_params_wrapper_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", ] } @@ -325,7 +325,7 @@ ohos_unittest("want_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", ] } diff --git a/frameworks/kits/content/cpp/test/unittest/common/want_params_test.cpp b/frameworks/kits/content/cpp/test/unittest/common/want_params_test.cpp index 443f7d4345a7c3c622e420a150a990f76b1e4e6a..197f5ac07bc412ae44f6e879a89860f5bb1e0ada 100644 --- a/frameworks/kits/content/cpp/test/unittest/common/want_params_test.cpp +++ b/frameworks/kits/content/cpp/test/unittest/common/want_params_test.cpp @@ -30,7 +30,7 @@ namespace OHOS { namespace AAFwk { class WantParamsBaseTest : public testing::Test { public: - WantParamsBaseTest() + WantParamsBaseTest() {} ~WantParamsBaseTest() { @@ -76,7 +76,7 @@ HWTEST_F(WantParamsBaseTest, AaFwk_WantParams_Parcelable_0100, Function | Medium wantParamsIn_->Marshalling(in); std::shared_ptr wantParamsOut_(WantParams::Unmarshalling(in)); EXPECT_EQ(valueStr, String::Unbox(IString::Query(wantParamsOut_->GetParam(keyStr)))); - } + } } /** @@ -95,7 +95,7 @@ HWTEST_F(WantParamsBaseTest, AaFwk_WantParams_Parcelable_0200, Function | Medium wantParamsIn_->Marshalling(in); std::shared_ptr wantParamsOut_(WantParams::Unmarshalling(in)); EXPECT_EQ(valueBool, Boolean::Unbox(IBoolean::Query(wantParamsOut_->GetParam(keyStr)))); - } + } } /** @@ -117,7 +117,7 @@ HWTEST_F(WantParamsBaseTest, AaFwk_WantParams_Parcelable_0300, Function | Medium right = Integer::Unbox(IInteger::Query(wantParamsOut_->GetParam(keyStr))); EXPECT_EQ(valueInteger, right); - wantParamsOut_ = nullptr; + wantParamsOut_ = nullptr; } } diff --git a/frameworks/kits/fmskit/BUILD.gn b/frameworks/kits/fmskit/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..83e684d0da69a2f05d9856912bf8727d827f7600 --- /dev/null +++ b/frameworks/kits/fmskit/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +SUBSYSTEM_DIR = "//foundation/aafwk/standard" + +config("fmskit_config") { + defines = [ + "APP_LOG_TAG = \"FmskitNative\"", + "LOG_DOMAIN = 0xD001151", + ] +} +config("fmskit_public_config") { + include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "${appexecfwk_path}/common/log/include", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//utils/system/safwk/native/include", + ] +} + +# build so +ohos_shared_library("fmskit_native") { + configs = [ ":fmskit_config" ] + public_configs = [ ":fmskit_public_config" ] + sources = [ + "$SUBSYSTEM_DIR/frameworks/kits/fmskit/native/src/form_errors.cpp", + "$SUBSYSTEM_DIR/frameworks/kits/fmskit/native/src/form_host_client.cpp", + "$SUBSYSTEM_DIR/frameworks/kits/fmskit/native/src/form_mgr.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager:form_manager", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "aafwk" + part_name = "form_runtime" +} diff --git a/frameworks/kits/fmskit/native/include/form_callback_interface.h b/frameworks/kits/fmskit/native/include/form_callback_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..458a143986ab082b03785e533336eccba99dc673 --- /dev/null +++ b/frameworks/kits/fmskit/native/include/form_callback_interface.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_ABILITY_INTERFACE_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_ABILITY_INTERFACE_H + +#include "form_js_info.h" + +namespace OHOS { +namespace AppExecFwk { +class FormCallbackInterface { +public: + /** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + virtual void ProcessFormUpdate(const FormJsInfo &formJsInfo) = 0; + + /** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ + virtual void ProcessFormUninstall(const int64_t formId) = 0; + + /** + * @brief Form service death event. + * + */ + virtual void OnDeathReceived() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_ABILITY_INTERFACE_H diff --git a/frameworks/kits/fmskit/native/include/form_errors.h b/frameworks/kits/fmskit/native/include/form_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..1d3ddb7ecb74011e1be0ea81d1c9c1348ee0af1b --- /dev/null +++ b/frameworks/kits/fmskit/native/include/form_errors.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H + +#include +#include + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormErrors + * FormErrors is used to access form error message. + */ +class FormErrors final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormErrors) +public: + DISALLOW_COPY_AND_MOVE(FormErrors); + + /** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ + std::string GetErrorMessage(int errCode); + +private: + /** + * @brief Init error message map object. + * + */ + void InitErrorMessageMap(); + +private: + std::map errorMessageMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H \ No newline at end of file diff --git a/frameworks/kits/fmskit/native/include/form_host_client.h b/frameworks/kits/fmskit/native/include/form_host_client.h new file mode 100755 index 0000000000000000000000000000000000000000..203650ff85133b84b4ce82a54def1c35044483cb --- /dev/null +++ b/frameworks/kits/fmskit/native/include/form_host_client.h @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H + +#include +#include +#include +#include +#include "form_callback_interface.h" +#include "form_host_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostClient + * The service of the form host. + */ +class HostForms; +class FormHostClient : public FormHostStub { +public: + FormHostClient(); + virtual ~FormHostClient(); + + /** + * @brief Get FormHostClient instance. + * + * @return FormHostClient instance. + */ + static sptr GetInstance(); + + /** + * @brief Add form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ + void AddForm(std::shared_ptr formCallback, const int64_t formId); + + /** + * @brief Remove form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ + void RemoveForm(std::shared_ptr formCallback, const int64_t formId); + + /** + * @brief Check whether the form exist in the formhosts. + * + * @param formId The Id of the form. + * @return Returns true if contains form; returns false otherwise. + */ + bool ContainsForm(int64_t formId); + + /** + * @brief Request to give back a form. + * + * @param formJsInfo Form js info. + * @return none. + */ + virtual void OnAcquired(const FormJsInfo &formJsInfo); + + /** + * @brief Update form. + * + * @param formJsInfo Form js info. + * @return none. + */ + virtual void OnUpdate(const FormJsInfo &formJsInfo); + + /** + * @brief UnInstall the forms. + * + * @param formIds The Id of the forms. + * @return none. + */ + virtual void OnUninstall(const std::vector &formIds); + +private: + static sptr instance_; + static std::mutex instanceMutex_; + mutable std::mutex lockMutex_; + std::vector keyVector_; + std::map> recordCallback_; + std::map recordHostForms_; + int32_t key_ = 0; + +private: + /** + * @brief Find callback by formId. + * + * @param formId The Id of the form. + * @return target callback + */ + std::shared_ptr FindTargetCallback(int64_t formId); + + /** + * @brief Find Key By form callback. + * + * @param formCallback The form callback. + * @return callback's key + */ + int32_t FindKeyByCallback(std::shared_ptr formCallback); + + /** + * @brief Compare callback. + * + * @param formCallback1 The form callback1. + * @param formCallback2 The callback to be compared with form callback1. + * @return Returns true if the two callback are equal to each other, returns false otherwise. + */ + bool Compare(std::shared_ptr formCallback1, std::shared_ptr formCallback2); + + DISALLOW_COPY_AND_MOVE(FormHostClient); +}; + +class HostForms { +public: + /** + * @brief Add form by formId. + * + * @param formId The Id of the form. + */ + void AddForm(const int64_t formId) + { + std::map::iterator it = forms_.find(formId); + if (it != forms_.end()) { + return; + } + forms_.insert(std::pair(formId, true)); + } + + /** + * @brief Delete form by formId. + * + * @param formId The Id of the form. + */ + void DelForm(const int64_t formId) + { + forms_.erase(formId); + } + + /** + * @brief Check whether the form is empty. + */ + bool IsEmpty() + { + return forms_.empty(); + } + + /** + * @brief Check whether the form exist in the forms. + * + * @param formId The Id of the form. + * @return Returns true if contains form; returns false otherwise. + */ + bool Contains(const int64_t formId) + { + std::map::iterator it = forms_.find(formId); + return (it == forms_.end()) ? false : true; + } + +private: + std::map forms_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H diff --git a/frameworks/kits/fmskit/native/include/form_mgr.h b/frameworks/kits/fmskit/native/include/form_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..1c961be477f75e8dd50bdd3fc9e6d4c8c73a69c3 --- /dev/null +++ b/frameworks/kits/fmskit/native/include/form_mgr.h @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_MGR_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_MGR_H + +#include +#include + +#include "form_callback_interface.h" +#include "form_constants.h" +#include "form_death_callback.h" +#include "form_info.h" +#include "form_js_info.h" +#include "form_mgr_interface.h" +#include "form_provider_data.h" +#include "iremote_object.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; + +static volatile int recoverStatus_ = Constants::NOT_IN_RECOVERY; + +/** + * @class FormMgr + * FormMgr is used to access form manager services. + */ +class FormMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormMgr) +public: + DISALLOW_COPY_AND_MOVE(FormMgr); + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo); + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DeleteForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache); + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formBindingData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const std::string &bundleName, const FormProviderData &formBindingData); + + /** + * @brief Notify the form service that the form user's lifecycle is updated. + * + * This should be called when form user request form. + * + * @param formId Indicates the unique id of form. + * @param callerToken Indicates the callback remote object of specified form user. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ + int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want); + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType); + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return None. + */ + int CastTempForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpStorageFormInfos(std::string &formInfos); + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByBundleName(const std::string bundleName, std::string &formInfos); + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo); + /** + * @brief Dump form timer by form id. + * @param formId The id of the form. + * @param formInfo Form timer. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService); + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken); + + /** + * @brief Get fms recoverStatus. + * + * @return The current recover status. + */ + static int GetRecoverStatus(); + + /** + * @brief Register death callback. + * + * @param formDeathCallback The death callback. + */ + void RegisterDeathCallback(const std::shared_ptr &formDeathCallback); + + /** + * @brief UnRegister death callback. + * + * @param formDeathCallback The death callback. + */ + void UnRegisterDeathCallback(const std::shared_ptr &formDeathCallback); + + /** + * @brief Set the next refresh time + * + * @param formId The id of the form. + * @param nextTime Next refresh time + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshTime(const int64_t formId, const int64_t nextTime); + + /** + * @brief Lifecycle Update. + * @param formIds The id of the forms. + * @param callerToken Host client. + * @param updateType Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType); + + /** + * @brief Set fms recoverStatus. + * + * @param recoverStatus The recover status. + */ + static void SetRecoverStatus(int recoverStatus); + + /** + * @brief Set form mgr service for test. + */ + void SetFormMgrService(sptr formMgrService); + + /** + * @brief Get death recipient. + * @return deathRecipient_. + */ + sptr GetDeathRecipient() const; + + /** + * @brief Check whether the specified death callback is registered in form mgr. + * @param formDeathCallback The specified death callback for checking. + * @return Return true on success, false on failure. + */ + bool CheckIsDeathCallbackRegistered(const std::shared_ptr &formDeathCallback); + + /** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ + std::string GetErrorMessage(int errCode); + + /** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + int DistributedDataAddForm(const Want &want); + + /** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ + int DistributedDataDeleteForm(const std::string &formId); + + /** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ + int GetAllFormsInfo(std::vector &formInfos); + + /** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ + int GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos); + + /** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ + int GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector &formInfos); + +private: + /** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode Connect(); + + /** + * @brief Reconnect form manager service once per 1000 milliseconds, + * until the connection succeeds or reaching the max retry times. + * @return Returns true if execute success, false otherwise. + */ + bool Reconnect(); + /** + * @brief Reset proxy. + * @param remote remote object. + */ + void ResetProxy(const wptr &remote); + +public: + friend class FormMgrDeathRecipient; + +private: + /** + * @class FormMgrDeathRecipient + * FormMgrDeathRecipient notices IRemoteBroker died. + */ + class FormMgrDeathRecipient : public IRemoteObject::DeathRecipient { + public: + FormMgrDeathRecipient() = default; + ~FormMgrDeathRecipient() = default; + + /** + * @brief Notices IRemoteBroker died. + * @param remote remote object. + */ + void OnRemoteDied(const wptr &remote) override; + private: + DISALLOW_COPY_AND_MOVE(FormMgrDeathRecipient); + }; + + std::mutex connectMutex_; + sptr remoteProxy_; + + sptr deathRecipient_ {nullptr}; + + // True: need to get a new fms remote object, + // False: no need to get a new fms remote object. + volatile bool resetFlag_ = false; + + std::vector> formDeathCallbacks_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_MGR_H \ No newline at end of file diff --git a/frameworks/kits/fmskit/native/src/form_errors.cpp b/frameworks/kits/fmskit/native/src/form_errors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25203bad713c6c61c6d79e326544ac9265108a65 --- /dev/null +++ b/frameworks/kits/fmskit/native/src/form_errors.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "form_errors.h" + +namespace OHOS { +namespace AppExecFwk { +FormErrors::FormErrors() +{ + InitErrorMessageMap(); +} +FormErrors::~FormErrors() +{ +} + +/** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ +std::string FormErrors::GetErrorMessage(int errCode) +{ + if (errorMessageMap_.find(errCode) != errorMessageMap_.end()) { + return errorMessageMap_[errCode]; + } else { + return errorMessageMap_[ERR_APPEXECFWK_FORM_COMMON_CODE]; + } +} + +/** + * @brief Init error message map object. + * + */ +void FormErrors::InitErrorMessageMap() +{ + errorMessageMap_ = { // error + message + { + ERR_APPEXECFWK_FORM_COMMON_CODE, "some internal server error occurs.", + }, + { + ERR_APPEXECFWK_FORM_PERMISSION_DENY, + "check permission deny, need to request ohos.permission.REQUIRE_FORM.", + }, + { + ERR_APPEXECFWK_FORM_GET_INFO_FAILED, "can't get form info by the formName.", + }, + { + ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, "the requested bundle name does not exist.", + }, + { + ERR_APPEXECFWK_FORM_INVALID_PARAM, "invalid params received on operating form.", + }, + { + ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, "the form id and form config are not matched.", + }, + { + ERR_APPEXECFWK_FORM_NOT_EXIST_ID, "the requested form id is not existed on fms.", + }, + { + ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, "fms bind provider failed.", + }, + { + ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, "exceed max forms in system, current limit is 512.", + }, + { + ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, "exceed max instances per form, limit is 32.", + }, + { + ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, + "the form to be operated is not self-owned or has been deleted already.", + }, + { + ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, "fms notify provider to delete failed.", + }, + { + ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, "exceed max forms per client, limit is 256.", + }, + { + ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, "exceed max temp forms in system, limit is 256.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_MODULE, "the module not exist in the bundle.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, "the ability not exist in the module.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION, "the dimension not exist in the form.", + }, + { + ERR_APPEXECFWK_FORM_FA_NOT_INSTALLED, "the ability not installed,need install first.", + }, + { + ERR_APPEXECFWK_FORM_MAX_REQUEST, "too many request,try again later.", + }, + { + ERR_APPEXECFWK_FORM_MAX_REFRESH, "already refresh 50 times.", + }, + { + ERR_APPEXECFWK_FORM_GET_BMS_FAILED, "get bms rpc failed.", + }, + { + ERR_APPEXECFWK_FORM_GET_FMS_FAILED, "get fms rpc failed.", + }, + { + ERR_APPEXECFWK_FORM_SEND_FMS_MSG, "send request to fms failed.", + }, + { + ERR_APPEXECFWK_FORM_FORM_DUPLICATE_ADDED, "form do not support acquire same id twice.", + }, + { + ERR_APPEXECFWK_FORM_IN_RECOVER, "form is in recover status, can't do action on form.", + }, + { + ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED, "get system manager failed.", + }, + { + ERR_APPEXECFWK_PARCEL_ERROR, "read parcelable info failed.", + }, + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/fmskit/native/src/form_host_client.cpp b/frameworks/kits/fmskit/native/src/form_host_client.cpp new file mode 100755 index 0000000000000000000000000000000000000000..959601777ec673d8eff700f08da7605b85eddfcc --- /dev/null +++ b/frameworks/kits/fmskit/native/src/form_host_client.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "form_host_client.h" + +namespace OHOS { +namespace AppExecFwk { +sptr FormHostClient::instance_ = nullptr; +std::mutex FormHostClient::instanceMutex_; + +FormHostClient::FormHostClient() +{ +} + +FormHostClient::~FormHostClient() +{ +} + +/** + * @brief Get FormHostClient instance. + * + * @return FormHostClient instance. + */ +sptr FormHostClient::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(instanceMutex_); + if (instance_ == nullptr) { + instance_ = new FormHostClient(); + } + } + return instance_; +} + +/** + * @brief Add form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ +void FormHostClient::AddForm(std::shared_ptr formCallback, const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative or zero.", __func__); + return; + } + + { + std::lock_guard lock(lockMutex_); + int64_t key = FindKeyByCallback(formCallback); + if (key == -1) { + HostForms hostForms; + int64_t tempKey = key_; + if (!keyVector_.empty()) { + tempKey = keyVector_.back(); + keyVector_.pop_back(); + } + hostForms.AddForm(formId); + recordCallback_.insert(std::make_pair(tempKey, formCallback)); + recordHostForms_.insert(std::make_pair(tempKey, hostForms)); + + if (tempKey == key_) { + key_++; + } + } else { + recordHostForms_[key].AddForm(formId); + } + } +} + +/** + * @brief Remove form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ +void FormHostClient::RemoveForm(std::shared_ptr formCallback, const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0 || formCallback == nullptr) { + APP_LOGE("%{public}s, invalid param.", __func__); + return; + } + + { + std::lock_guard lock(lockMutex_); + int64_t key = FindKeyByCallback(formCallback); + if (key == -1) { + APP_LOGE("%{public}s, failed to find callback.", __func__); + return; + } + + if (recordHostForms_[key].IsEmpty()) { + recordCallback_.erase(key); + recordHostForms_.erase(key); + keyVector_.push_back(key); + APP_LOGI("%{public}s, clear data.", __func__); + return; + } + + recordHostForms_[key].DelForm(formId); + if (recordHostForms_[key].IsEmpty()) { + recordCallback_.erase(key); + recordHostForms_.erase(key); + keyVector_.push_back(key); + APP_LOGI("%{public}s, clear data.", __func__); + } + } + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Check whether the form exist in the formhosts. + * + * @param formId The Id of the form. + * @return Returns true if contains form; returns false otherwise. + */ +bool FormHostClient::ContainsForm(int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + std::lock_guard lock(lockMutex_); + for (auto recordHostForm : recordHostForms_) { + if (recordHostForm.second.Contains(formId)) { + return true; + } + } + return false; +} + +/** + * @brief Request to give back a form. + * + * @param formJsInfo Form js info. + * @return none. + */ +void FormHostClient::OnAcquired(const FormJsInfo &formJsInfo) +{ + APP_LOGI("%{public}s called.", __func__); + int64_t formId = formJsInfo.formId; + if (formId < 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); + return; + } + std::shared_ptr targetCallback = FindTargetCallback(formId); + if (targetCallback == nullptr) { + APP_LOGE("%{public}s error, can't find target callback. formId: %{public}" PRId64 ".", __func__, formId); + return; + } + APP_LOGI("%{public}s, formId: %{public}" PRId64 ", jspath: %{public}s, data: %{public}s", __func__, formId, + formJsInfo.jsFormCodePath.c_str(), formJsInfo.formData.c_str()); + targetCallback->ProcessFormUpdate(formJsInfo); +} + +/** + * @brief Update form. + * + * @param formJsInfo Form js info. + * @return none. + */ +void FormHostClient::OnUpdate(const FormJsInfo &formJsInfo) +{ + APP_LOGI("%{public}s called.", __func__); + int64_t formId = formJsInfo.formId; + if (formId < 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); + return; + } + std::shared_ptr targetCallback = FindTargetCallback(formId); + if (targetCallback == nullptr) { + APP_LOGE("%{public}s error, can't find target callback. formId: %{public}" PRId64 ".", __func__, formId); + return; + } + targetCallback->ProcessFormUpdate(formJsInfo); +} + +/** + * @brief UnInstall the forms. + * + * @param formIds The Id of the forms. + * @return none. + */ +void FormHostClient::OnUninstall(const std::vector &formIds) +{ + APP_LOGI("%{public}s called.", __func__); + if (formIds.size() <= 0) { + APP_LOGE("%{public}s error, formIds is empty.", __func__); + return; + } + for (auto &formId : formIds) { + if (formId < 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); + continue; + } + std::shared_ptr targetCallback = FindTargetCallback(formId); + if (targetCallback == nullptr) { + APP_LOGE("%{public}s error, can't find target callback. formId: %{public}" PRId64 ".", __func__, formId); + continue; + } + targetCallback->ProcessFormUninstall(formId); + } +} + +/** + * @brief Find callback by formId. + * + * @param formId The Id of the form. + * @return target callback + */ +std::shared_ptr FormHostClient::FindTargetCallback(int64_t formId) +{ + std::lock_guard lock(lockMutex_); + for (auto record : recordHostForms_) { + if (record.second.Contains(formId)) { + return recordCallback_[record.first]; + } + } + return nullptr; +} + +/** + * @brief Find Key By form callback. + * + * @param formCallback The form callback. + * @return callback's key + */ +int32_t FormHostClient::FindKeyByCallback(std::shared_ptr formCallback) +{ + for (auto recordCallback : recordCallback_) { + if (Compare(recordCallback.second, formCallback)) { + return recordCallback.first; + } + } + return -1; +} + +/** + * @brief Compare form callback. + * + * @param formCallback1 The form callback. + * @param formCallback2 The form callback to be compared with form callback1. + * @return Returns true if the two form callback are equal to each other, returns false otherwise. + */ +bool FormHostClient::Compare(std::shared_ptr formCallback1, + std::shared_ptr formCallback2) +{ + return (formCallback1 == formCallback2) ? true : false; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/fmskit/native/src/form_mgr.cpp b/frameworks/kits/fmskit/native/src/form_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cc0e4306d8c52359be8cb636b54629775464e03 --- /dev/null +++ b/frameworks/kits/fmskit/native/src/form_mgr.cpp @@ -0,0 +1,598 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_mgr.h" + +#include + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "form_errors.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +FormMgr::FormMgr(){} +FormMgr::~FormMgr() +{ + if (remoteProxy_ != nullptr) { + auto remoteObject = remoteProxy_->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + } +} +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::AddForm( + const int64_t formId, + const Want &want, + const sptr &callerToken, + FormJsInfo &formInfo) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->AddForm(formId, want, callerToken, formInfo); +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->DeleteForm(formId, callerToken); +} + +/** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->ReleaseForm(formId, callerToken, delCache); +} + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formBindingData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::UpdateForm(const int64_t formId, const std::string &bundleName, const FormProviderData &formBindingData) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->UpdateForm(formId, bundleName, formBindingData); +} + +/** + * @brief Notify the form service that the form user's lifecycle is updated. + * + * This should be called when form user request form. + * + * @param formId Indicates the unique id of form. + * @param callerToken Indicates the callback remote object of specified form user. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ +int FormMgr::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->RequestForm(formId, callerToken, want); +} + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::NotifyWhetherVisibleForms( + const std::vector &formIds, + const sptr &callerToken, + const int32_t formVisibleType) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); +} + +/** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return None. + */ +int FormMgr::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->CastTempForm(formId, callerToken); +} + +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DumpStorageFormInfos(std::string &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->DumpStorageFormInfos(formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DumpFormInfoByBundleName(const std::string bundleName, std::string &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->DumpFormInfoByBundleName(bundleName, formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->DumpFormInfoByFormId(formId, formInfo); +} +/** + * @brief Dump form timer by form id. + * @param formId The id of the form. + * @param formInfo Form timer. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->DumpFormTimerByFormId(formId, isTimingService); +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgr::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->MessageEvent(formId, want, callerToken); +} + +/** + * @brief Set next refresh time. + * @param formId The id of the form. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->SetNextRefreshTime(formId, nextTime); +} + +/** + * @brief Lifecycle Update. + * @param formIds The id of the forms. + * @param callerToken Host client. + * @param updateType Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::LifecycleUpdate( + const std::vector &formIds, + const sptr &callerToken, + const int32_t updateType) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->LifecycleUpdate(formIds, callerToken, updateType); +} +/** + * @brief Get fms recoverStatus. + * + * @return The current recover status. + */ +int FormMgr::GetRecoverStatus() +{ + APP_LOGI("%{public}s called.", __func__); + return recoverStatus_; +} + +/** + * @brief Set fms recoverStatus. + * + * @param recoverStatus The recover status. + */ +void FormMgr::SetRecoverStatus(int recoverStatus) +{ + APP_LOGI("%{public}s called.", __func__); + recoverStatus_ = recoverStatus; +} + +/** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ +std::string FormMgr::GetErrorMessage(int errCode) +{ + APP_LOGI("%{public}s called.", __func__); + return FormErrors::GetInstance().GetErrorMessage(errCode); +} + +/** + * @brief Register death callback. + * + * @param deathCallback Death callback. + */ +void FormMgr::RegisterDeathCallback(const std::shared_ptr &formDeathCallback) +{ + APP_LOGI("%{public}s called.", __func__); + if (formDeathCallback == nullptr) { + APP_LOGE("%{public}s error, form death callback is nullptr.", __func__); + return; + } + formDeathCallbacks_.emplace_back(formDeathCallback); +} + +/** + * @brief UnRegister death callback. + * + * @param deathCallback Death callback. + */ +void FormMgr::UnRegisterDeathCallback(const std::shared_ptr &formDeathCallback) +{ + APP_LOGI("%{public}s called.", __func__); + if (formDeathCallback == nullptr) { + APP_LOGE("%{public}s error, form death callback is nullptr.", __func__); + return; + } + + // Remove the specified death callback in the vector of death callback + auto iter = std::find(formDeathCallbacks_.begin(), formDeathCallbacks_.end(), formDeathCallback); + if (iter != formDeathCallbacks_.end()) { + formDeathCallbacks_.erase(iter); + } + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Get death recipient. + * @return deathRecipient_. + */ +sptr FormMgr::GetDeathRecipient() const +{ + return deathRecipient_; +} + +/** + * @brief Check whether the specified death callback is registered in form mgr. + * @param formDeathCallback The specified death callback for checking. + * @return Return true on success, false on failure. + */ +bool FormMgr::CheckIsDeathCallbackRegistered(const std::shared_ptr &formDeathCallback) +{ + APP_LOGI("%{public}s called.", __func__); + auto iter = std::find(formDeathCallbacks_.begin(), formDeathCallbacks_.end(), formDeathCallback); + if (iter != formDeathCallbacks_.end()) { + return true; + } + return false; +} + +/** + * @brief Notices IRemoteBroker died. + * @param remote remote object. + */ +void FormMgr::FormMgrDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGI("%{public}s called.", __func__); + if (remote == nullptr) { + APP_LOGE("%{public}s failed, remote is nullptr.", __func__); + return; + } + + if (FormMgr::GetInstance().GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGW("%{public}s, fms in recovering.", __func__); + return; + } + // Reset proxy + FormMgr::GetInstance().ResetProxy(remote); + + if (!FormMgr::GetInstance().Reconnect()) { + APP_LOGE("%{public}s, form mgr service died, try to reconnect to fms failed.", __func__); + FormMgr::GetInstance().SetRecoverStatus(Constants::RECOVER_FAIL); + return; + } + + // refresh form host. + for (auto &deathCallback : FormMgr::GetInstance().formDeathCallbacks_) { + deathCallback->OnDeathReceived(); + } + FormMgr::GetInstance().SetRecoverStatus(Constants::NOT_IN_RECOVERY); +} + +/** + * @brief Reconnect form manager service once per 1000 milliseconds, + * until the connection succeeds or reaching the max retry times. + * @return Returns true if execute success, false otherwise. + */ +bool FormMgr::Reconnect() +{ + APP_LOGI("%{public}s called.", __func__); + for (int i = 0; i < Constants::MAX_RETRY_TIME; i++) { + // Sleep 1000 milliseconds before reconnect. + std::this_thread::sleep_for(std::chrono::milliseconds(Constants::SLEEP_TIME)); + + // try to connect fms + if (Connect() != ERR_OK) { + APP_LOGE("%{public}s, get fms proxy fail, try again.", __func__); + continue; + } + + APP_LOGI("%{public}s, get fms proxy success.", __func__); + return true; + } + + return false; +} + +/** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgr::Connect() +{ + std::lock_guard lock(connectMutex_); + if (remoteProxy_ != nullptr && !resetFlag_) { + return ERR_OK; + } + + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + APP_LOGE("%{private}s fail to get registry", __func__); + return ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED; + } + sptr remoteObject = systemManager->GetSystemAbility(FORM_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + APP_LOGE("%{private}s fail to connect FormMgrService", __func__); + return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; + } + deathRecipient_ = sptr(new FormMgrDeathRecipient()); + if (deathRecipient_ == nullptr) { + APP_LOGE("%{public}s Failed to create FormMgrDeathRecipient!", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if ((remoteObject->IsProxyObject()) && (!remoteObject->AddDeathRecipient(deathRecipient_))) { + APP_LOGE("%{public}s Add death recipient to FormMgrService failed.", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + remoteProxy_ = iface_cast(remoteObject); + APP_LOGD("%{public}s Connecting FormMgrService success.", __func__); + return ERR_OK; +} + +/** + * @brief Reset proxy. + * @param remote remote object. + */ +void FormMgr::ResetProxy(const wptr &remote) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock(connectMutex_); + if (remoteProxy_ == nullptr) { + APP_LOGE("%{public}s failed, remote proxy is nullptr.", __func__); + return; + } + + // set formMgr's recover status to IN_RECOVERING. + recoverStatus_ = Constants::IN_RECOVERING; + + // remove the death recipient + auto serviceRemote = remoteProxy_->AsObject(); + if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) { + serviceRemote->RemoveDeathRecipient(deathRecipient_); + } + // clearn the remote proxy + remoteProxy_ = nullptr; +} + +/** + * @brief Set form mgr service for test. + */ +void FormMgr::SetFormMgrService(sptr formMgrService) +{ + APP_LOGI("%{public}s called.", __func__); + remoteProxy_ = formMgrService; +} + +/** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DistributedDataAddForm(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->DistributedDataAddForm(want); +} + +/** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DistributedDataDeleteForm(const std::string &formId) +{ + APP_LOGI("%{public}s called.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->DistributedDataDeleteForm(formId); +} + +/** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::GetAllFormsInfo(std::vector &formInfos) +{ + APP_LOGI("%{public}s start.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGI("%{public}s failed, errCode: %{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->GetAllFormsInfo(formInfos); +} + +/** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) +{ + APP_LOGI("%{public}s start.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->GetFormsInfoByApp(bundleName, formInfos); +} + +/** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector &formInfos) +{ + APP_LOGI("%{public}s start.", __func__); + int errCode = Connect(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s failed errCode:%{public}d.", __func__, errCode); + return errCode; + } + return remoteProxy_->GetFormsInfoByModule(bundleName, moduleName, formInfos); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/runtime/native/js_data_struct_converter.cpp b/frameworks/kits/runtime/native/js_data_struct_converter.cpp index b4a9583fba2f798800523bee9b4243f74e33cd85..593c3c7b4e17f69fbf8671a3ff19f7e7f16e0c3b 100644 --- a/frameworks/kits/runtime/native/js_data_struct_converter.cpp +++ b/frameworks/kits/runtime/native/js_data_struct_converter.cpp @@ -78,11 +78,33 @@ NativeValue* CreateJsAbilityInfo(NativeEngine& engine, const AppExecFwk::Ability object->SetProperty("minFormWidth", CreateJsValue(engine, abilityInfo.minFormWidth)); object->SetProperty("defaultFormWidth", CreateJsValue(engine, abilityInfo.defaultFormWidth)); object->SetProperty("uri", CreateJsValue(engine, abilityInfo.uri)); - // customizeData: Map>; + object->SetProperty("metaData", CreateJsCustomizeDataArray(engine, abilityInfo.metaData.customizeData)); return objValue; } +NativeValue* CreateJsCustomizeData(NativeEngine& engine, const AppExecFwk::CustomizeData &Info) +{ + NativeValue *objValue = engine.CreateObject(); + NativeObject *object = ConvertNativeValueTo(objValue); + + object->SetProperty("name", CreateJsValue(engine, Info.name)); + object->SetProperty("value", CreateJsValue(engine, Info.value)); + object->SetProperty("extra", CreateJsValue(engine, Info.extra)); + return objValue; +} + +NativeValue* CreateJsCustomizeDataArray(NativeEngine& engine, const std::vector &info) +{ + NativeValue* arrayValue = engine.CreateArray(info.size()); + NativeArray* array = ConvertNativeValueTo(arrayValue); + uint32_t index = 0; + for (const auto& item : info) { + array->SetElement(index++, CreateJsCustomizeData(engine, item)); + } + return arrayValue; +} + NativeValue* CreateJsModuleInfo(NativeEngine& engine, const AppExecFwk::ModuleInfo &moduleInfo) { NativeValue *objValue = engine.CreateObject(); @@ -126,6 +148,10 @@ NativeValue* CreateJsApplicationInfo(NativeEngine& engine, const AppExecFwk::App } } object->SetProperty("moduleInfo", arrayValue); + // metaData: Map>; + for (auto &item : applicationInfo.metaData) { + object->SetProperty(item.first.c_str(), CreateJsCustomizeDataArray(engine, item.second)); + } return objValue; } @@ -140,5 +166,16 @@ NativeValue* CreateJsLaunchParam(NativeEngine& engine, const AAFwk::LaunchParam& return objValue; } + +NativeValue* CreateJsConfiguration(NativeEngine& engine, const AppExecFwk::Configuration& configuration) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + object->SetProperty("language", CreateJsValue(engine, configuration.GetItem("ohos.system.language"))); + object->SetProperty("orientation", CreateJsValue(engine, configuration.GetItem("ohos.system.orientation"))); + + return objValue; +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/runtime/native/js_runtime.cpp b/frameworks/kits/runtime/native/js_runtime.cpp index 85c64e55541c1726fa611fd26c1ecce05689a3f5..cd874720bc2fe3fd37151c1283553f00bf303a42 100644 --- a/frameworks/kits/runtime/native/js_runtime.cpp +++ b/frameworks/kits/runtime/native/js_runtime.cpp @@ -21,6 +21,7 @@ #include #include "native_engine/impl/ark/ark_native_engine.h" +#include "declarative_module_preloader.h" #include "event_handler.h" #include "hilog_wrapper.h" @@ -240,11 +241,14 @@ bool JsRuntime::Initialize(const Options& options) { // Create event handler for runtime eventHandler_ = std::make_shared(options.eventRunner); - idleTask_ = [this]() { - nativeEngine_->Loop(LOOP_NOWAIT); - eventHandler_->PostIdleTask(idleTask_); - }; - eventHandler_->PostIdleTask(idleTask_); + nativeEngine_->SetPostTask([this](bool needSync) { + eventHandler_->PostTask( + [this, needSync]() { + nativeEngine_->Loop(LOOP_NOWAIT, needSync); + }, + "idleTask"); + }); + nativeEngine_->CheckUVLoop(); HandleScope handleScope(*this); @@ -269,6 +273,7 @@ bool JsRuntime::Initialize(const Options& options) return false; } + OHOS::Ace::DeclarativeModulePreloader::Preload(*nativeEngine_); codePath_ = options.codePath; return true; } @@ -281,6 +286,8 @@ void JsRuntime::Deinitialize() } methodRequireNapiRef_.reset(); + nativeEngine_->CancelCheckUVLoop(); + RemoveTask("idleTask"); nativeEngine_.reset(); } @@ -468,5 +475,10 @@ NativeValue* JsRuntime::ClearCallbackTimer(NativeEngine& engine, NativeCallbackI JsRuntime::RemoveTask(name); return engine.CreateUndefined(); } + +std::string JsRuntime::BuildNativeAndJsBackStackTrace() +{ + return nativeEngine_->BuildNativeAndJsBackStackTrace(); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/runtime/test/BUILD.gn b/frameworks/kits/runtime/test/BUILD.gn index 37331c48dd1e08493bb40f864d5af7559d0571f4..d86d6a4c016608affff781b959e7148b8189b2ca 100644 --- a/frameworks/kits/runtime/test/BUILD.gn +++ b/frameworks/kits/runtime/test/BUILD.gn @@ -16,8 +16,8 @@ import("//build/ohos.gni") ohos_executable("runtime_test") { sources = [ "main.cpp" ] - external_deps = [ "aafwk_standard:runtime" ] + external_deps = [ "ability_runtime:runtime" ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/frameworks/kits/test/BUILD.gn b/frameworks/kits/test/BUILD.gn index bd9f64940dfe90509af3b68985b57af294fc9b14..b2c93bb7c5cc95f90806918b5a8f46a14bc0090d 100644 --- a/frameworks/kits/test/BUILD.gn +++ b/frameworks/kits/test/BUILD.gn @@ -13,7 +13,7 @@ import("//build/test.gni") -module_output_path = "aafwk_standard/aafwk_L2" +module_output_path = "ability_runtime/aafwk_L2" ############################################################################### #1. intent(c++) get/set test without transport @@ -93,13 +93,14 @@ ohos_moduletest("ability_moduletest") { "//base/hiviewdfx/hiview/adapter/utility:hiview_adapter_utility", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", @@ -154,13 +155,14 @@ ohos_moduletest("ability_conetxt_test") { "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", @@ -225,13 +227,14 @@ ohos_moduletest("data_ability_operation_moduletest") { "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", @@ -274,12 +277,12 @@ ohos_moduletest("data_ability_helper_module_test") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/frameworks/kits/test/mock/AMS/mock_ability_manager_client.cpp b/frameworks/kits/test/mock/AMS/mock_ability_manager_client.cpp index 1afdcd097d8a92681f21234114c7946d3304b520..2aecb5f8131ac4d7c4b04165e56829085ab058a5 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_client.cpp +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_client.cpp @@ -105,13 +105,13 @@ void AbilityManagerClient::AddWindowInfo(const sptr &token, int32 abms->AddWindowInfo(token, windowToken); } -ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode) +ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode, int32_t userId) { if (remoteObject_ == nullptr) { return ABILITY_SERVICE_NOT_CONNECTED; } sptr abms = iface_cast(remoteObject_); - return abms->StartAbility(want, requestCode); + return abms->StartAbility(want, userId, requestCode); } ErrCode AbilityManagerClient::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) @@ -137,7 +137,7 @@ ErrCode AbilityManagerClient::TerminateAbility(const sptr &caller } ErrCode AbilityManagerClient::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { if (remoteObject_ == nullptr) { remoteObject_ = diff --git a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp index 5efa32557d2b1f8d88fd94360e7b141cccf225e9..85e0079c8428034c51282816ba1bcb4a35b5d7c1 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp @@ -33,7 +33,7 @@ MockAbilityManagerService::MockAbilityManagerService() : abilityScheduler_(nullp MockAbilityManagerService::~MockAbilityManagerService() {} -int MockAbilityManagerService::StartAbility(const Want &want, int requestCode) +int MockAbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode) { GTEST_LOG_(INFO) << "MockAbilityManagerService::StartAbility called"; curstate_ = AbilityLifeCycleState::ABILITY_STATE_INITIAL; @@ -68,7 +68,8 @@ int MockAbilityManagerService::StartAbility(const Want &want, int requestCode) return 0; } -int MockAbilityManagerService::StartAbility(const Want &want, const sptr &callerToken, int requestCode) +int MockAbilityManagerService::StartAbility(const Want &want, const sptr &callerToken, + int32_t userId, int requestCode) { return 0; } @@ -91,7 +92,7 @@ int MockAbilityManagerService::TerminateAbility( } int MockAbilityManagerService::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { if (abilityScheduler_ != nullptr) { PacMap inState; @@ -128,6 +129,10 @@ int MockAbilityManagerService::AttachAbilityThread( void MockAbilityManagerService::DumpState(const std::string &args, std::vector &info) {} +void MockAbilityManagerService::DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) +{} + int MockAbilityManagerService::AbilityTransitionDone( const sptr &token, int state, const PacMap &saveData) { @@ -165,7 +170,7 @@ int MockAbilityManagerService::TerminateAbilityResult(const sptr return 0; } -int MockAbilityManagerService::StopServiceAbility(const Want &want) +int MockAbilityManagerService::StopServiceAbility(const Want &want, int32_t userId) { return 0; } @@ -234,6 +239,5 @@ int MockAbilityManagerService::PowerOn() { return 0; } - } // namespace AAFwk } // namespace OHOS diff --git a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h index 2c172379b52e42422081f5924fa5fce4c66b09b8..ae22c4a306fcf42df45cd4aa1ffbc15871761381 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h @@ -35,8 +35,20 @@ class MockAbilityManagerService : public AbilityManagerStub, public: MockAbilityManagerService(); ~MockAbilityManagerService(); - int StartAbility(const Want &want, int requestCode = -1) override; - int StartAbility(const Want &want, const sptr &callerToken, int requestCode = -1) override; + int StartAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) override; + int StartAbility(const Want &want, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = -1) override; + int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override + { + return 0; + } int TerminateAbility( const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; int MinimizeAbility(const sptr &token) override @@ -44,7 +56,10 @@ public: return 0; } int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) override; + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) override; int DisconnectAbility(const sptr &connect) override; sptr AcquireDataAbility(const Uri &uri, bool tryBind, const sptr &callerToken); @@ -61,9 +76,11 @@ public: int ScheduleCommandAbilityDone(const sptr &token) override; void DumpState(const std::string &args, std::vector &info) override; + void DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) override; int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) override; int TerminateAbilityResult(const sptr &token, int startId) override; - int StopServiceAbility(const Want &want) override; + int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) override; MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); @@ -84,8 +101,8 @@ public: MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); MOCK_METHOD1(SetShowOnLockScreen, int(bool isAllow)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); - MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode)); + MOCK_METHOD5(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int32_t userId, int requestCode)); MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); MOCK_METHOD2(MoveMissionToSplitScreenStack, int(const MissionOption &primary, const MissionOption &secondary)); MOCK_METHOD2( @@ -113,8 +130,14 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr &, const sptr &)); + int MoveMissionToEnd(const sptr &token, const bool nonFirst) override; bool IsFirstInMission(const sptr &token) override; int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override; @@ -187,6 +210,60 @@ public: return 0; } + virtual int ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) override + { + return 0; + } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + virtual bool SendANRProcessID(int pid) override + { + return true; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } + AbilityLifeCycleState curstate_ = AbilityLifeCycleState::ABILITY_STATE_INITIAL; sptr abilityScheduler_; // kit interface used to schedule ability life Want want_; diff --git a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp index 1c13ed493217ebb538f9e87729e217ea5f99e75e..d0d74aa39a7dfacd20070876d8fd6da18ac56a85 100644 --- a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp +++ b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp @@ -31,7 +31,7 @@ MockServiceAbilityManagerService::MockServiceAbilityManagerService() MockServiceAbilityManagerService::~MockServiceAbilityManagerService() {} -int MockServiceAbilityManagerService::StartAbility(const Want &want, int requestCode) +int MockServiceAbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode) { GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::StartAbility"; if (abilityScheduler_ != nullptr) { @@ -46,7 +46,7 @@ int MockServiceAbilityManagerService::StartAbility(const Want &want, int request } int MockServiceAbilityManagerService::StartAbility( - const Want &want, const sptr &callerToken, int requestCode) + const Want &want, const sptr &callerToken, int32_t userId, int requestCode) { return 0; } @@ -67,7 +67,7 @@ int MockServiceAbilityManagerService::TerminateAbility( } int MockServiceAbilityManagerService::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::connectAbility"; if (abilityScheduler_ != nullptr) { @@ -104,6 +104,10 @@ int MockServiceAbilityManagerService::AttachAbilityThread( void MockServiceAbilityManagerService::DumpState(const std::string &args, std::vector &info) {} +void MockServiceAbilityManagerService::DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) +{} + int MockServiceAbilityManagerService::AbilityTransitionDone( const sptr &token, int state, const PacMap &saveData) { @@ -158,7 +162,7 @@ int MockServiceAbilityManagerService::TerminateAbilityByCaller(const sptr &callerToken, int requestCode = -1) override; + int StartAbility( + const Want &want, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; + int StartAbility( + const Want &want, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; + int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override + { + return 0; + } int TerminateAbility( const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; int MinimizeAbility(const sptr &token) override @@ -43,7 +59,10 @@ public: return 0; } int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) override; + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) override; int DisconnectAbility(const sptr &connect) override; void AddWindowInfo(const sptr &token, int32_t windowToken) override; @@ -56,9 +75,11 @@ public: int ScheduleCommandAbilityDone(const sptr &token) override; void DumpState(const std::string &args, std::vector &info) override; + void DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) override; int TerminateAbilityResult(const sptr &token, int startId) override; - int StopServiceAbility(const Want &want) override; + int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) override; int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) override; @@ -78,8 +99,8 @@ public: MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); - MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode)); + MOCK_METHOD5(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int32_t userId, int requestCode)); MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); MOCK_METHOD2(MoveMissionToSplitScreenStack, int(const MissionOption &primary, const MissionOption &secondary)); MOCK_METHOD2( @@ -108,9 +129,15 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); - + + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr &, const sptr &)); + int MoveMissionToEnd(const sptr &token, const bool nonFirst) override; bool IsFirstInMission(const sptr &token) override; int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override; @@ -202,6 +229,61 @@ public: { return 0; } + virtual int ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) override + { + return 0; + } + + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + virtual bool SendANRProcessID(int pid) override + { + return true; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } sptr abilityScheduler_ = nullptr; // kit interface used to schedule ability life Want want_; diff --git a/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h b/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h index 2211492767c45ea0c6708fd06c3f9d35e123055f..fe32ccc474715d64c16ee6103e865619d4915344 100644 --- a/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h +++ b/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h @@ -72,7 +72,7 @@ public: return -1; } fd = fileno(fd2); - + return fd; } diff --git a/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h b/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h index fc44c7dda0a63b79ad9d8250cd5c43dd30745148..96997c597ddebd71233a1144b1fb5017ed15e6e4 100644 --- a/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h +++ b/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h @@ -37,7 +37,7 @@ public: DemoAbilityManagerClientData() {}; virtual ~DemoAbilityManagerClientData() {}; - std::map> data; + std::map> data; }; static DemoAbilityManagerClientData demoAbilityMgrClientData; @@ -52,9 +52,9 @@ sptr AAFwk::AbilityManagerClient::AcquireDataAbility( sptr abilityThread = AppExecFwk::MockCreateAbilityThread(); sptr remoteProxy(new (std::nothrow) AAFwk::AbilitySchedulerProxy(abilityThread)); demoAbilityMgrClientData.data.emplace(uri.ToString(), remoteProxy); - + retval = remoteProxy; - + if (retval == nullptr) { GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock result retval is nullptr called"; } diff --git a/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp index c645ec882caa58d0a019da713976db3268e0fe3e..f02cd40c97bdf166f21b588323c23fc3f57aebaa 100644 --- a/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp @@ -122,7 +122,7 @@ HWTEST_F(DataAbilityOperationModuleTest, AaFwk_DataAbilityOperation_AssertBuilde int count = operation->GetExpectedCount(); EXPECT_EQ(count, 2); - + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_AssertBuilder_0100"; } @@ -144,7 +144,7 @@ HWTEST_F(DataAbilityOperationModuleTest, AaFwk_DataAbilityOperation_DeleteBuilde EXPECT_NE(operation, nullptr); bool isDeleteOperation = operation->IsDeleteOperation(); EXPECT_TRUE(isDeleteOperation); - + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_DeleteBuilder_0100"; } diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index f3c7715eaea4c8734b1fe61d9e0e71857c2893af..458e8b9923e3f7e5f54e071d150ee0b6c0994f39 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -14,9 +14,14 @@ group("innerkits_target") { deps = [ "ability_manager:ability_manager", + "app_manager:app_manager", "base:base", "dataobs_manager:dataobs_manager", "intent:intent", "want:want", ] } + +group("fms_innerkits_target") { + deps = [ "form_manager:form_manager" ] +} diff --git a/interfaces/innerkits/ability_manager/BUILD.gn b/interfaces/innerkits/ability_manager/BUILD.gn index ea024b0226e2693dbc1e6546fe13f0ccf83e0602..17865d3150ec9e87e8cb85c14d4364cd084109e2 100644 --- a/interfaces/innerkits/ability_manager/BUILD.gn +++ b/interfaces/innerkits/ability_manager/BUILD.gn @@ -26,8 +26,8 @@ config("ability_manager_public_config") { "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", "//foundation/multimedia/image_standard/interfaces/innerkits/include", "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb/include", "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk/include", @@ -48,10 +48,12 @@ ohos_shared_library("ability_manager") { "${services_path}/abilitymgr/src/ability_manager_stub.cpp", "${services_path}/abilitymgr/src/ability_mission_info.cpp", "${services_path}/abilitymgr/src/ability_record_info.cpp", + "${services_path}/abilitymgr/src/ability_running_info.cpp", "${services_path}/abilitymgr/src/ability_scheduler_proxy.cpp", "${services_path}/abilitymgr/src/ability_scheduler_stub.cpp", "${services_path}/abilitymgr/src/ability_start_setting.cpp", "${services_path}/abilitymgr/src/caller_info.cpp", + "${services_path}/abilitymgr/src/extension_running_info.cpp", "${services_path}/abilitymgr/src/image_info.cpp", "${services_path}/abilitymgr/src/launch_param.cpp", "${services_path}/abilitymgr/src/lifecycle_state_info.cpp", @@ -73,6 +75,7 @@ ohos_shared_library("ability_manager") { "${services_path}/abilitymgr/src/stop_user_callback_proxy.cpp", "${services_path}/abilitymgr/src/stop_user_callback_stub.cpp", "${services_path}/abilitymgr/src/want_sender_info.cpp", + "${services_path}/abilitymgr/src/want_sender_stub.cpp", "${services_path}/abilitymgr/src/wants_info.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_operation.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp", @@ -90,6 +93,7 @@ ohos_shared_library("ability_manager") { "${innerkits_path}/base:base", "${innerkits_path}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", @@ -113,5 +117,5 @@ ohos_shared_library("ability_manager") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/innerkits/ability_manager/ability_manager_headers.gni b/interfaces/innerkits/ability_manager/ability_manager_headers.gni index 5913ebcafca8dcc11af8ee84109cdef13e7e2383..057a03e5b0569011fb058dbcb28b28d554626883 100644 --- a/interfaces/innerkits/ability_manager/ability_manager_headers.gni +++ b/interfaces/innerkits/ability_manager/ability_manager_headers.gni @@ -18,7 +18,9 @@ ability_manager_headers = { "ability_manager_client.h", "ability_manager_errors.h", "ability_manager_interface.h", + "ability_running_info.h", "ability_scheduler_interface.h", + "extension_running_info.h", "lifecycle_state_info.h", "mission_stack_info.h", "stack_info.h", diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_client.h b/interfaces/innerkits/ability_manager/include/ability_manager_client.h index 57887f13dc8208f93c5ffb114d51adcb6efbd75a..18cab581e9a9eb3020938f98d37f19819f794a29 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_client.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_client.h @@ -22,6 +22,7 @@ #include "ability_manager_errors.h" #include "ability_scheduler_interface.h" #include "ability_manager_interface.h" +#include "snapshot.h" #include "want.h" #include "iremote_object.h" @@ -97,7 +98,7 @@ public: * @param requestCode Ability request code. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE); + ErrCode StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE, int32_t userId = DEFAULT_INVAL_VALUE); /** * StartAbility with want, send want to ability manager service. @@ -108,7 +109,10 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode StartAbility( - const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE); + const Want &want, + const sptr &callerToken, + int requestCode = DEFAULT_INVAL_VALUE, + int32_t userId = DEFAULT_INVAL_VALUE); /** * Starts a new ability with specific start settings. @@ -118,8 +122,12 @@ public: * @param abilityStartSetting Indicates the setting ability used to start. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE); + ErrCode StartAbility( + const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int requestCode = DEFAULT_INVAL_VALUE, + int32_t userId = DEFAULT_INVAL_VALUE); /** * Starts a new ability with specific start options. @@ -130,8 +138,12 @@ public: * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StartAbility(const Want &want, const StartOptions &startOptions, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE); + ErrCode StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int requestCode = DEFAULT_INVAL_VALUE, + int32_t userId = DEFAULT_INVAL_VALUE); /** * TerminateAbility with want, return want from ability manager service. @@ -181,7 +193,10 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken); + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE); /** * DisconnectAbility, disconnect session with service ability. @@ -219,7 +234,8 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode DumpState(const std::string &args, std::vector &state); - + ErrCode DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID); /** * Connect ability manager service. * @@ -357,8 +373,7 @@ public: * mission. This parameter cannot be null. * @return Returns ERR_OK on success, others on failure. */ - ErrCode SetMissionDescriptionInfo( - const sptr &token, const MissionDescriptionInfo &description); + ErrCode SetMissionDescriptionInfo(const sptr &token, const MissionDescriptionInfo &description); /** * get current system mission lock mode state. @@ -475,8 +490,8 @@ public: * @param wantParams, extended params. * @return Returns ERR_OK on success, others on failure. */ - ErrCode ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, - int32_t missionId, const sptr &callback, AAFwk::WantParams &wantParams); + ErrCode ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, + const sptr &callback, AAFwk::WantParams &wantParams); /** * start continuation. @@ -535,8 +550,7 @@ public: * * @return Returns ERR_OK on success, others on failure. */ - ErrCode RegisterMissionListener(const std::string &deviceId, - const sptr &listener); + ErrCode RegisterMissionListener(const std::string &deviceId, const sptr &listener); /** * @brief UnRegister mission listener from ability manager service. @@ -545,8 +559,7 @@ public: * * @return Returns ERR_OK on success, others on failure. */ - ErrCode UnRegisterMissionListener(const std::string &deviceId, - const sptr &listener); + ErrCode UnRegisterMissionListener(const std::string &deviceId, const sptr &listener); /** * @brief Get mission infos from ams. @@ -556,7 +569,7 @@ public: * * @return Returns ERR_OK on success, others on failure. */ - ErrCode GetMissionInfos(const std::string& deviceId, int32_t numMax, std::vector &missionInfos); + ErrCode GetMissionInfos(const std::string &deviceId, int32_t numMax, std::vector &missionInfos); /** * @brief Get mission info by id. @@ -566,7 +579,16 @@ public: * * @return Returns ERR_OK on success, others on failure. */ - ErrCode GetMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo); + ErrCode GetMissionInfo(const std::string &deviceId, int32_t missionId, MissionInfo &missionInfo); + + /** + * @brief Get the Mission Snapshot Info object + * @param deviceId local or remote deviceid. + * @param missionId Id of target mission. + * @param snapshot snapshot of target mission + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot); /** * @brief Clean mission by id. @@ -590,6 +612,30 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode MoveMissionToFront(int32_t missionId); + + /** + * Start Ability, connect session with common ability. + * + * @param want, Special want for service type's ability. + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callToken); + + /** + * Release Ability, disconnect session with common ability. + * + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ReleaseAbility(const sptr &connect, const AppExecFwk::ElementName &element); + + ErrCode GetAbilityRunningInfos(std::vector &info); + + ErrCode GetExtensionRunningInfos(int upperLimit, std::vector &info); + + ErrCode GetProcessRunningInfos(std::vector &info); /** * Start synchronizing remote device mission @@ -598,14 +644,14 @@ public: * @param tag, call tag. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag); + ErrCode StartSyncRemoteMissions(const std::string &devId, bool fixConflict, int64_t tag); /** * Stop synchronizing remote device mission * @param devId, deviceId. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StopSyncRemoteMissions(const std::string& devId); + ErrCode StopSyncRemoteMissions(const std::string &devId); /** * @brief start user. @@ -623,6 +669,68 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode StopUser(int accountId, const sptr &callback); + + /** + * @brief Register the snapshot handler + * @param handler snapshot handler + * @return ErrCode Returns ERR_OK on success, others on failure. + */ + ErrCode RegisterSnapshotHandler(const sptr& handler); + + /** + * Set mission label of this ability. + * + * @param abilityToken Indidate token of ability. + * @param label Indidate the label showed of the ability in recent missions. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SetMissionLabel(const sptr &abilityToken, const std::string &label); + + /** + * @brief start user test. + * @param want the want of the ability user test to start. + * @param observer test observer callback. + * + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode StartUserTest(const Want &want, const sptr &observer); + + /** + * @brief Finish user test. + * @param msg user test message. + * @param resultCode user test result Code. + * @param bundleName user test bundleName. + * @param observer test observer callback. + * + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer); + + /** + * GetCurrentTopAbility, get the token of current top ability. + * + * @param token, the token of current top ability. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetCurrentTopAbility(sptr &token); + + /** + * DelegatorDoAbilityForeground, the delegator calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DelegatorDoAbilityForeground(const sptr &token); + + /** + * DelegatorDoAbilityBackground, the delegator calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DelegatorDoAbilityBackground(const sptr &token); + private: static std::mutex mutex_; static std::shared_ptr instance_; diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h index dd99e8b401bff66a4bd92b5b81625f20b14dedf1..f2248c6d20658b72dc204f714e053e44ca5a4619 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h @@ -329,6 +329,32 @@ enum { * Result(2097217) for clear the application data fail. */ CLEAR_APPLICATION_DATA_FAIL, + + // for call ability + /** + * Result(2097218) for resolve ability failed, there is no permissions + */ + RESOLVE_CALL_NO_PERMISSIONS, + + /** + * Result(2097219) for resolve ability failed, target ability not page or singleton + */ + RESOLVE_CALL_ABILITY_TYPE_ERR, + + /** + * Result(2097220) for resolve ability failed, resolve failed. + */ + RESOLVE_CALL_ABILITY_INNER_ERR, + + /** + * Result(2097221) for resolve ability failed, resolve failed. + */ + RESOLVE_CALL_ABILITY_VERSION_ERR, + + /** + * Result(2097222) for release ability failed, release failed. + */ + RELEASE_CALL_ABILITY_INNER_ERR, /** * Result(2097216) for register remote mission listener fail. @@ -339,6 +365,16 @@ enum { * Result(2097217) for unregister remote mission listener fail. */ UNREGISTER_REMOTE_MISSION_LISTENER_FAIL, + + /** + * Result() for invalid userid. + */ + INVALID_USERID_VALUE, + + /** + * Result() for start user test fail. + */ + START_USER_TEST_FAIL, }; enum { diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h old mode 100755 new mode 100644 index 31bf7e3d1cd20f5539966973008bb4329eded7d1..1039ee270dc986fce37b1011fd82fc639ef0e670 --- a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h @@ -24,9 +24,11 @@ #include "ability_connect_callback_interface.h" #include "ability_scheduler_interface.h" #include "ability_start_setting.h" -#include "foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/configuration.h" +#include "foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr/configuration.h" #include "mission_snapshot.h" #include "ability_mission_info.h" +#include "ability_running_info.h" +#include "extension_running_info.h" #include "mission_option.h" #include "stack_info.h" #include "stack_setting.h" @@ -40,10 +42,12 @@ #include "system_memory_attr.h" #include "mission_listener_interface.h" #include "mission_info.h" +#include "snapshot.h" #include "start_options.h" #include "stop_user_callback.h" +#include "running_process_info.h" #include "remote_mission_listener_interface.h" - +#include "iability_controller.h" namespace OHOS { namespace AAFwk { @@ -61,21 +65,29 @@ public: * StartAbility with want, send want to ability manager service. * * @param want, the want of the ability to start. + * @param userId, Designation User ID. * @param requestCode, Ability request code. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE) = 0; + virtual int StartAbility( + const Want &want, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) = 0; /** * StartAbility with want, send want to ability manager service. * * @param want, the want of the ability to start. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @param requestCode, Ability request code. * @return Returns ERR_OK on success, others on failure. */ virtual int StartAbility( - const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) = 0; + const Want &want, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) = 0; /** * Starts a new ability with specific start settings. @@ -83,10 +95,15 @@ public: * @param want Indicates the ability to start. * @param requestCode the resultCode of the ability to start. * @param abilityStartSetting Indicates the setting ability used to start. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) = 0; + virtual int StartAbility( + const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) = 0; /** * Starts a new ability with specific start options. @@ -94,11 +111,16 @@ public: * @param want, the want of the ability to start. * @param startOptions Indicates the options used to start. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const StartOptions &startOptions, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) { return 0; } + virtual int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) = 0; /** * TerminateAbility, terminate the special ability. @@ -134,10 +156,14 @@ public: * @param want, Special want for service type's ability. * @param connect, Callback used to notify caller the result of connecting or disconnecting. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ virtual int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) = 0; + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) = 0; /** * DisconnectAbility, disconnect session with service ability. @@ -229,6 +255,8 @@ public: * @return Returns ERR_OK on success, others on failure. */ virtual void DumpState(const std::string &args, std::vector &state) = 0; + virtual void DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) = 0; /** * Destroys this Service ability if the number of times it @@ -248,7 +276,7 @@ public: * @param want, Special want for service type's ability. * @return Returns true if this Service ability will be destroyed; returns false otherwise. */ - virtual int StopServiceAbility(const Want &want) = 0; + virtual int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) = 0; /** * Obtains information about ability stack that are running on the device. @@ -506,8 +534,8 @@ public: */ virtual void GetSystemMemoryAttr(AppExecFwk::SystemMemoryAttr &memoryInfo) = 0; - virtual int ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, - int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams) = 0; + virtual int ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, + const sptr &callBack, AAFwk::WantParams &wantParams) = 0; virtual int ContinueAbility(const std::string &deviceId, int32_t missionId) = 0; @@ -525,22 +553,49 @@ public: virtual int UnRegisterMissionListener(const sptr &listener) = 0; - virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, - std::vector &missionInfos) = 0; + virtual int GetMissionInfos( + const std::string &deviceId, int32_t numMax, std::vector &missionInfos) = 0; - virtual int GetMissionInfo(const std::string& deviceId, int32_t missionId, - MissionInfo &missionInfo) = 0; + virtual int GetMissionInfo(const std::string &deviceId, int32_t missionId, MissionInfo &missionInfo) = 0; + + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) = 0; virtual int CleanMission(int32_t missionId) = 0; virtual int CleanAllMissions() = 0; virtual int MoveMissionToFront(int32_t missionId) = 0; + + /** + * Start Ability, connect session with common ability. + * + * @param want, Special want for service type's ability. + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) = 0; + + /** + * Release Ability, disconnect session with common ability. + * + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ReleaseAbility(const sptr &connect, const AppExecFwk::ElementName &element) = 0; virtual int StartUser(int userId) = 0; virtual int StopUser(int userId, const sptr &callback) = 0; + virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) = 0; + + virtual int GetAbilityRunningInfos(std::vector &info) = 0; + + virtual int GetExtensionRunningInfos(int upperLimit, std::vector &info) = 0; + + virtual int GetProcessRunningInfos(std::vector &info) = 0; + /** * Start synchronizing remote device mission * @param devId, deviceId. @@ -548,21 +603,78 @@ public: * @param tag, call tag. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) = 0; + virtual int StartSyncRemoteMissions(const std::string &devId, bool fixConflict, int64_t tag) = 0; /** * Stop synchronizing remote device mission * @param devId, deviceId. * @return Returns ERR_OK on success, others on failure. */ - virtual int StopSyncRemoteMissions(const std::string& devId) = 0; + virtual int StopSyncRemoteMissions(const std::string &devId) = 0; - virtual int RegisterMissionListener(const std::string &deviceId, - const sptr &listener) = 0; + virtual int RegisterMissionListener(const std::string &deviceId, const sptr &listener) = 0; virtual int UnRegisterMissionListener(const std::string &deviceId, const sptr &listener) = 0; + /** + * Set ability controller. + * + * @param abilityController, The ability controller. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) = 0; + + /** + * Is user a stability test. + * + * @return Returns true if user is a stability test. + */ + virtual bool IsRunningInStabilityTest() = 0; + + /** + * @brief Register the snapshot handler + * @param handler snapshot handler + * @return int Returns ERR_OK on success, others on failure. + */ + virtual int RegisterSnapshotHandler(const sptr& handler) = 0; + + virtual int StartUserTest(const Want &want, const sptr &observer) = 0; + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) = 0; + + /** + * GetCurrentTopAbility, get the token of current top ability. + * + * @param token, the token of current top ability. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetCurrentTopAbility(sptr &token) = 0; + + /** + * The delegator calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DelegatorDoAbilityForeground(const sptr &token) = 0; + + /** + * The delegator calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DelegatorDoAbilityBackground(const sptr &token) = 0; + + /** + * Send not response process ID to ability manager service. + * @param pid The not response process ID. + */ + virtual bool SendANRProcessID(int pid) = 0; + enum { // ipc id 1-1000 for kit // ipc id for terminating ability (1) @@ -679,7 +791,7 @@ public: // ipc id for minimize ability (38) MINIMIZE_ABILITY, - // ipc id for lock mission for cleanup operation (39) + // ipc id for lock mission for cleanup operation (39) LOCK_MISSION_FOR_CLEANUP, // ipc id for unlock mission for cleanup operation (40) @@ -691,7 +803,7 @@ public: // ipc id for unregister mission listener (42) UNREGISTER_MISSION_LISTENER, - // ipc id for get mission infos (43) + // ipc id for get mission infos (43) GET_MISSION_INFOS, // ipc id for get mission info by id (44) @@ -715,6 +827,15 @@ public: // ipc id for move mission to front (50) STOP_USER, + // ipc id for set ability controller (51) + SET_ABILITY_CONTROLLER, + + // ipc id for get stability test flag (52) + IS_USER_A_STABILITY_TEST, + + // ipc id for set mission label (53) + SET_MISSION_LABEL, + // ipc id 1001-2000 for DMS // ipc id for starting ability (1001) START_ABILITY = 1001, @@ -756,6 +877,8 @@ public: GET_PENDING_WANT_SENDER_INFO, SET_SHOW_ON_LOCK_SCREEN, + SEND_APP_NOT_RESPONSE_PROCESS_ID, + // ipc id for starting ability by settings(1018) START_ABILITY_FOR_SETTINGS, @@ -763,10 +886,21 @@ public: GET_SYSTEM_MEMORY_ATTR, + GET_ABILITY_RUNNING_INFO, + + GET_EXTENSION_RUNNING_INFO, + + GET_PROCESS_RUNNING_INFO, + CLEAR_UP_APPLICATION_DATA, START_ABILITY_FOR_OPTIONS, + // ipc id for call ability + START_CALL_ABILITY, + + RELEASE_CALL_ABILITY, + // ipc id for continue ability(1101) START_CONTINUATION = 1101, @@ -783,10 +917,20 @@ public: UNREGISTER_REMOTE_MISSION_LISTENER = 1111, START_SYNC_MISSIONS = 1112, STOP_SYNC_MISSIONS = 1113, + REGISTER_SNAPSHOT_HANDLER = 1114, + GET_MISSION_SNAPSHOT_INFO = 1115, + + // ipc id for user test(1120) + START_USER_TEST = 1120, + FINISH_USER_TEST = 1121, + DELEGATOR_DO_ABILITY_FOREGROUND = 1122, + DELEGATOR_DO_ABILITY_BACKGROUND = 1123, + GET_CURRENT_TOP_ABILITY = 1124, // ipc id 2001-3000 for tools // ipc id for dumping state (2001) DUMP_STATE = 2001, + DUMPSYS_STATE = 2002, }; }; } // namespace AAFwk diff --git a/interfaces/innerkits/ability_manager/include/ability_running_info.h b/interfaces/innerkits/ability_manager/include/ability_running_info.h new file mode 100644 index 0000000000000000000000000000000000000000..1e4de26867a1f4790c1f99103a7e41d5c1d9e892 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/ability_running_info.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_INTERFACES_INNERKITS_RUNNING_ABILITY_INFO_H +#define OHOS_AAFWK_INTERFACES_INNERKITS_RUNNING_ABILITY_INFO_H + +#include "parcel.h" +#include "ability_info.h" +#include "element_name.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AAFwk { +/** + * @struct AbilityRunningInfo + * AbilityRunningInfo is used to save informations about running ability. + */ +struct AbilityRunningInfo : public Parcelable { +public: + AppExecFwk::ElementName ability; + int pid; + int uid; + std::string processName; + int64_t startTime; + int abilityState; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static AbilityRunningInfo *Unmarshalling(Parcel &parcel); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_INTERFACES_INNERKITS_RUNNING_ABILITY_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h index d66d7020974c25b676e139ce4b8ebb7f6af439bc..42db89b98546233e1ad4184f4b98510930be77cb 100644 --- a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h @@ -16,7 +16,7 @@ #ifndef OHOS_AAFWK_ABILITY_SCHEDULER_INTERFACE_H #define OHOS_AAFWK_ABILITY_SCHEDULER_INTERFACE_H -#include "foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/configuration.h" +#include "foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr/configuration.h" #include #include "lifecycle_state_info.h" #include "pac_map.h" @@ -274,6 +274,11 @@ public: const std::vector> &operations) = 0; virtual void ContinueAbility(const std::string& deviceId) = 0; virtual void NotifyContinuationResult(const int32_t result) = 0; + + virtual void DumpAbilityInfo(std::vector& info) = 0; + + virtual sptr CallRequest() = 0; + enum { // ipc id for scheduling ability to a state of life cycle SCHEDULE_ABILITY_TRANSACTION = 0, @@ -328,13 +333,13 @@ public: // ipc id for dataAbilityObServer Reguster SCHEDULE_REGISTEROBSERVER, - + // ipc id for dataAbilityObServer UnReguster SCHEDULE_UNREGISTEROBSERVER, - - // ipc id for dataAbilityObServer change + + // ipc id for dataAbilityObServer change SCHEDULE_NOTIFYCHANGE, - + // ipc id for scheduling multi window changed MULTI_WIN_CHANGED, @@ -348,15 +353,21 @@ public: // ipc id for scheduling DenormalizeUri SCHEDULE_DENORMALIZEURI, - - // ipc id for scheduling ExecuteBatch + + // ipc id for scheduling ExecuteBatch SCHEDULE_EXECUTEBATCH, // ipc id for notify continuation result NOTIFY_CONTINUATION_RESULT, + + // ipc id for scheduling call request + REQUEST_CALL_REMOTE, // ipc id for continue ability CONTINUE_ABILITY, + + // ipc id for dump ability runner + DUMP_ABILITY_RUNNER_INNER }; }; } // namespace AAFwk diff --git a/interfaces/innerkits/ability_manager/include/extension_running_info.h b/interfaces/innerkits/ability_manager/include/extension_running_info.h new file mode 100644 index 0000000000000000000000000000000000000000..209187ea47c6ba9a258d360beb276ac0ef566af4 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/extension_running_info.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_INTERFACES_INNERKITS_EXTENSION_RUNNING_INFO_H +#define OHOS_AAFWK_INTERFACES_INNERKITS_EXTENSION_RUNNING_INFO_H + +#include "parcel.h" +#include "element_name.h" +#include "iremote_object.h" +#include "extension_ability_info.h" + +namespace OHOS { +namespace AAFwk { +/** + * @struct ExtensionRunningInfo + * ExtensionRunningInfo is used to save informations about extension. + */ +struct ExtensionRunningInfo : public Parcelable { +public: + AppExecFwk::ElementName extension; + int pid; + int uid; + AppExecFwk::ExtensionAbilityType type = AppExecFwk::ExtensionAbilityType::UNSPECIFIED; + std::string processName; + int64_t startTime; + std::vector clientPackage; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ExtensionRunningInfo *Unmarshalling(Parcel &parcel); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_INTERFACES_INNERKITS_EXTENSION_RUNNING_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/include/mission_info.h b/interfaces/innerkits/ability_manager/include/mission_info.h index 7f1a4b7bc7aadfb569661964e72498c4184ccee2..7d1f16a8102a575def8455849128b8c4af73152a 100644 --- a/interfaces/innerkits/ability_manager/include/mission_info.h +++ b/interfaces/innerkits/ability_manager/include/mission_info.h @@ -35,6 +35,7 @@ struct MissionInfo : public Parcelable { int32_t id = -1; int32_t runningState = -1; bool lockedState; + bool continuable = false; std::string time; std::string label; std::string iconPath; diff --git a/interfaces/innerkits/ability_manager/include/mission_snapshot.h b/interfaces/innerkits/ability_manager/include/mission_snapshot.h index ed1b0dd209a0ac37b8f6cbad71d35774a5efd914..ca1fdcbdf7a79b9252298d2e6f7e0d82fbba2f9f 100644 --- a/interfaces/innerkits/ability_manager/include/mission_snapshot.h +++ b/interfaces/innerkits/ability_manager/include/mission_snapshot.h @@ -37,9 +37,13 @@ struct MissionPixelMap : public Parcelable { static MissionPixelMap *Unmarshalling(Parcel &parcel); }; -struct MissionSnapshot { +struct MissionSnapshot : public Parcelable { AppExecFwk::ElementName topAbility; std::shared_ptr snapshot; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static MissionSnapshot *Unmarshalling(Parcel &parcel); }; } // namespace AAFwk diff --git a/interfaces/innerkits/ability_manager/include/snapshot.h b/interfaces/innerkits/ability_manager/include/snapshot.h new file mode 100644 index 0000000000000000000000000000000000000000..9236a4e8cb21232015e656cb759b070458b6c1d3 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/snapshot.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_SNAPSHOT_H +#define OHOS_AAFWK_SNAPSHOT_H + +#include + +namespace OHOS { +namespace Media { +class PixelMap; +} +namespace AAFwk { +/** + * @class Snapshot + * Snapshot info + */ +class Snapshot { +public: + Snapshot() = default; + ~Snapshot() = default; + const std::shared_ptr& GetPixelMap() const + { + return pixelMap_; + } + void SetPixelMap(const std::shared_ptr& pixelMap) + { + pixelMap_ = pixelMap; + } +private: + std::shared_ptr pixelMap_ = nullptr; +}; + +/** + * @class ISnapshotHandler + * Snapshot handler, use to get snapshot + */ +class ISnapshotHandler : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.SnapshotHandler"); + + enum { + TRANS_ID_GET_SNAPSHOT + }; + + /** + * @brief Get the Snapshot object + * @param token remote object token + * @param snapshot the application snapshot + * @return int32_t function result + */ + virtual int32_t GetSnapshot(const sptr& token, Snapshot& snapshot) = 0; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_SNAPSHOT_H \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/include/start_options.h b/interfaces/innerkits/ability_manager/include/start_options.h index 4c5ebdbbffd9358e5a5bbf2c36adb25bea0b2b3d..82fe7cd47f70d11565949bff267bab297c8fa8a7 100644 --- a/interfaces/innerkits/ability_manager/include/start_options.h +++ b/interfaces/innerkits/ability_manager/include/start_options.h @@ -20,12 +20,12 @@ #include "ability_window_configuration.h" #include "parcel.h" - namespace OHOS { namespace AAFwk { class StartOptions : public Parcelable { public: - static const std::string STRING_WINDOW_MODE; + static const std::string STRING_DISPLAY_ID; + const int32_t DEFAULT_DISPLAY_ID {0}; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; @@ -33,8 +33,12 @@ public: void SetWindowMode(int32_t windowMode); int32_t GetWindowMode() const; + + void SetDisplayID(int32_t displayId); + int32_t GetDisplayID() const; private: int32_t windowMode_ = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED; + int32_t displayId_ = DEFAULT_DISPLAY_ID; }; } // namespace AAFwk } // namespace OHOS diff --git a/tools/zip/BUILD.gn b/interfaces/innerkits/app_manager/BUILD.gn similarity index 30% rename from tools/zip/BUILD.gn rename to interfaces/innerkits/app_manager/BUILD.gn index 77de9bf92c5f15c9371a23ff908197fa5580a79c..dddfd5bf055dfb93990434579c9876873098fc04 100644 --- a/tools/zip/BUILD.gn +++ b/interfaces/innerkits/app_manager/BUILD.gn @@ -11,90 +11,89 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/test.gni") +import("//build/ohos.gni") import("//foundation/aafwk/standard/aafwk.gni") -TASK_DIR = "//foundation/appexecfwk/standard" -LOG_DIR = "//foundation/aafwk/standard" -NAPI_DIR2 = - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common" -ACE_DIR = "//foundation/ace/napi/interfaces/kits" -PACMAP_DIR = "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content" -ABILITY_DIR = - "//foundation/aafwk/standard/frameworks/kits/ability/native/include" -IREMOTE_DIR = - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include" -BUNDLE_MGR_DIR = - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include" -BUNDLE_MGR_DIR2 = "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr" -APP_DIR = "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr" -RESMGR_DIR = "//base/global/resmgr_standard/interfaces/innerkits/include" -config("zip_config") { +config("appmgr_sdk_config") { include_dirs = [ - "include", - "$NAPI_DIR2", - "$ACE_DIR", - "$ABILITY_DIR", - "$PACMAP_DIR", - "$IREMOTE_DIR", - "$BUNDLE_MGR_DIR", - "$BUNDLE_MGR_DIR2", - "$APP_DIR", - "$RESMGR_DIR", - "//third_party/zlib", - "//utils/native/base/include", - "$LOG_DIR/services/common/include", - "$TASK_DIR/common/log/include", - "$TASK_DIR/interfaces/innerkits/appexecfwk_base/include", - "$TASK_DIR/interfaces/innerkits/libeventhandler/include", - "$TASK_DIR/interfaces/innerkits/task_dispatcher/include/dispatcher", - "$TASK_DIR/interfaces/innerkits/task_dispatcher/include/task", - "$TASK_DIR/interfaces/innerkits/task_dispatcher/include/threading", - "$TASK_DIR/kits/appkit/native/app/include/task", - "$TASK_DIR/kits/appkit/native/app/include", - "//third_party/libuv/include", - "//third_party/node/src", - "//third_party/icu/icu4c/source/common/unicode", + "include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", ] } -ohos_shared_library("zlib") { - public_configs = [ ":zip_config" ] +config("appexecfwk_core_config") { + include_dirs = [ "include" ] +} + +ohos_shared_library("app_manager") { + include_dirs = [ + "//third_party/json/include", + "${aafwk_path}/services/appmgr/include", + "//utils/system/safwk/native/include", + ] sources = [ - "kits/napi/napi_zlib.cpp", - "kits/napi/napi_zlib_common.cpp", - "kits/napi/native_module.cpp", - "src/file_path.cpp", - "src/zip.cpp", - "src/zip_internal.cpp", - "src/zip_reader.cpp", - "src/zip_utils.cpp", - "src/zip_writer.cpp", + "src/appmgr/ability_controller_proxy.cpp", + "src/appmgr/ability_controller_stub.cpp", + "src/appmgr/ability_state_data.cpp", + "src/appmgr/ams_mgr_proxy.cpp", + "src/appmgr/ams_mgr_stub.cpp", + "src/appmgr/app_launch_data.cpp", + "src/appmgr/app_mgr_client.cpp", + "src/appmgr/app_mgr_proxy.cpp", + "src/appmgr/app_mgr_stub.cpp", + "src/appmgr/app_process_data.cpp", + "src/appmgr/app_record_id.cpp", + "src/appmgr/app_scheduler_host.cpp", + "src/appmgr/app_scheduler_proxy.cpp", + "src/appmgr/app_service_manager.cpp", + "src/appmgr/app_state_callback_host.cpp", + "src/appmgr/app_state_callback_proxy.cpp", + "src/appmgr/app_state_data.cpp", + "src/appmgr/app_task_info.cpp", + "src/appmgr/application_state_observer_proxy.cpp", + "src/appmgr/application_state_observer_stub.cpp", + "src/appmgr/configuration.cpp", + "src/appmgr/priority_object.cpp", + "src/appmgr/process_data.cpp", + "src/appmgr/process_info.cpp", + "src/appmgr/profile.cpp", + "src/appmgr/start_specified_ability_response_proxy.cpp", + "src/appmgr/start_specified_ability_response_stub.cpp", + ] + + public_configs = [ + ":appexecfwk_core_config", + ":appmgr_sdk_config", ] + defines = [ + "APP_LOG_TAG = \"AppexecfwkCore\"", + "LOG_DOMAIN = 0xD001100", + ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", - "//third_party/libuv:uv_static", - "//third_party/zlib:libz", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//utils/native/base:utils", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "bytrace_standard:bytrace_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] - install_enable = true subsystem_name = "aafwk" - part_name = "aafwk_standard" - relative_install_dir = "module" -} - -group("tools_zip") { - deps = [ ":zlib" ] + part_name = "ability_runtime" } diff --git a/interfaces/innerkits/app_manager/include/appmgr/ability_controller_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..271d130f6440ca4c2c11c0c6a9309ec923e382ec --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_proxy.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_CONTROLLER_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_CONTROLLER_PROXY_H + +#include "iremote_proxy.h" +#include "iability_controller.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Testing interface to monitor what is happening in ability manager while tests are running. + */ +class AbilityControllerProxy : public IRemoteProxy { +public: + explicit AbilityControllerProxy(const sptr &impl); + virtual ~AbilityControllerProxy() = default; + + /** + * The system is trying to start an ability. + * + * @param want The want of ability to start. + * @param bundleName The bundleName of ability to start. + * @return Return true to allow ability to start, or false to reject. + */ + virtual bool AllowAbilityStart(const Want &want, const std::string &bundleName) override; + + /** + * The system is scheduling Ability to the foreground. + * + * @param bundleName The bundleName of ability to return. + * @return Return true to allow ability to foreground, or false to reject. + */ + virtual bool AllowAbilityForeground(const std::string &bundleName) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/ability_controller_stub.h b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..f4abe003c311eeb2ac42d0d87560af73ec06751d --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_stub.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_CONTROLLER_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_CONTROLLER_STUB_H + +#include + +#include "iremote_stub.h" +#include "iability_controller.h" +#include "nocopyable.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Testing interface to monitor what is happening in ability manager while tests are running. + */ +class AbilityControllerStub : public IRemoteStub { +public: + AbilityControllerStub(); + virtual ~AbilityControllerStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + /** + * The system is trying to start an ability. + * + * @param want The want of ability to start. + * @param bundleName The bundleName of ability to start. + * @return Return true to allow ability to start, or false to reject. + */ + virtual bool AllowAbilityStart(const Want &want, const std::string &bundleName) override; + + /** + * The system is scheduling Ability to the foreground. + * + * @param bundleName The bundleName of ability to return. + * @return Return true to allow ability to foreground, or false to reject. + */ + virtual bool AllowAbilityForeground(const std::string &bundleName) override; + +private: + int32_t HandleAllowAbilityStart(MessageParcel &data, MessageParcel &reply); + + int32_t HandleAllowAbilityForeground(MessageParcel &data, MessageParcel &reply); + + using AbilityControllerFunc = int32_t (AbilityControllerStub::*)(MessageParcel &data, + MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(AbilityControllerStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_CONTROLLER_STUB_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/ability_state_data.h b/interfaces/innerkits/app_manager/include/appmgr/ability_state_data.h new file mode 100644 index 0000000000000000000000000000000000000000..742d8b09a70fbde28d4971da0074144bb777e731 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/ability_state_data.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_STATE_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_STATE_DATA_H + +#include + +#include "parcel.h" + +#include "app_mgr_constants.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +struct AbilityStateData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AbilityStateData *Unmarshalling(Parcel &parcel); + + std::string bundleName; + std::string abilityName; + int32_t abilityState = 0; + pid_t pid = 0; + int32_t uid = 0; + sptr token; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_ABILITY_STATE_DATA_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_interface.h b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..a61aefdfe538e91c328c26f93ea5cddff282e78b --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_interface.h @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_INTERFACE_H + +#include "iremote_broker.h" +#include "iremote_object.h" + +#include "ability_info.h" +#include "application_info.h" +#include "app_record_id.h" +#include "iapp_state_callback.h" +#include "running_process_info.h" +#include "istart_specified_ability_response.h" +#include "configuration.h" + +namespace OHOS { +namespace AppExecFwk { +class IAmsMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IAmsMgr"); + + /** + * LoadAbility, call LoadAbility() through proxy project, load the ability that needed to be started. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param abilityInfo, the ability information. + * @param appInfo, the app information. + * @return + */ + virtual void LoadAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) = 0; + + /** + * TerminateAbility, call TerminateAbility() through the proxy object, terminate the token ability. + * + * @param token, token, he unique identification to terminate the ability. + * @return + */ + virtual void TerminateAbility(const sptr &token) = 0; + + /** + * UpdateAbilityState, call UpdateAbilityState() through the proxy object, update the ability status. + * + * @param token, the unique identification to update the ability. + * @param state, ability status that needs to be updated. + * @return + */ + virtual void UpdateAbilityState(const sptr &token, const AbilityState state) = 0; + + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) = 0; + + /** + * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. + * + * @param callback, Ams register the callback. + * @return + */ + virtual void RegisterAppStateCallback(const sptr &callback) = 0; + + /** + * Reset,call Reset() through the proxy object, reset DFX of AppMgr. + * + * @return + */ + virtual void Reset() = 0; + + /** + * AbilityBehaviorAnalysis,call AbilityBehaviorAnalysis() through the proxy object, + * ability behavior analysis assistant process optimization. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param visibility, the visibility information about windows info. + * @param perceptibility, the Perceptibility information about windows info. + * @param connectionState, the service ability connection state. + * @return + */ + virtual void AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) = 0; + + /** + * KillProcessByAbilityToken, call KillProcessByAbilityToken() through proxy object, + * kill the process by ability token. + * + * @param token, the unique identification to the ability. + * @return + */ + virtual void KillProcessByAbilityToken(const sptr &token) = 0; + + /** + * KillProcessesByUserId, call KillProcessesByUserId() through proxy object, + * kill the processes by userId. + * + * @param userId, the user id. + * @return + */ + virtual void KillProcessesByUserId(int32_t userId) = 0; + + /** + * KillProcessWithAccount, call KillProcessWithAccount() through proxy object, + * kill the process. + * + * @param bundleName, bundle name in Application record. + * @param accountId, account ID. + * @return ERR_OK, return back success, others fail. + */ + virtual int KillProcessWithAccount(const std::string &bundleName, const int accountId) = 0; + + /** + * KillApplication, call KillApplication() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int KillApplication(const std::string &bundleName) = 0; + + /** + * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @param userId, userId. + * @return ERR_OK, return back success, others fail. + */ + virtual int KillApplicationByUid(const std::string &bundleName, const int uid) = 0; + + virtual void AbilityAttachTimeOut(const sptr &token) = 0; + + virtual void PrepareTerminate(const sptr &token) = 0; + + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) = 0; + + virtual void GetRunningProcessInfoByToken( + const sptr &token, OHOS::AppExecFwk::RunningProcessInfo &info) = 0; + + virtual void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) = 0; + + virtual void RegisterStartSpecifiedAbilityResponse(const sptr &response) = 0; + + /** + * ANotify application update system environment changes. + * + * @param config System environment change parameters. + * @return Returns ERR_OK on success, others on failure. + */ + virtual void UpdateConfiguration(const Configuration &config) = 0; + + virtual int GetConfiguration(Configuration &config) = 0; + + enum class Message { + LOAD_ABILITY = 0, + TERMINATE_ABILITY, + UPDATE_ABILITY_STATE, + UPDATE_EXTENSION_STATE, + REGISTER_APP_STATE_CALLBACK, + RESET, + ABILITY_BEHAVIOR_ANALYSIS, + KILL_PEOCESS_BY_ABILITY_TOKEN, + KILL_PROCESSES_BY_USERID, + KILL_PROCESS_WITH_ACCOUNT, + KILL_APPLICATION, + ABILITY_ATTACH_TIMEOUT, + COMPEL_VERIFY_PERMISSION, + PREPARE_TERMINATE_ABILITY, + KILL_APPLICATION_BYUID, + GET_RUNNING_PROCESS_INFO_BY_TOKEN, + START_SPECIFIED_ABILITY, + REGISTER_START_SPECIFIED_ABILITY_RESPONSE, + UPDATE_CONFIGURATION, + GET_CONFIGURATION, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_INTERFACE_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..8a58e6ef9f5d5179b3b37fed8e10ef7ffd1d2c44 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_proxy.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_CLIENT_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_CLIENT_H + +#include "iremote_proxy.h" + +#include "ams_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsMgrProxy : public IRemoteProxy { +public: + explicit AmsMgrProxy(const sptr &impl); + virtual ~AmsMgrProxy() = default; + + /** + * LoadAbility, call LoadAbility() through proxy project, load the ability that needed to be started. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param abilityInfo, the ability information. + * @param appInfo, the app information. + * @return + */ + virtual void LoadAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) override; + + /** + * TerminateAbility, call TerminateAbility() through the proxy object, terminate the token ability. + * + * @param token, token, he unique identification to terminate the ability. + * @return + */ + virtual void TerminateAbility(const sptr &token) override; + + /** + * UpdateAbilityState, call UpdateAbilityState() through the proxy object, update the ability status. + * + * @param token, the unique identification to update the ability. + * @param state, ability status that needs to be updated. + * @return + */ + virtual void UpdateAbilityState(const sptr &token, const AbilityState state) override; + + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) override; + + /** + * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. + * + * @param callback, Ams register the callback. + * @return + */ + virtual void RegisterAppStateCallback(const sptr &callback) override; + + /** + * Reset,call Reset() through the proxy object, reset DFX of AppMgr. + * + * @return + */ + virtual void Reset() override; + + /** + * AbilityBehaviorAnalysis,call AbilityBehaviorAnalysis() through the proxy object, + * ability behavior analysis assistant process optimization. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param visibility, the visibility information about windows info. + * @param perceptibility, the Perceptibility information about windows info. + * @param connectionState, the service ability connection state. + * @return + */ + virtual void AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) override; + + /** + * KillProcessByAbilityToken, call KillProcessByAbilityToken() through proxy object, + * kill the process by ability token. + * + * @param token, the unique identification to the ability. + * @return + */ + virtual void KillProcessByAbilityToken(const sptr &token) override; + + /** + * KillProcessesByUserId, call KillProcessesByUserId() through proxy object, + * kill the processes by userId. + * + * @param userId, the user id. + * @return + */ + virtual void KillProcessesByUserId(int32_t userId) override; + + /** + * KillProcessWithAccount, call KillProcessWithAccount() through proxy object, + * kill the process. + * + * @param bundleName, bundle name in Application record. + * @param accountId, account ID. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillProcessWithAccount(const std::string &bundleName, const int accountId) override; + + /** + * KillApplication, call KillApplication() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillApplication(const std::string &bundleName) override; + + /** + * KillApplication, call KillApplication() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @param uid, uid. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillApplicationByUid(const std::string &bundleName, const int uid) override; + + virtual void AbilityAttachTimeOut(const sptr &token) override; + + virtual void PrepareTerminate(const sptr &token) override; + + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override; + + void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) override; + + virtual void StartSpecifiedAbility( + const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) override; + + /** + * ANotify application update system environment changes. + * + * @param config System environment change parameters. + * @return Returns ERR_OK on success, others on failure. + */ + virtual void UpdateConfiguration(const Configuration &config) override; + + virtual void RegisterStartSpecifiedAbilityResponse(const sptr &response) override; + + virtual int GetConfiguration(Configuration &config) override; +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_CLIENT_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_stub.h b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..982f5a5a86e8fef4cfa2eeb2924217a87381b114 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_stub.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_STUB_H + +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" +#include "ams_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsMgrStub : public IRemoteStub { +public: + AmsMgrStub(); + virtual ~AmsMgrStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) override; +private: + int32_t HandleLoadAbility(MessageParcel &data, MessageParcel &reply); + int32_t HandleTerminateAbility(MessageParcel &data, MessageParcel &reply); + int32_t HandleUpdateAbilityState(MessageParcel &data, MessageParcel &reply); + int32_t HandleUpdateExtensionState(MessageParcel &data, MessageParcel &reply); + int32_t HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply); + int32_t HandleReset(MessageParcel &data, MessageParcel &reply); + int32_t HandleAbilityBehaviorAnalysis(MessageParcel &data, MessageParcel &reply); + int32_t HandleKillProcessByAbilityToken(MessageParcel &data, MessageParcel &reply); + int32_t HandleKillProcessesByUserId(MessageParcel &data, MessageParcel &reply); + int32_t HandleKillProcessWithAccount(MessageParcel &data, MessageParcel &reply); + int32_t HandleKillApplication(MessageParcel &data, MessageParcel &reply); + int32_t HandleAbilityAttachTimeOut(MessageParcel &data, MessageParcel &reply); + int32_t HandleCompelVerifyPermission(MessageParcel &data, MessageParcel &reply); + int32_t HandlePrepareTerminate(MessageParcel &data, MessageParcel &reply); + int32_t HandleKillApplicationByUid(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetRunningProcessInfoByToken(MessageParcel &data, MessageParcel &reply); + int32_t HandleStartSpecifiedAbility(MessageParcel &data, MessageParcel &reply); + int32_t HandleRegisterStartSpecifiedAbilityResponse(MessageParcel &data, MessageParcel &reply); + int32_t HandleUpdateConfiguration(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetConfiguration(MessageParcel &data, MessageParcel &reply); + + using AmsMgrFunc = int32_t (AmsMgrStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(AmsMgrStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_STUB_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_launch_data.h b/interfaces/innerkits/app_manager/include/appmgr/app_launch_data.h new file mode 100644 index 0000000000000000000000000000000000000000..6b8a6da77c52482fc511e8e451c68cba4bfcf5eb --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_launch_data.h @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_APPMGR_INCLUDE_APP_LAUNCH_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_APPMGR_INCLUDE_APP_LAUNCH_DATA_H + +#include + +#include "iremote_object.h" +#include "parcel.h" + +#include "application_info.h" +#include "process_info.h" +#include "profile.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +struct UserTestRecord : public Parcelable { + AAFwk::Want want; + sptr observer; + UserTestRecord() : observer(nullptr) + {} + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static UserTestRecord *Unmarshalling(Parcel &parcel); +}; + +class AppLaunchData : public Parcelable { +public: + /** + * @brief setting information for the application. + * + * @param ApplicationInfo&, the current application info. + */ + void SetApplicationInfo(const ApplicationInfo &); + + /** + * @brief Setting information for the profile. + * + * @param Profile&, the current profile. + */ + void SetProfile(const Profile &); + + /** + * @brief Setting information for the process. + * + * @param Profile&, the current process info. + */ + void SetProcessInfo(const ProcessInfo &); + + /** + * @brief Setting id for app record. + * + * @param int32_t, the current app record id. + */ + void SetRecordId(const int32_t); + + /** + * @brief Setting id for User. + * + * @param int32_t, the current app User. + */ + void SetUId(const int32_t); + + /** + * @brief set user test info. + * + * @param UserTestRecord, user test info. + */ + void SetUserTestInfo(const UserTestRecord &record); + + /** + * @brief Obtains the info of the application. + * + * @return Returns the current application info. + */ + inline const ApplicationInfo &GetApplicationInfo() const + { + return applicationInfo_; + } + + /** + * @brief Obtains the profile. + * + * @return Returns the current profile. + */ + inline const Profile &GetProfile() const + { + return profile_; + } + + /** + * @brief Obtains the info of the process. + * + * @return Returns the current process info. + */ + inline const ProcessInfo &GetProcessInfo() const + { + return processInfo_; + } + + /** + * @brief Obtains the id of the app record. + * + * @return Returns the current appRecord id. + */ + inline int32_t GetRecordId() const + { + return recordId_; + } + + /** + * @brief Obtains the id of the User. + * + * @return Returns the current User id. + */ + inline int32_t GetUId() const + { + return uId_; + } + + /** + * @brief get user test info. + * + * @return Returns user test info. + */ + inline const UserTestRecord &GetUserTestInfo() const + { + return userTestRecord_; + } + + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AppLaunchData *Unmarshalling(Parcel &parcel); + +private: + ApplicationInfo applicationInfo_; + Profile profile_; + ProcessInfo processInfo_; + int32_t recordId_ = 0; + int32_t uId_ = 0; + UserTestRecord userTestRecord_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_APPMGR_INCLUDE_APP_LAUNCH_DATA_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_client.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_client.h new file mode 100644 index 0000000000000000000000000000000000000000..3ef4eb1799d26043eb0bb05361ace8bd3543f4d8 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_client.h @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_MGR_CLIENT_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_MGR_CLIENT_H + +#include "iremote_object.h" +#include "refbase.h" +#include "want.h" + +#include "ability_info.h" +#include "application_info.h" +#include "app_mgr_constants.h" +#include "bundle_info.h" +#include "iapp_state_callback.h" +#include "running_process_info.h" +#include "system_memory_attr.h" +#include "istart_specified_ability_response.h" + +namespace OHOS { +namespace AppExecFwk { +class AppServiceManager; +class Configuration; +class AppMgrClient { +public: + AppMgrClient(); + virtual ~AppMgrClient(); + + /** + * Load ability. + * + * @param token, Ability identify. + * @param abilityInfo, Ability information. + * @param appInfo, Application information. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode LoadAbility(const sptr &token, const sptr &preToken, + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo); + + /** + * Terminate ability. + * + * @param token Ability identify. + * + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode TerminateAbility(const sptr &token); + + /** + * Update ability state. + * + * @param token Ability identify. + * @param state Ability running state. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode UpdateAbilityState(const sptr &token, const AbilityState state); + + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual AppMgrResultCode UpdateExtensionState(const sptr &token, const ExtensionState state); + + /** + * Register Application state callback. + * + * @param callback IAppStateCallback + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode RegisterAppStateCallback(const sptr &callback); + + /** + * Connect service. + * + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode ConnectAppMgrService(); + + /** + * Ability manager resst. + * + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode Reset(); + + /** + * AbilityBehaviorAnalysis, ability behavior analysis assistant process optimization. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param visibility, the visibility information about windows info. + * @param perceptibility, the Perceptibility information about windows info. + * @param connectionState, the service ability connection state. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode AbilityBehaviorAnalysis(const sptr &token, + const sptr &preToken, const int32_t visibility, const int32_t perceptibility, + const int32_t connectionState); + + /** + * KillProcessByAbilityToken, call KillProcessByAbilityToken() through proxy object, + * kill the process by ability token. + * + * @param token, the unique identification to the ability. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode KillProcessByAbilityToken(const sptr &token); + + /** + * KillProcessesByUserId, call KillProcessesByUserId() through proxy object, + * kill the processes by user id. + * + * @param userId, the user id. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode KillProcessesByUserId(int32_t userId); + + /** + * KillApplication, call KillApplication() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual AppMgrResultCode KillApplication(const std::string &bundleName); + + /** + * KillApplication, call KillApplication() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @param uid, uid. + * @return ERR_OK, return back success, others fail. + */ + virtual AppMgrResultCode KillApplicationByUid(const std::string &bundleName, const int uid); + + /** + * ClearUpApplicationData, call ClearUpApplicationData() through proxy project, + * clear the application data. + * + * @param bundleName, bundle name in Application record. + * @return + */ + virtual AppMgrResultCode ClearUpApplicationData(const std::string &bundleName); + + /** + * GetAllRunningProcesses, call GetAllRunningProcesses() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual AppMgrResultCode GetAllRunningProcesses(std::vector &info); + + /** + * GetProcessRunningInfosByUserId, call GetProcessRunningInfosByUserId() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @param userId, user Id in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual AppMgrResultCode GetProcessRunningInfosByUserId(std::vector &info, int32_t userId); + + /** + * GetConfiguration + * + * @param info, configuration. + * @return ERR_OK ,return back success,others fail. + */ + virtual AppMgrResultCode GetConfiguration(Configuration& config); + + /** + * SetAppSuspendTimes, Setting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual AppMgrResultCode SetAppFreezingTime(int time); + + /** + * GetAppFreezingTime, Getting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual AppMgrResultCode GetAppFreezingTime(int &time); + virtual void AbilityAttachTimeOut(const sptr &token); + + virtual void PrepareTerminate(const sptr &token); + + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message); + + /** + * Get system memory information. + * @param SystemMemoryAttr, memory information. + * @param strConfig, params string. + */ + virtual void GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig); + + virtual void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info); + /** + * Notify that the ability stage has been updated + * @param recordId, the app record. + */ + virtual void AddAbilityStageDone(const int32_t recordId); + + /** + * Start a resident process + */ + virtual void StartupResidentProcess(); + + /** + * ANotify application update system environment changes. + * + * @param config System environment change parameters. + * @return Returns ERR_OK on success, others on failure. + */ + virtual AppMgrResultCode UpdateConfiguration(const Configuration &config); + + /** + * Start a user test + */ + virtual int StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &bundleInfo); + + virtual void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + + virtual void RegisterStartSpecifiedAbilityResponse(const sptr &response); + + virtual void ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag); + +private: + void SetServiceManager(std::unique_ptr serviceMgr); + +private: + std::unique_ptr serviceManager_; + sptr remote_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_MGR_CLIENT_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_constants.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..4fa3265930be53f11691574f7fc1ebbeac15efa4 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_constants.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CONSTANTS_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CONSTANTS_H + +namespace OHOS { +namespace AppExecFwk { +namespace Constants { +const std::string APP_MGR_SERVICE_NAME = "AppMgrService"; +} // namespace Constants + +enum class ApplicationState { + APP_STATE_BEGIN = 0, + APP_STATE_CREATE = APP_STATE_BEGIN, + APP_STATE_READY, + APP_STATE_FOREGROUND, + APP_STATE_BACKGROUND, + APP_STATE_SUSPENDED, + APP_STATE_TERMINATED, + APP_STATE_END, +}; + +enum class AbilityState { + ABILITY_STATE_BEGIN = 0, + ABILITY_STATE_CREATE = ABILITY_STATE_BEGIN, + ABILITY_STATE_READY, + ABILITY_STATE_FOREGROUND, + ABILITY_STATE_BACKGROUND, + ABILITY_STATE_TERMINATED, + ABILITY_STATE_END, +}; + +enum class ExtensionState { + EXTENSION_STATE_CREATE = 0, + EXTENSION_STATE_READY, + EXTENSION_STATE_CONNECTED, + EXTENSION_STATE_DISCONNECTED, + EXTENSION_STATE_TERMINATED, +}; + +enum AppMgrResultCode { + RESULT_OK = 0, + ERROR_SERVICE_NOT_READY, + ERROR_SERVICE_NOT_CONNECTED, +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CONSTANTS_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_interface.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..0ac19509e2ee0078bce27f4366eb15cbb2d29bea --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_interface.h @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_INTERFACE_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "want.h" + +#include "ability_info.h" +#include "application_info.h" +#include "app_record_id.h" +#include "bundle_info.h" +#include "iapp_state_callback.h" +#include "ams_mgr_interface.h" +#include "running_process_info.h" +#include "system_memory_attr.h" +#include "iapplication_state_observer.h" + +namespace OHOS { +namespace AppExecFwk { +class IAppMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AppMgr"); + + /** + * AttachApplication, call AttachApplication() through proxy object, + * get all the information needed to start the Application (data related to the Application ). + * + * @param app, information needed to start the Application. + * @return + */ + virtual void AttachApplication(const sptr &app) = 0; + + /** + * ApplicationForegrounded, call ApplicationForegrounded() through proxy object, + * set the application to Foreground State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationForegrounded(const int32_t recordId) = 0; + + /** + * ApplicationBackgrounded, call ApplicationBackgrounded() through proxy object, + * set the application to Backgrounded State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationBackgrounded(const int32_t recordId) = 0; + + /** + * ApplicationTerminated, call ApplicationTerminated() through proxy object, + * terminate the application. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationTerminated(const int32_t recordId) = 0; + + /** + * CheckPermission, call CheckPermission() through proxy object, check the permission. + * + * @param recordId, a unique record that identifies this Application from others. + * @param permission, check the permissions. + * @return ERR_OK, return back success, others fail. + */ + virtual int CheckPermission(const int32_t recordId, const std::string &permission) = 0; + + /** + * AbilityCleaned,call through AbilityCleaned() proxy project, clean Ability record. + * + * @param token, a unique record that identifies AbilityCleaned from others. + * @return + */ + virtual void AbilityCleaned(const sptr &token) = 0; + + /** + * GetAmsMgr, call GetAmsMgr() through proxy object, get AMS interface instance. + * + * @return sptr, return to AMS interface instance. + */ + virtual sptr GetAmsMgr() = 0; + + /** + * ClearUpApplicationData, call ClearUpApplicationData() through proxy project, + * clear the application data. + * + * @param bundleName, bundle name in Application record. + * @return + */ + virtual int32_t ClearUpApplicationData(const std::string &bundleName) = 0; + + /** + * IsBackgroundRunningRestricted, call IsBackgroundRunningRestricted() through proxy project, + * Checks whether the process of this application is forbidden to run in the background. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int IsBackgroundRunningRestricted(const std::string &bundleName) = 0; + + /** + * GetAllRunningProcesses, call GetAllRunningProcesses() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int GetAllRunningProcesses(std::vector &info) = 0; + + /** + * GetProcessRunningInfosByUserId, call GetProcessRunningInfosByUserId() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @param userId, user Id in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) = 0; + + /** + * SetAppSuspendTimes, Setting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void SetAppFreezingTime(int time) = 0; + + /** + * GetAppFreezingTime, Getting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void GetAppFreezingTime(int &time) = 0; + + /** + * Get system memory information. + * @param SystemMemoryAttr, memory information. + */ + virtual void GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig) = 0; + + /** + * Notify that the ability stage has been updated + * @param recordId, the app record. + */ + virtual void AddAbilityStageDone(const int32_t recordId) = 0; + + /** + * Start a resident process + */ + virtual void StartupResidentProcess() = 0; + + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) = 0; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) = 0; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) = 0; + + /** + * Start user test process. + * @param want, want object. + * @param observer, test observer remote object. + * @param bundleInfo, bundle info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &bundleInfo) = 0; + + virtual void ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag) = 0; + + enum class Message { + APP_ATTACH_APPLICATION = 0, + APP_APPLICATION_FOREGROUNDED, + APP_APPLICATION_BACKGROUNDED, + APP_APPLICATION_TERMINATED, + APP_CHECK_PERMISSION, + APP_ABILITY_CLEANED, + APP_GET_MGR_INSTANCE, + APP_CLEAR_UP_APPLICATION_DATA, + APP_IS_BACKGROUND_RUNNING_RESTRICTED, + APP_GET_ALL_RUNNING_PROCESSES, + APP_GET_RUNNING_PROCESSES_BY_USER_ID, + APP_SET_APP_FREEZING_TIME, + APP_GET_APP_FREEZING_TIME, + APP_GET_SYSTEM_MEMORY_ATTR, + APP_ADD_ABILITY_STAGE_INFO_DONE, + STARTUP_RESIDENT_PROCESS, + REGISTER_APPLICATION_STATE_OBSERVER, + UNREGISTER_APPLICATION_STATE_OBSERVER, + GET_FOREGROUND_APPLICATIONS, + START_USER_TEST_PROCESS, + SCHEDULE_ACCEPT_WANT_DONE, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_INTERFACE_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..d3db6663ef838318c7f6fec4535ae1e046b823ae --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_proxy.h @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CLIENT_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CLIENT_H + +#include "iremote_proxy.h" +#include "want.h" + +#include "app_mgr_interface.h" +#include "bundle_info.h" + +namespace OHOS { +namespace AppExecFwk { +class AppMgrProxy : public IRemoteProxy { +public: + explicit AppMgrProxy(const sptr &impl); + virtual ~AppMgrProxy() = default; + + /** + * AttachApplication, call AttachApplication() through proxy object, + * get all the information needed to start the Application (data related to the Application ). + * + * @param app, information needed to start the Application. + * @return + */ + virtual void AttachApplication(const sptr &obj) override; + + /** + * ApplicationForegrounded, call ApplicationForegrounded() through proxy object, + * set the application to Foreground State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationForegrounded(const int32_t recordId) override; + + /** + * ApplicationBackgrounded, call ApplicationBackgrounded() through proxy object, + * set the application to Backgrounded State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationBackgrounded(const int32_t recordId) override; + + /** + * ApplicationTerminated, call ApplicationTerminated() through proxy object, + * terminate the application. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationTerminated(const int32_t recordId) override; + + /** + * CheckPermission, call CheckPermission() through proxy object, check the permission. + * + * @param recordId, a unique record that identifies this Application from others. + * @param permission, check the permissions. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t CheckPermission(const int32_t recordId, const std::string &permission) override; + + /** + * AbilityCleaned,call through AbilityCleaned() proxy project, clean Ability record. + * + * @param token, a unique record that identifies AbilityCleaned from others. + * @return + */ + virtual void AbilityCleaned(const sptr &token) override; + + /** + * GetAmsMgr, call GetAmsMgr() through proxy object, get AMS interface instance. + * + * @return sptr, return to AMS interface instance. + */ + virtual sptr GetAmsMgr() override; + + /** + * ClearUpApplicationData, call ClearUpApplicationData() through proxy project, + * clear the application data. + * + * @param bundleName, bundle name in Application record. + * @return + */ + virtual int32_t ClearUpApplicationData(const std::string &bundleName) override; + + /** + * IsBackgroundRunningRestricted, call IsBackgroundRunningRestricted() through proxy project, + * Checks whether the process of this application is forbidden to run in the background. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t IsBackgroundRunningRestricted(const std::string &bundleName) override; + + /** + * GetAllRunningProcesses, call GetAllRunningProcesses() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetAllRunningProcesses(std::vector &info) override; + + /** + * GetProcessRunningInfosByUserId, call GetProcessRunningInfosByUserId() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) override; + + /** + * SetAppSuspendTimes, Setting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void SetAppFreezingTime(int time) override; + + /** + * GetAppFreezingTime, Getting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void GetAppFreezingTime(int &time) override; + + /** + * Get system memory information. + * @param SystemMemoryAttr, memory information. + */ + virtual void GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig) override; + + /** + * Notify that the ability stage has been updated + * @param recordId, the app record. + */ + virtual void AddAbilityStageDone(const int32_t recordId) override; + + /** + * Start a resident process + */ + virtual void StartupResidentProcess() override; + + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) override; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) override; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) override; + + /** + * Start user test process. + * @param want, want object. + * @param observer, test observer remote object. + * @param bundleInfo, bundle info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &bundleInfo) override; + + virtual void ScheduleAcceptWantDone( + const int32_t recordId, const AAFwk::Want &want, const std::string &flag) override; + +private: + bool SendTransactCmd(IAppMgr::Message code, MessageParcel &data, MessageParcel &reply); + bool WriteInterfaceToken(MessageParcel &data); + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CLIENT_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_stub.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..0af16c37c815c883cf2a21a5db705d2159be2eec --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_stub.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_STUB_H + +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" +#include "app_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class AppMgrStub : public IRemoteStub { +public: + AppMgrStub(); + virtual ~AppMgrStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) override; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) override; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) override; + +private: + int32_t HandleAttachApplication(MessageParcel &data, MessageParcel &reply); + int32_t HandleApplicationForegrounded(MessageParcel &data, MessageParcel &reply); + int32_t HandleApplicationBackgrounded(MessageParcel &data, MessageParcel &reply); + int32_t HandleApplicationTerminated(MessageParcel &data, MessageParcel &reply); + int32_t HandleCheckPermission(MessageParcel &data, MessageParcel &reply); + int32_t HandleAbilityCleaned(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetAmsMgr(MessageParcel &data, MessageParcel &reply); + int32_t HandleClearUpApplicationData(MessageParcel &data, MessageParcel &reply); + int32_t HandleIsBackgroundRunningRestricted(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetAllRunningProcesses(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetProcessRunningInfosByUserId(MessageParcel &data, MessageParcel &reply); + int32_t HandleSetAppFreezingTime(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetAppFreezingTime(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel &reply); + int32_t HandleAddAbilityStageDone(MessageParcel &data, MessageParcel &reply); + int32_t HandleStartupResidentProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleRegisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply); + int32_t HandleUnregisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetForegroundApplications(MessageParcel &data, MessageParcel &reply); + int32_t HandleStartUserTestProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleAcceptWantDone(MessageParcel &data, MessageParcel &reply); + + using AppMgrFunc = int32_t (AppMgrStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(AppMgrStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_STUB_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_process_data.h b/interfaces/innerkits/app_manager/include/appmgr/app_process_data.h new file mode 100644 index 0000000000000000000000000000000000000000..32a19fe0cb736113c2ceabdaa3c8407d1a1c6382 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_process_data.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_PROCESS_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_PROCESS_DATA_H + +#include + +#include "parcel.h" + +#include "app_mgr_constants.h" + +namespace OHOS { +namespace AppExecFwk { +struct AppData { + std::string appName; + int32_t uid; +}; + +struct AppProcessData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AppProcessData *Unmarshalling(Parcel &parcel); + + std::string processName; + ApplicationState appState = ApplicationState::APP_STATE_CREATE; + pid_t pid = 0; + std::vector appDatas; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_PROCESS_DATA_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_record_id.h b/interfaces/innerkits/app_manager/include/appmgr/app_record_id.h new file mode 100644 index 0000000000000000000000000000000000000000..2a9bd3157421fdd273aa09805c151e8d35ec5567 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_record_id.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_RECORD_ID_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_RECORD_ID_H + +namespace OHOS { +namespace AppExecFwk { +class AppRecordId { +public: + /** + * @brief create id for the application. + * + * @return the app record id. + */ + static int32_t Create(); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_RECORD_ID_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_host.h b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_host.h new file mode 100644 index 0000000000000000000000000000000000000000..5d5c9e4bc5d6ce09efafde77041e50a740fcc857 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_host.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_HOST_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_HOST_H + +#include + +#include "iremote_object.h" +#include "iremote_stub.h" +#include "nocopyable.h" +#include "app_scheduler_interface.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +class AppSchedulerHost : public IRemoteStub { +public: + AppSchedulerHost(); + virtual ~AppSchedulerHost(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t HandleScheduleForegroundApplication(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleBackgroundApplication(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleTerminateApplication(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleLowMemory(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleShrinkMemory(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleLaunchAbility(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleCleanAbility(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleLaunchApplication(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleAbilityStage(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleProfileChanged(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleConfigurationUpdated(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleProcessSecurityExit(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleAcceptWant(MessageParcel &data, MessageParcel &reply); + + using AppSchedulerFunc = int32_t (AppSchedulerHost::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(AppSchedulerHost); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_HOST_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_interface.h b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..631de3d4dbfe25ff3d78423cbe03583c98a4beaa --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_interface.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_INTERFACE_H + +#include "iremote_broker.h" +#include "ability_info.h" +#include "app_launch_data.h" +#include "configuration.h" +#include "hap_module_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class IAppScheduler : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AppScheduler"); + + /** + * ScheduleForegroundApplication, call ScheduleForegroundApplication() through proxy project, + * Notify application to switch to foreground. + * + * @return + */ + virtual void ScheduleForegroundApplication() = 0; + + /** + * ScheduleBackgroundApplication, call ScheduleBackgroundApplication() through proxy project, + * Notify application to switch to background. + * + * @return + */ + virtual void ScheduleBackgroundApplication() = 0; + + /** + * ScheduleTerminateApplication, call ScheduleTerminateApplication() through proxy project, + * Notify application to terminate. + * + * @return + */ + virtual void ScheduleTerminateApplication() = 0; + + /** + * ScheduleShrinkMemory, call ScheduleShrinkMemory() through proxy project, + * Notifies the application of the memory seen. + * + * @param The memory value. + * + * @return + */ + virtual void ScheduleShrinkMemory(const int) = 0; + + /** + * ScheduleLowMemory, call ScheduleLowMemory() through proxy project, + * Notify application to low memory. + * + * @return + */ + virtual void ScheduleLowMemory() = 0; + + /** + * ScheduleLaunchApplication, call ScheduleLaunchApplication() through proxy project, + * Notify application to launch application. + * + * @param The app data value. + * + * @return + */ + virtual void ScheduleLaunchApplication(const AppLaunchData &, const Configuration &) = 0; + + /** + * ScheduleAbilityStageInfo, call ScheduleAbilityStageInfo() through proxy project, + * Notify application to launch application. + * + * @param The app data value. + * + * @return + */ + virtual void ScheduleAbilityStage(const HapModuleInfo &) = 0; + + /** + * ScheduleLaunchAbility, call ScheduleLaunchAbility() through proxy project, + * Notify application to launch ability. + * + * @param The ability info. + * @return + */ + virtual void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) = 0; + + /** + * ScheduleCleanAbility, call ScheduleCleanAbility() through proxy project, + * Notify application to clean ability. + * + * @param The ability token. + * @return + */ + virtual void ScheduleCleanAbility(const sptr &) = 0; + + /** + * ScheduleProfileChanged, call ScheduleProfileChanged() through proxy project, + * Notify application to profile update. + * + * @param The profile data. + * @return + */ + virtual void ScheduleProfileChanged(const Profile &) = 0; + + /** + * ScheduleConfigurationUpdated, call ScheduleConfigurationUpdated() through proxy project, + * Notify application to configuration update. + * + * @param The configuration data. + * @return + */ + virtual void ScheduleConfigurationUpdated(const Configuration &config) = 0; + + /** + * ScheduleProcessSecurityExit, call ScheduleProcessSecurityExit() through proxy project, + * Notify application process exit safely. + * + * @return + */ + virtual void ScheduleProcessSecurityExit() = 0; + + virtual void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) = 0; + + enum class Message { + SCHEDULE_FOREGROUND_APPLICATION_TRANSACTION = 0, + SCHEDULE_BACKGROUND_APPLICATION_TRANSACTION, + SCHEDULE_TERMINATE_APPLICATION_TRANSACTION, + SCHEDULE_LOWMEMORY_APPLICATION_TRANSACTION, + SCHEDULE_SHRINK_MEMORY_APPLICATION_TRANSACTION, + SCHEDULE_LAUNCH_ABILITY_TRANSACTION, + SCHEDULE_CLEAN_ABILITY_TRANSACTION, + SCHEDULE_LAUNCH_APPLICATION_TRANSACTION, + SCHEDULE_PROFILE_CHANGED_TRANSACTION, + SCHEDULE_CONFIGURATION_UPDATED, + SCHEDULE_PROCESS_SECURITY_EXIT_TRANSACTION, + SCHEDULE_ABILITY_STAGE_INFO, + SCHEDULE_ACCEPT_WANT, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_INTERFACE_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..de976e225cda63a87f7b3826c0e8dd7aa750fe05 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_proxy.h @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_CLIENT_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_CLIENT_H + +#include "iremote_proxy.h" +#include "app_scheduler_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class AppSchedulerProxy : public IRemoteProxy { +public: + explicit AppSchedulerProxy(const sptr &impl); + virtual ~AppSchedulerProxy() = default; + + /** + * ScheduleForegroundApplication, call ScheduleForegroundApplication() through proxy project, + * Notify application to switch to foreground. + * + * @return + */ + virtual void ScheduleForegroundApplication() override; + + /** + * ScheduleBackgroundApplication, call ScheduleBackgroundApplication() through proxy project, + * Notify application to switch to background. + * + * @return + */ + virtual void ScheduleBackgroundApplication() override; + + /** + * ScheduleTerminateApplication, call ScheduleTerminateApplication() through proxy project, + * Notify application to terminate. + * + * @return + */ + virtual void ScheduleTerminateApplication() override; + + /** + * ScheduleShrinkMemory, call ScheduleShrinkMemory() through proxy project, + * Notifies the application of the memory seen. + * + * @param The memory value. + * + * @return + */ + virtual void ScheduleShrinkMemory(const int32_t) override; + + /** + * ScheduleLowMemory, call ScheduleLowMemory() through proxy project, + * Notify application to low memory. + * + * @return + */ + virtual void ScheduleLowMemory() override; + + /** + * ScheduleLaunchApplication, call ScheduleLaunchApplication() through proxy project, + * Notify application to launch application. + * + * @param The app data value. + * + * @return + */ + virtual void ScheduleLaunchApplication(const AppLaunchData &, const Configuration &) override; + + /** + * Notify application to launch ability stage. + * + * @param The resident process data value. + */ + virtual void ScheduleAbilityStage(const HapModuleInfo &abilityStage) override; + + /** + * ScheduleLaunchAbility, call ScheduleLaunchAbility() through proxy project, + * Notify application to launch ability. + * + * @param The ability info. + * @return + */ + virtual void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) override; + + /** + * ScheduleCleanAbility, call ScheduleCleanAbility() through proxy project, + * Notify application to clean ability. + * + * @param The ability token. + * @return + */ + virtual void ScheduleCleanAbility(const sptr &) override; + + /** + * ScheduleProfileChanged, call ScheduleProfileChanged() through proxy project, + * Notify application to profile update. + * + * @param The profile data. + * @return + */ + virtual void ScheduleProfileChanged(const Profile &) override; + + /** + * ScheduleConfigurationUpdated, call ScheduleConfigurationUpdated() through proxy project, + * Notify application to configuration update. + * + * @param The configuration data. + * @return + */ + virtual void ScheduleConfigurationUpdated(const Configuration &config) override; + + /** + * ScheduleProcessSecurityExit, call ScheduleProcessSecurityExit() through proxy project, + * Notify application process exit safely. + * + * @return + */ + virtual void ScheduleProcessSecurityExit() override; + + virtual void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_CLIENT_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_service_manager.h b/interfaces/innerkits/app_manager/include/appmgr/app_service_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..fae5e8ea79255ac52d02ebf69a30d2ac9e276472 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_service_manager.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_SERVICE_MANAGER_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_SERVICE_MANAGER_H + +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +class AppServiceManager { +public: + AppServiceManager() = default; + virtual ~AppServiceManager() = default; + + /** + * @brief Obtains the AMS interface instance. + * + * @return Returns the AMS interface instance. + */ + virtual sptr GetAppMgrService() const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_SERVICE_MANAGER_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_state_callback_host.h b/interfaces/innerkits/app_manager/include/appmgr/app_state_callback_host.h new file mode 100644 index 0000000000000000000000000000000000000000..eec80b877474bf1edc0d1bf794a76daaf4f5c7db --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_state_callback_host.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_HOST_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_HOST_H + +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" +#include "app_mgr_constants.h" +#include "iapp_state_callback.h" + +namespace OHOS { +namespace AppExecFwk { +class AppStateCallbackHost : public IRemoteStub { +public: + AppStateCallbackHost(); + virtual ~AppStateCallbackHost(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + /** + * AbilityMgr's request is done. + * + * @param token Ability token. + * @param state Application state. + */ + virtual void OnAbilityRequestDone(const sptr &, const AbilityState) override; + + /** + * Application state changed callback. + * + * @param appProcessData Process data + */ + virtual void OnAppStateChanged(const AppProcessData &) override; + +private: + int32_t HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply); + int32_t HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply); + + using AppStateCallbackFunc = int32_t (AppStateCallbackHost::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(AppStateCallbackHost); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_HOST_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_state_callback_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/app_state_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..b91ed58a3445f533dd1ef3a1a10b259c39c1ab88 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_state_callback_proxy.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_PROXY_H + +#include "iremote_proxy.h" + +#include "app_mgr_constants.h" +#include "iapp_state_callback.h" + +namespace OHOS { +namespace AppExecFwk { +class AppStateCallbackProxy : public IRemoteProxy { +public: + explicit AppStateCallbackProxy(const sptr &impl); + virtual ~AppStateCallbackProxy() = default; + + /** + * AbilityMgr's request is done. + * + * @param token Ability token. + * @param state Application state. + */ + virtual void OnAbilityRequestDone(const sptr &token, const AbilityState state) override; + + /** + * Application state changed callback. + * + * @param appProcessData Process data + */ + virtual void OnAppStateChanged(const AppProcessData &appProcessData) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_PROXY_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_state_data.h b/interfaces/innerkits/app_manager/include/appmgr/app_state_data.h new file mode 100644 index 0000000000000000000000000000000000000000..15b26f76573b09e221d9ec5f4a0fe5f11a989a65 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_state_data.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_DATA_H + +#include + +#include "parcel.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +struct AppStateData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AppStateData *Unmarshalling(Parcel &parcel); + + std::string bundleName; + int32_t uid = 0; + int32_t state = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_DATA_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_task_info.h b/interfaces/innerkits/app_manager/include/appmgr/app_task_info.h new file mode 100644 index 0000000000000000000000000000000000000000..6e5de4b24f0268e0c4c350ffce8cd541b1a91ca6 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/app_task_info.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_TASK_INFO_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_TASK_INFO_H + +#include +#include + +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +class AppTaskInfo : public Parcelable { +public: + /** + * @brief Obtains the app name. + * + * @return Returns the app name. + */ + const std::string &GetName() const; + + /** + * @brief Obtains the process name. + * + * @return Returns the process name. + */ + const std::string &GetProcessName() const; + + /** + * @brief Obtains the app pid. + * + * @return Returns the app pid. + */ + pid_t GetPid() const; + + /** + * @brief Obtains the app record id. + * + * @return Returns app record id. + */ + int32_t GetRecordId() const; + + /** + * @brief Setting name for app. + * + * @param appName, the app name. + */ + void SetName(const std::string &appName); + + /** + * @brief Setting name for process. + * + * @param int32_t, the process name. + */ + void SetProcessName(const std::string &processName); + + /** + * @brief Setting pid for app. + * + * @param int32_t, the app pid. + */ + void SetPid(const pid_t pid); + + /** + * @brief Setting id for app record. + * + * @param int32_t, the app record id. + */ + void SetRecordId(const int32_t appRecordId); + + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read succeeded; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AppTaskInfo *Unmarshalling(Parcel &parcel); + +private: + std::string appName_; + std::string processName_; + pid_t pid_ = 0; + int32_t appRecordId_ = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_TASK_INFO_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/application_state_observer_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/application_state_observer_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..51e309fb43548e63f5db28b415297b5ae3707772 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/application_state_observer_proxy.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_PROXY_H + +#include "iremote_proxy.h" + +#include "app_mgr_constants.h" +#include "iapplication_state_observer.h" + +namespace OHOS { +namespace AppExecFwk { +class ApplicationStateObserverProxy : public IRemoteProxy { +public: + explicit ApplicationStateObserverProxy(const sptr &impl); + virtual ~ApplicationStateObserverProxy() = default; + + /** + * Application foreground state changed callback. + * + * @param appStateData Application Process data. + */ + virtual void OnForegroundApplicationChanged(const AppStateData &appStateData) override; + + /** + * Will be called when the ability state changes. + * + * @param abilityStateData Ability state data. + */ + virtual void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the extension state changes. + * + * @param abilityStateData Extension state data. + */ + virtual void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the process start. + * + * @param processData Process data. + */ + virtual void OnProcessCreated(const ProcessData &processData) override; + + /** + * Will be called when the process die. + * + * @param processData Process data. + */ + virtual void OnProcessDied(const ProcessData &processData) override; + + /** + * Application state changed callback. + * + * @param appStateData Application state data. + */ + virtual void OnApplicationStateChanged(const AppStateData &appStateData) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif diff --git a/interfaces/innerkits/app_manager/include/appmgr/application_state_observer_stub.h b/interfaces/innerkits/app_manager/include/appmgr/application_state_observer_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..4f3197f078605964bdea2bbf978785427fe4b964 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/application_state_observer_stub.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_STUB_H + +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" +#include "app_mgr_constants.h" +#include "iapplication_state_observer.h" + +namespace OHOS { +namespace AppExecFwk { +class ApplicationStateObserverStub : public IRemoteStub { +public: + ApplicationStateObserverStub(); + virtual ~ApplicationStateObserverStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + /** + * Application foreground state changed callback. + * + * @param appStateData Application Process data. + */ + virtual void OnForegroundApplicationChanged(const AppStateData &appStateData) override; + + /** + * Will be called when the ability state changes. + * + * @param abilityStateData Ability state data. + */ + virtual void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the extension state changes. + * + * @param abilityStateData Extension state data. + */ + virtual void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; + + /** + * Will be called when the process start. + * + * @param processData Process data. + */ + virtual void OnProcessCreated(const ProcessData &processData) override; + + /** + * Will be called when the process die. + * + * @param processData Process data. + */ + virtual void OnProcessDied(const ProcessData &processData) override; + + /** + * Application state changed callback. + * + * @param appStateData Application state data. + */ + virtual void OnApplicationStateChanged(const AppStateData &appStateData) override; + +private: + int32_t HandleOnForegroundApplicationChanged(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnAbilityStateChanged(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnExtensionStateChanged(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnProcessCreated(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnProcessDied(MessageParcel &data, MessageParcel &reply); + + int32_t HandleOnApplicationStateChanged(MessageParcel &data, MessageParcel &reply); + + using ApplicationStateObserverFunc = int32_t (ApplicationStateObserverStub::*)(MessageParcel &data, + MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(ApplicationStateObserverStub); +}; + +/** + * @class ApplicationStateObserverRecipient + * ApplicationStateObserverRecipient notices IRemoteBroker died. + */ +class ApplicationStateObserverRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + ApplicationStateObserverRecipient(RemoteDiedHandler handler); + virtual ~ApplicationStateObserverRecipient(); + virtual void OnRemoteDied(const wptr &remote); + +private: + RemoteDiedHandler handler_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APPLICATION_STATE_OBSERVER_STUB_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/configuration.h b/interfaces/innerkits/app_manager/include/appmgr/configuration.h new file mode 100644 index 0000000000000000000000000000000000000000..43ef49f5de5222624ada508ae38782933099b016 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/configuration.h @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_H +#define OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_H + +#include +#include +#include +#include +#include "parcel.h" +#include "global_configuration_key.h" + +namespace OHOS { +namespace AppExecFwk { +namespace ConfigurationInner { + const std::string CONNECTION_SYMBOL {"#"}; + const std::string EMPTY_STRING {""}; + + /* + * This must be synchronized with the value in GlobalConfigurationKey + */ + const std::vector SystemConfigurationKeyStore { + OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, + OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_ORIENTATION, + }; +} +class Configuration final: public Parcelable { +public: + Configuration(); + + Configuration(const Configuration &other); + + Configuration& operator= (const Configuration &other); + + ~Configuration(); + + /** + * @brief Compare the difference between the current and the passed in object. + * + * @param diffKeyV Out Ginseng. get the current difference item keys. + * @param other Comparisons obj + * + * @return void + */ + void CompareDifferent(std::vector &diffKeyV, const Configuration &other); + + /** + * @brief Update the content according to the key. + * + * @param mergeItemKey The key of the element currently to be updated. + * @param other Provide updated content obj + * + * @return void + */ + void Merge(const std::vector &diffKeyV, const Configuration &other); + + /** + * @brief obtain the value according to the display number and storage key. + * + * @param displayId Currently displayed id. + * @param key The key of the item to access configura. ej : key = GlobalConfigurationKey::SYSTEM_LANGUAGE + * Means you want to change the language part + * @param value Changed value + * @return return true if the deposit is successful, otherwise return false + */ + bool AddItem(int displayId, const std::string &key, const std::string &value); + + /** + * @brief obtain the value according to the display number and storage key. + * + * @param displayId Currently displayed id. + * @param key The key of the item to access configura. ej : key = GlobalConfigurationKey::SYSTEM_LANGUAGE + * Means you want to change the language part + * + * @return return empty string if not found | return val if found + */ + std::string GetItem(int displayId, const std::string &key) const; + + /** + * @brief Delete element. + * + * @param displayId Currently displayed id. + * @param key The key of the item to access configura. ej : key = GlobalConfigurationKey::SYSTEM_LANGUAGE + * Means you want to change the language part + * + * @return Return an integer greater than 0 if the deletion succeeds, otherwise it returns 0. + */ + int RemoveItem(int displayId, const std::string &key); + + /** + * @brief obtain the value according to the display number and storage key. + * + * @param key The key of the item to access configura. ej : key = GlobalConfigurationKey::SYSTEM_LANGUAGE + * Means you want to change the language part + * @param value Changed value + * @return return true if the deposit is successful, otherwise return false + */ + bool AddItem(const std::string &key, const std::string &value); + + /** + * @brief obtain the value according to the display number and storage key. + * + * @param key The key of the item to access configura. ej : key = GlobalConfigurationKey::SYSTEM_LANGUAGE + * Means you want to change the language part + * + * @return return empty string if not found | return val if found + */ + std::string GetItem(const std::string &key) const; + + /** + * @brief Delete element. + * + * @param key The key of the item to access configura. ej : key = GlobalConfigurationKey::SYSTEM_LANGUAGE + * Means you want to change the language part + * + * @return Return an integer greater than 0 if the deletion succeeds, otherwise it returns 0. + */ + int RemoveItem(const std::string &key); + + /** + * @brief Get the currently existing key-value pairs. + * + * @return return currently item size. + */ + int GetItemSize() const; + + /** + * @brief Return all current key-value pairs. + * + */ + const std::string& GetName() const; + + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static Configuration *Unmarshalling(Parcel &parcel); + +private: + + /** + * @brief Make the key by id and param + * + * @param getKey Key made. + * @param id displayId. + * @param param The key of the item to access configura. + * + */ + bool MakeTheKey(std::string &getKey, int id, const std::string ¶m) const; + + /** + * @brief Get all current keys. + * + * @param keychain Out Ginseng. Contains all current keys. + */ + void GetAllKey(std::vector &keychain) const; + + /** + * @brief Get value by key. + * + * @param key the key to get value. + */ + std::string GetValue(const std::string &key) const; + +private: + int defaultDisplayId_ {0}; + mutable std::string toStrintg_ {""}; /* For interface GetName(), Assign value only when calling the interface */ + std::unordered_map configParameter_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/global_configuration_key.h b/interfaces/innerkits/app_manager/include/appmgr/global_configuration_key.h new file mode 100644 index 0000000000000000000000000000000000000000..2cbbf7ace4cfdf4a9ac2cc97013b59ac9794a833 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/global_configuration_key.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_INTERFACES_INNERKITS_GLOBAL_CONFIGURATION_KEY_H +#define OHOS_APPEXECFWK_INTERFACES_INNERKITS_GLOBAL_CONFIGURATION_KEY_H + +#include + +namespace OHOS { +namespace AppExecFwk { +namespace GlobalConfigurationKey { + /* For the time being, there is no uniform standard */ + /* Must be synchronized with the keystore(SystemConfigurationKeyStore)in the configuration */ + static const std::string SYSTEM_LANGUAGE {"ohos.system.language"}; + static const std::string SYSTEM_ORIENTATION {"ohos.system.orientation"}; +} // namespace GlobalConfigurationKey +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_INTERFACES_INNERKITS_GLOBAL_CONFIGURATION_KEY_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/iability_controller.h b/interfaces/innerkits/app_manager/include/appmgr/iability_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..96d687fc0404d2b24e6841916d7a53971b3e8c10 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/iability_controller.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IABILITY_CONTROLLER_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IABILITY_CONTROLLER_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; +/** + * @brief Testing interface to monitor what is happening in ability manager while tests are running. + */ +class IAbilityController : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IAbilityController"); + + /** + * The system is trying to start an ability. + * + * @param want The want of ability to start. + * @param bundleName The bundleName of ability to start. + * @return Return true to allow ability to start, or false to reject. + */ + virtual bool AllowAbilityStart(const Want &want, const std::string &bundleName) = 0; + + /** + * The system is scheduling Ability to the foreground. + * + * @param bundleName The bundleName of ability to return. + * @return Return true to allow ability to foreground, or false to reject. + */ + virtual bool AllowAbilityForeground(const std::string &bundleName) = 0; + + enum class Message { + TRANSACT_ON_ALLOW_ABILITY_START = 0, + TRANSACT_ON_ALLOW_ABILITY_FOREGROUND, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IABILITY_CONTROLLER_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/iapp_state_callback.h b/interfaces/innerkits/app_manager/include/appmgr/iapp_state_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..5abbef37c64120311e51285435d03a7da7f6f0e3 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/iapp_state_callback.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPP_STATE_CALLBACK_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPP_STATE_CALLBACK_H + +#include "iremote_broker.h" +#include "iremote_object.h" + +#include "app_mgr_constants.h" +#include "app_process_data.h" + +namespace OHOS { +namespace AppExecFwk { +class IAppStateCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AppStateCallback"); + + /** + * Application state changed callback. + * + * @param appProcessData Process data + */ + virtual void OnAppStateChanged(const AppProcessData &appProcessData) = 0; + + /** + * AbilityMgr's request is done. + * + * @param token Ability token. + * @param state Application state. + */ + virtual void OnAbilityRequestDone(const sptr &token, const AbilityState state) = 0; + + enum class Message { + TRANSACT_ON_APP_STATE_CHANGED = 0, + TRANSACT_ON_ABILITY_REQUEST_DONE, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPP_STATE_CALLBACK_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/iapplication_state_observer.h b/interfaces/innerkits/app_manager/include/appmgr/iapplication_state_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..500cf0e5b72df0ab1c086905bdc18e1bca62491b --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/iapplication_state_observer.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPPLICATION_STATE_OBSERVER_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPPLICATION_STATE_OBSERVER_H + +#include "ability_state_data.h" +#include "app_state_data.h" +#include "process_data.h" +#include "iremote_broker.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +class IApplicationStateObserver : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IApplicationStateObserver"); + + /** + * Application foreground state changed callback. + * + * @param appStateData Application state data. + */ + virtual void OnForegroundApplicationChanged(const AppStateData &appStateData) = 0; + + /** + * Will be called when the ability state changes. + * + * @param abilityStateData Ability state data. + */ + virtual void OnAbilityStateChanged(const AbilityStateData &abilityStateData) = 0; + + /** + * Will be called when the extension state changes. + * + * @param abilityStateData Extension state data. + */ + virtual void OnExtensionStateChanged(const AbilityStateData &abilityStateData) = 0; + + /** + * Will be called when the process start. + * + * @param processData Process data. + */ + virtual void OnProcessCreated(const ProcessData &processData) = 0; + + /** + * Will be called when the process die. + * + * @param processData Process data. + */ + virtual void OnProcessDied(const ProcessData &processData) = 0; + + /** + * Application state changed callback. + * + * @param appStateData Application state data. + */ + virtual void OnApplicationStateChanged(const AppStateData &appStateData) = 0; + + enum class Message { + TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED = 0, + TRANSACT_ON_ABILITY_STATE_CHANGED, + TRANSACT_ON_EXTENSION_STATE_CHANGED, + TRANSACT_ON_PROCESS_CREATED, + TRANSACT_ON_PROCESS_DIED, + TRANSACT_ON_APPLICATION_STATE_CHANGED, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPPLICATION_STATE_OBSERVER_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/istart_specified_ability_response.h b/interfaces/innerkits/app_manager/include/appmgr/istart_specified_ability_response.h new file mode 100644 index 0000000000000000000000000000000000000000..ba87d2da5888977a8f945bacf203b2ebbe3e65f4 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/istart_specified_ability_response.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_ISTART_SPECIFIED_ABILITY_RESPONSE_H +#define FOUNDATION_ISTART_SPECIFIED_ABILITY_RESPONSE_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class IStartSpecifiedAbilityResponse : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.startSpecifiedAbilityResponse"); + + virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) = 0; + + virtual void OnTimeoutResponse(const AAFwk::Want &want) = 0; + + enum class Message { + ON_ACCEPT_WANT_RESPONSE = 0, + ON_TIMEOUT_RESPONSE, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_ISTART_SPECIFIED_ABILITY_RESPONSE_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/priority_object.h b/interfaces/innerkits/app_manager/include/appmgr/priority_object.h new file mode 100644 index 0000000000000000000000000000000000000000..834e236801578bf4ee7e0c7303d3a50924340dc7 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/priority_object.h @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_PRIORITY_OBJECT_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_PRIORITY_OBJECT_H + +#include +#include + +#include "nocopyable.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +class PriorityObject : public Parcelable { +public: + PriorityObject() = default; + virtual ~PriorityObject() = default; + + /** + * @brief Obtains the app pid. + * + * @return Returns the app pid. + */ + pid_t GetPid() const; + + /** + * @brief Obtains the app max adj. + * + * @return Returns the app max adj. + */ + int32_t GetMaxAdj() const; + + /** + * @brief Obtains the app cur adj. + * + * @return Returns the app cur adj. + */ + int32_t GetCurAdj() const; + + /** + * @brief Obtains the app cur cgroup. + * + * @return Returns the app cur cgroup. + */ + int32_t GetCurCgroup() const; + + /** + * @brief Obtains the app time level. + * + * @return Returns the app time level. + */ + int32_t GetTimeLevel() const; + + /** + * @brief Obtains the ability visible status. + * + * @return Returns the ability visible status. + */ + bool GetVisibleStatus() const; + + /** + * @brief Obtains the ability preceptible status. + * + * @return Returns the ability preceptible status. + */ + bool GetPerceptibleStatus() const; + + /** + * @brief Setting pid for app. + * + * @param appName, the app pid. + */ + void SetPid(const pid_t pid); + + /** + * @brief Setting max adj for app. + * + * @param appName, the app max adj. + */ + void SetMaxAdj(const int32_t maxAdj); + + /** + * @brief Setting cur adj for app. + * + * @param appName, the app cur adj. + */ + void SetCurAdj(const int32_t curAdj); + + /** + * @brief Setting cur cgroup for app. + * + * @param appName, the app cur cgroup. + */ + void SetCurCgroup(const int32_t curCgroup); + + /** + * @brief Setting time level for app. + * + * @param appName, the app time level. + */ + void SetTimeLevel(const int32_t timeLevel); + + /** + * @brief Setting visible status for ability. + * + * @param status, the visible status. + */ + void SetVisibleStatus(bool status); + + /** + * @brief Setting perceptible status for ability. + * + * @param status, the perceptible status. + */ + void SetPerceptibleStatus(bool status); + + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static PriorityObject *Unmarshalling(Parcel &parcel); + +private: + pid_t pid_ = 0; + int32_t maxAdj_ = 0; + int32_t curAdj_ = 0; + int32_t curCgroup_ = 0; + int32_t timeLevel_ = 0; + bool visibleStatus_ = false; + bool perceptibleStatus_ = false; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_PRIORITY_OBJECT_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/process_data.h b/interfaces/innerkits/app_manager/include/appmgr/process_data.h new file mode 100644 index 0000000000000000000000000000000000000000..8122c2be2afd347cb0ed8634fcf9912e781b53e9 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/process_data.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_STATE_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_STATE_DATA_H + +#include + +#include "parcel.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +struct ProcessData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static ProcessData *Unmarshalling(Parcel &parcel); + + std::string bundleName; + int32_t pid = 0; + int32_t uid = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_STATE_DATA_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/process_info.h b/interfaces/innerkits/app_manager/include/appmgr/process_info.h new file mode 100644 index 0000000000000000000000000000000000000000..f9247e2be315e286cb0fe553eeef7742048fe707 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/process_info.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_INFO_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_INFO_H + +#include +#include + +#include "nocopyable.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +class ProcessInfo : public Parcelable { +public: + ProcessInfo() = default; + explicit ProcessInfo(const std::string &name, const pid_t &pid); + virtual ~ProcessInfo() = default; + + /** + * @brief Obtains the name of the current process. + * + * @return Returns the current process name. + */ + inline const std::string &GetProcessName() const + { + return processName_; + } + + /** + * @brief Obtains the id of the current process. + * + * @return Returns the current process id. + */ + inline pid_t GetPid() const + { + return pid_; + } + + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static ProcessInfo *Unmarshalling(Parcel &parcel); + +private: + std::string processName_; + pid_t pid_ = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_INFO_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/profile.h b/interfaces/innerkits/app_manager/include/appmgr/profile.h new file mode 100644 index 0000000000000000000000000000000000000000..77589fcd9a8202e5e07b89e6691c3871156f1b0f --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/profile.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROFILE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROFILE_H + +#include + +#include "nocopyable.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +class Profile : public Parcelable { +public: + Profile() = default; + explicit Profile(const std::string &name); + virtual ~Profile() = default; + + /** + * @brief Obtains the profile name. + * + * @return Returns profile name. + */ + inline const std::string &GetName() const + { + return profileName_; + } + + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static Profile *Unmarshalling(Parcel &parcel); + +private: + std::string profileName_; // the name of the ability +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROFILE_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/start_specified_ability_response_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/start_specified_ability_response_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..a7afa43efba2054686a77dd5017d695549e4ae49 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/start_specified_ability_response_proxy.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_START_SPECIFIED_ABILITY_RESPONSE_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_START_SPECIFIED_ABILITY_RESPONSE_PROXY_H + +#include "iremote_proxy.h" +#include "istart_specified_ability_response.h" +namespace OHOS { +namespace AppExecFwk { +class StartSpecifiedAbilityResponseProxy : public IRemoteProxy { +public: + explicit StartSpecifiedAbilityResponseProxy(const sptr &impl); + virtual ~StartSpecifiedAbilityResponseProxy() = default; + + virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) override; + + virtual void OnTimeoutResponse(const AAFwk::Want &want) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_START_SPECIFIED_ABILITY_RESPONSE_PROXY_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/start_specified_ability_response_stub.h b/interfaces/innerkits/app_manager/include/appmgr/start_specified_ability_response_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..5ade7f07be11a72d631cc785a8b3e47970ec237e --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/start_specified_ability_response_stub.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_START_SPECIFIED_ABILITY_RESPONSE_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_START_SPECIFIED_ABILITY_RESPONSE_STUB_H + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" +#include "istart_specified_ability_response.h" + +namespace OHOS { +namespace AppExecFwk { +class StartSpecifiedAbilityResponseStub : public IRemoteStub { +public: + StartSpecifiedAbilityResponseStub(); + virtual ~StartSpecifiedAbilityResponseStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + // virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) {} + // virtual void OnTimeoutResponse(const AAFwk::Want &want) {} + +private: + int32_t HandleOnAcceptWantResponse(MessageParcel &data, MessageParcel &reply); + int32_t HandleOnTimeoutResponse(MessageParcel &data, MessageParcel &reply); + + using responseFunc = std::function; + std::map responseFuncMap_; + + DISALLOW_COPY_AND_MOVE(StartSpecifiedAbilityResponseStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_START_SPECIFIED_ABILITY_RESPONSE_STUB_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/ability_controller_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..303c1890afb000fdbe3260f8c275f1ed5505d6e6 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_proxy.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_controller_proxy.h" + +#include "ipc_types.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +AbilityControllerProxy::AbilityControllerProxy( + const sptr &impl) : IRemoteProxy(impl) +{} + +bool AbilityControllerProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(AbilityControllerProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +bool AbilityControllerProxy::AllowAbilityStart(const Want &want, const std::string &bundleName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return true; + } + data.WriteParcelable(&want); + data.WriteString(bundleName); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return true; + } + int32_t ret = remote->SendRequest( + static_cast(IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_START), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return true; + } + return reply.ReadBool(); +} + +bool AbilityControllerProxy::AllowAbilityForeground(const std::string &bundleName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return true; + } + data.WriteString(bundleName); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return true; + } + int32_t ret = remote->SendRequest( + static_cast(IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_FOREGROUND), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return true; + } + return reply.ReadBool(); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/ability_controller_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5705d3bd0927dafd3d7a8fd6e2a7066fc510adb --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_stub.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_controller_stub.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +AbilityControllerStub::AbilityControllerStub() +{ + memberFuncMap_[static_cast( + IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_START)] = + &AbilityControllerStub::HandleAllowAbilityStart; + memberFuncMap_[static_cast( + IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_FOREGROUND)] = + &AbilityControllerStub::HandleAllowAbilityForeground; +} + +AbilityControllerStub::~AbilityControllerStub() +{ + memberFuncMap_.clear(); +} + +int AbilityControllerStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("AbilityControllerStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = AbilityControllerStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +bool AbilityControllerStub::AllowAbilityStart(const Want &want, const std::string &bundleName) +{ + return true; +} + +bool AbilityControllerStub::AllowAbilityForeground(const std::string &bundleName) +{ + return true; +} + +int32_t AbilityControllerStub::HandleAllowAbilityStart(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("HandleAllowAbilityStart"); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + std::string pkg = data.ReadString(); + bool ret = AllowAbilityStart(*want, pkg); + reply.WriteBool(ret); + return NO_ERROR; +} + +int32_t AbilityControllerStub::HandleAllowAbilityForeground(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("HandleAllowAbilityForeground"); + std::string pkg = data.ReadString(); + bool ret = AllowAbilityForeground(pkg); + reply.WriteBool(ret); + return NO_ERROR; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/ability_state_data.cpp b/interfaces/innerkits/app_manager/src/appmgr/ability_state_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5dd13b6e2d695796fbe95b7a3cab6ad86e71418b --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/ability_state_data.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_state_data.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +bool AbilityStateData::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString(bundleName) && parcel.WriteString(abilityName) && + parcel.WriteInt32(abilityState) && + parcel.WriteInt32(pid) && parcel.WriteInt32(uid) && parcel.WriteParcelable(token)); +} + +bool AbilityStateData::ReadFromParcel(Parcel &parcel) +{ + bundleName = parcel.ReadString(); + + abilityName = parcel.ReadString(); + + abilityState = parcel.ReadInt32(); + + pid = parcel.ReadInt32(); + + uid = parcel.ReadInt32(); + + token = parcel.ReadParcelable(); + + return true; +} + +AbilityStateData *AbilityStateData::Unmarshalling(Parcel &parcel) +{ + AbilityStateData *abilityStateData = new (std::nothrow) AbilityStateData(); + if (abilityStateData && !abilityStateData->ReadFromParcel(parcel)) { + APP_LOGW("AbilityStateData failed, because ReadFromParcel failed"); + delete abilityStateData; + abilityStateData = nullptr; + } + return abilityStateData; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..effa2e7d6798bc3c295847e861a934c079e5bec5 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_proxy.cpp @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_mgr_proxy.h" +#include "ipc_types.h" +#include "iremote_object.h" +#include "string_ex.h" + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" + +namespace OHOS { +namespace AppExecFwk { +AmsMgrProxy::AmsMgrProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +bool AmsMgrProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(AmsMgrProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void AmsMgrProxy::LoadAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) +{ + APP_LOGD("start"); + if (!abilityInfo || !appInfo) { + APP_LOGE("param error"); + return; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token); + data.WriteParcelable(preToken); + data.WriteParcelable(abilityInfo.get()); + data.WriteParcelable(appInfo.get()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest(static_cast(IAmsMgr::Message::LOAD_ABILITY), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::TerminateAbility(const sptr &token) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::TERMINATE_ABILITY), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::UpdateAbilityState(const sptr &token, const AbilityState state) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + data.WriteInt32(static_cast(state)); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::UPDATE_ABILITY_STATE), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + APP_LOGD("UpdateExtensionState start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + data.WriteInt32(static_cast(state)); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::UPDATE_EXTENSION_STATE), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::RegisterAppStateCallback(const sptr &callback) +{ + APP_LOGD("start"); + if (!callback) { + APP_LOGE("callback is nullptr"); + return; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(callback->AsObject()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is nullptr"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAmsMgr::Message::REGISTER_APP_STATE_CALLBACK), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::Reset() +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest(static_cast(IAmsMgr::Message::RESET), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + data.WriteParcelable(preToken.GetRefPtr()); + data.WriteInt32(static_cast(visibility)); + data.WriteInt32(static_cast(perceptibility)); + data.WriteInt32(static_cast(connectionState)); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::TERMINATE_ABILITY), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::KillProcessByAbilityToken(const sptr &token) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::TERMINATE_ABILITY), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::KillProcessesByUserId(int32_t userId) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + if (!data.WriteInt32(userId)) { + APP_LOGE("parcel WriteInt32 failed"); + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::KILL_PROCESSES_BY_USERID), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +int32_t AmsMgrProxy::KillProcessWithAccount(const std::string &bundleName, const int accountId) +{ + APP_LOGD("start"); + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_INVALID_DATA; + } + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("parcel WriteString failed"); + return ERR_FLATTEN_OBJECT; + } + + if (!data.WriteInt32(accountId)) { + APP_LOGE("parcel WriteInt32 failed"); + return ERR_FLATTEN_OBJECT; + } + + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::KILL_PROCESS_WITH_ACCOUNT), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ret; + } + + APP_LOGD("end"); + + return reply.ReadInt32(); +} + +int32_t AmsMgrProxy::KillApplication(const std::string &bundleName) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_INVALID_DATA; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + if (!data.WriteString(bundleName)) { + APP_LOGE("parcel WriteString failed"); + return ERR_FLATTEN_OBJECT; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::KILL_APPLICATION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ret; + } + return reply.ReadInt32(); +} + +int32_t AmsMgrProxy::KillApplicationByUid(const std::string &bundleName, const int uid) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_INVALID_DATA; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + if (!data.WriteString(bundleName)) { + APP_LOGE("parcel WriteString failed"); + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteInt32(uid)) { + APP_LOGE("uid write failed."); + return ERR_FLATTEN_OBJECT; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::KILL_APPLICATION_BYUID), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ret; + } + return reply.ReadInt32(); +} + +void AmsMgrProxy::AbilityAttachTimeOut(const sptr &token) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::ABILITY_ATTACH_TIMEOUT), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AmsMgrProxy::PrepareTerminate(const sptr &token) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::PREPARE_TERMINATE_ABILITY), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +int AmsMgrProxy::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_INVALID_DATA; + } + if (!data.WriteString16(Str8ToStr16(permission)) || !data.WriteInt32(pid) || !data.WriteInt32(uid)) { + APP_LOGE("%{public}s, write failed", __func__); + return ERR_INVALID_DATA; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + auto ret = + remote->SendRequest(static_cast(IAmsMgr::Message::COMPEL_VERIFY_PERMISSION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ERR_INVALID_DATA; + } + message = Str16ToStr8(reply.ReadString16()); + return reply.ReadInt32(); +} + +void AmsMgrProxy::GetRunningProcessInfoByToken( + const sptr &token, AppExecFwk::RunningProcessInfo &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteParcelable(token.GetRefPtr())) { + return; + } + + auto remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + auto ret = remote->SendRequest( + static_cast(IAmsMgr::Message::GET_RUNNING_PROCESS_INFO_BY_TOKEN), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return; + } + + std::unique_ptr processInfo(reply.ReadParcelable()); + if (processInfo == nullptr) { + APP_LOGE("recv process info faild"); + return; + } + + info = *processInfo; +} + +void AmsMgrProxy::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) + +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteParcelable(&want) || !data.WriteParcelable(&abilityInfo)) { + APP_LOGE("Write data failed."); + return; + } + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote is nullptr."); + return; + } + auto ret = remote->SendRequest( + static_cast(IAmsMgr::Message::START_SPECIFIED_ABILITY), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AmsMgrProxy::RegisterStartSpecifiedAbilityResponse(const sptr &response) +{ + APP_LOGD("Register multi instances response by proxy."); + if (!response) { + APP_LOGE("response is nullptr"); + return; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(response->AsObject()); + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote is nullptr."); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAmsMgr::Message::REGISTER_START_SPECIFIED_ABILITY_RESPONSE), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AmsMgrProxy::UpdateConfiguration(const Configuration &config) +{ + APP_LOGI("UpdateConfiguration start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + if (!data.WriteParcelable(&config)) { + APP_LOGE("parcel config failed"); + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::UPDATE_CONFIGURATION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGI("UpdateConfiguration end"); +} + +int AmsMgrProxy::GetConfiguration(Configuration &config) +{ + APP_LOGI("GetConfiguration start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + APP_LOGE("parcel data failed"); + return ERR_INVALID_DATA; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_INVALID_DATA; + } + int32_t ret = + remote->SendRequest(static_cast(IAmsMgr::Message::GET_CONFIGURATION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ERR_INVALID_DATA; + } + + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("read configuration failed."); + return ERR_UNKNOWN_OBJECT; + } + config = *info; + APP_LOGI("GetConfiguration end"); + return NO_ERROR; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9ad246fa302f2ffaf435b54787a652025164f73 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_stub.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_mgr_stub.h" + +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +#include "ability_info.h" +#include "app_log_wrapper.h" +#include "app_mgr_proxy.h" +#include "app_scheduler_interface.h" +#include "appexecfwk_errors.h" +#include "bytrace.h" +#include "iapp_state_callback.h" + +namespace OHOS { +namespace AppExecFwk { +AmsMgrStub::AmsMgrStub() +{ + memberFuncMap_[static_cast(IAmsMgr::Message::LOAD_ABILITY)] = &AmsMgrStub::HandleLoadAbility; + memberFuncMap_[static_cast(IAmsMgr::Message::TERMINATE_ABILITY)] = + &AmsMgrStub::HandleTerminateAbility; + memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_ABILITY_STATE)] = + &AmsMgrStub::HandleUpdateAbilityState; + memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_EXTENSION_STATE)] = + &AmsMgrStub::HandleUpdateExtensionState; + memberFuncMap_[static_cast(IAmsMgr::Message::REGISTER_APP_STATE_CALLBACK)] = + &AmsMgrStub::HandleRegisterAppStateCallback; + memberFuncMap_[static_cast(IAmsMgr::Message::RESET)] = &AmsMgrStub::HandleReset; + memberFuncMap_[static_cast(IAmsMgr::Message::ABILITY_BEHAVIOR_ANALYSIS)] = + &AmsMgrStub::HandleAbilityBehaviorAnalysis; + memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PEOCESS_BY_ABILITY_TOKEN)] = + &AmsMgrStub::HandleKillProcessByAbilityToken; + memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PROCESSES_BY_USERID)] = + &AmsMgrStub::HandleKillProcessesByUserId; + memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PROCESS_WITH_ACCOUNT)] = + &AmsMgrStub::HandleKillProcessWithAccount; + memberFuncMap_[static_cast(IAmsMgr::Message::KILL_APPLICATION)] = &AmsMgrStub::HandleKillApplication; + memberFuncMap_[static_cast(IAmsMgr::Message::ABILITY_ATTACH_TIMEOUT)] = + &AmsMgrStub::HandleAbilityAttachTimeOut; + memberFuncMap_[static_cast(IAmsMgr::Message::COMPEL_VERIFY_PERMISSION)] = + &AmsMgrStub::HandleCompelVerifyPermission; + memberFuncMap_[static_cast(IAmsMgr::Message::PREPARE_TERMINATE_ABILITY)] = + &AmsMgrStub::HandlePrepareTerminate; + memberFuncMap_[static_cast(IAmsMgr::Message::KILL_APPLICATION_BYUID)] = + &AmsMgrStub::HandleKillApplicationByUid; + memberFuncMap_[static_cast(IAmsMgr::Message::GET_RUNNING_PROCESS_INFO_BY_TOKEN)] = + &AmsMgrStub::HandleGetRunningProcessInfoByToken; + memberFuncMap_[static_cast(IAmsMgr::Message::START_SPECIFIED_ABILITY)] = + &AmsMgrStub::HandleStartSpecifiedAbility; + memberFuncMap_[static_cast(IAmsMgr::Message::REGISTER_START_SPECIFIED_ABILITY_RESPONSE)] = + &AmsMgrStub::HandleRegisterStartSpecifiedAbilityResponse; + memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_CONFIGURATION)] = + &AmsMgrStub::HandleUpdateConfiguration; + memberFuncMap_[static_cast(IAmsMgr::Message::GET_CONFIGURATION)] = + &AmsMgrStub::HandleGetConfiguration; +} + +AmsMgrStub::~AmsMgrStub() +{ + memberFuncMap_.clear(); +} + +int AmsMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("AmsMgrStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = AmsMgrStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +ErrCode AmsMgrStub::HandleLoadAbility(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + sptr preToke = data.ReadParcelable(); + std::shared_ptr abilityInfo(data.ReadParcelable()); + if (!abilityInfo) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + std::shared_ptr appInfo(data.ReadParcelable()); + if (!appInfo) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + LoadAbility(token, preToke, abilityInfo, appInfo); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleTerminateAbility(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + TerminateAbility(token); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleUpdateAbilityState(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + int32_t state = data.ReadInt32(); + UpdateAbilityState(token, static_cast(state)); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleUpdateExtensionState(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + int32_t state = data.ReadInt32(); + UpdateExtensionState(token, static_cast(state)); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr obj = data.ReadParcelable(); + sptr callback = iface_cast(obj); + RegisterAppStateCallback(callback); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleReset(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + Reset(); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleAbilityBehaviorAnalysis(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + sptr preToke = data.ReadParcelable(); + int32_t visibility = data.ReadInt32(); + int32_t Perceptibility = data.ReadInt32(); + int32_t connectionState = data.ReadInt32(); + + AbilityBehaviorAnalysis(token, preToke, visibility, Perceptibility, connectionState); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleKillProcessByAbilityToken(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + + KillProcessByAbilityToken(token); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleKillProcessesByUserId(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + int32_t userId = data.ReadInt32(); + + KillProcessesByUserId(userId); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleKillProcessWithAccount(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("enter"); + + BYTRACE(BYTRACE_TAG_APP); + + std::string bundleName = data.ReadString(); + int accountId = data.ReadInt32(); + + APP_LOGI("bundleName = %{public}s, accountId = %{public}d", bundleName.c_str(), accountId); + + int32_t result = KillProcessWithAccount(bundleName, accountId); + reply.WriteInt32(result); + + APP_LOGI("end"); + + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleKillApplication(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::string bundleName = data.ReadString(); + int32_t result = KillApplication(bundleName); + reply.WriteInt32(result); + return NO_ERROR; +} + +ErrCode AmsMgrStub::HandleKillApplicationByUid(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::string bundleName = data.ReadString(); + int uid = data.ReadInt32(); + int32_t result = KillApplicationByUid(bundleName, uid); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AmsMgrStub::HandleAbilityAttachTimeOut(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + AbilityAttachTimeOut(token); + return NO_ERROR; +} + +int32_t AmsMgrStub::HandleCompelVerifyPermission(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + auto permission = Str16ToStr8(data.ReadString16()); + auto pid = data.ReadInt32(); + auto uid = data.ReadInt32(); + std::string message; + auto result = CompelVerifyPermission(permission, pid, uid, message); + reply.WriteString16(Str8ToStr16(message)); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AmsMgrStub::HandlePrepareTerminate(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + PrepareTerminate(token); + return NO_ERROR; +} + +void AmsMgrStub::UpdateExtensionState(const sptr &token, const ExtensionState state) +{} + +int32_t AmsMgrStub::HandleGetRunningProcessInfoByToken(MessageParcel &data, MessageParcel &reply) +{ + RunningProcessInfo processInfo; + auto token = data.ReadParcelable(); + GetRunningProcessInfoByToken(token, processInfo); + if (reply.WriteParcelable(&processInfo)) { + APP_LOGE("process info write failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int32_t AmsMgrStub::HandleStartSpecifiedAbility(MessageParcel &data, MessageParcel &reply) +{ + AAFwk::Want *want = data.ReadParcelable(); + if (want == nullptr) { + APP_LOGE("want is nullptr"); + return ERR_INVALID_VALUE; + } + + AbilityInfo *abilityInfo = data.ReadParcelable(); + if (abilityInfo == nullptr) { + APP_LOGE("abilityInfo is nullptr."); + return ERR_INVALID_VALUE; + } + StartSpecifiedAbility(*want, *abilityInfo); + return NO_ERROR; +} + +int32_t AmsMgrStub::HandleRegisterStartSpecifiedAbilityResponse(MessageParcel &data, MessageParcel &reply) +{ + sptr obj = data.ReadParcelable(); + sptr response = iface_cast(obj); + RegisterStartSpecifiedAbilityResponse(response); + return NO_ERROR; +} + +int32_t AmsMgrStub::HandleUpdateConfiguration(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr config(data.ReadParcelable()); + if (config) { + UpdateConfiguration(*config); + return NO_ERROR; + } + return UNKNOWN_ERROR; +} + +int32_t AmsMgrStub::HandleGetConfiguration(MessageParcel &data, MessageParcel &reply) +{ + Configuration config; + int ret = GetConfiguration(config); + if (ret != ERR_OK) { + APP_LOGE("GetConfiguration error"); + return ERR_INVALID_VALUE; + } + if (!reply.WriteParcelable(&config)) { + APP_LOGE("GetConfiguration error"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_launch_data.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_launch_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..918ca5842aef798bc24c2ecff0f5c824c18bb112 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_launch_data.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_launch_data.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +void AppLaunchData::SetApplicationInfo(const ApplicationInfo &info) +{ + applicationInfo_ = info; +} + +void AppLaunchData::SetProfile(const Profile &profile) +{ + profile_ = profile; +} + +void AppLaunchData::SetProcessInfo(const ProcessInfo &info) +{ + processInfo_ = info; +} + +void AppLaunchData::SetRecordId(const int32_t recordId) +{ + recordId_ = recordId; +} + +void AppLaunchData::SetUId(const int32_t uId) +{ + uId_ = uId; +} + +void AppLaunchData::SetUserTestInfo(const UserTestRecord &record) +{ + userTestRecord_ = record; +} + +bool AppLaunchData::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteParcelable(&applicationInfo_) && parcel.WriteParcelable(&profile_) && + parcel.WriteParcelable(&processInfo_) && parcel.WriteInt32(recordId_) && + parcel.WriteInt32(uId_) && parcel.WriteParcelable(&userTestRecord_)); +} + +bool AppLaunchData::ReadFromParcel(Parcel &parcel) +{ + std::unique_ptr applicationInfoRead(parcel.ReadParcelable()); + if (!applicationInfoRead) { + APP_LOGE("failed, applicationInfoRead is nullptr"); + return false; + } + applicationInfo_ = *applicationInfoRead; + + std::unique_ptr profileRead(parcel.ReadParcelable()); + if (!profileRead) { + APP_LOGE("failed, profileRead is nullptr"); + return false; + } + profile_ = *profileRead; + + std::unique_ptr processInfoRead(parcel.ReadParcelable()); + if (!processInfoRead) { + APP_LOGE("failed, processInfoRead is nullptr"); + return false; + } + processInfo_ = *processInfoRead; + + recordId_ = parcel.ReadInt32(); + uId_ = parcel.ReadInt32(); + + std::unique_ptr userTestRecord(parcel.ReadParcelable()); + if (!userTestRecord) { + APP_LOGE("failed, userTestRecord is nullptr"); + return false; + } + userTestRecord_ = *userTestRecord; + return true; +} + +AppLaunchData *AppLaunchData::Unmarshalling(Parcel &parcel) +{ + AppLaunchData *appLaunchData = new (std::nothrow) AppLaunchData(); + if (appLaunchData && !appLaunchData->ReadFromParcel(parcel)) { + APP_LOGW("failed, because ReadFromParcel failed"); + delete appLaunchData; + appLaunchData = nullptr; + } + return appLaunchData; +} + +bool UserTestRecord::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(&want)) { + APP_LOGE("Failed to write want"); + return false; + } + + auto valid = observer ? true : false; + if (!parcel.WriteBool(valid)) { + APP_LOGE("Failed to write the flag which indicate whether observer is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(observer)) { + APP_LOGE("Failed to write observer"); + return false; + } + } + return true; +} + +UserTestRecord *UserTestRecord::Unmarshalling(Parcel &parcel) +{ + UserTestRecord *userTestRecord = new (std::nothrow) UserTestRecord(); + if (userTestRecord && !userTestRecord->ReadFromParcel(parcel)) { + APP_LOGW("failed, because ReadFromParcel failed"); + delete userTestRecord; + userTestRecord = nullptr; + } + return userTestRecord; +} + +bool UserTestRecord::ReadFromParcel(Parcel &parcel) +{ + AAFwk::Want *wantPtr = parcel.ReadParcelable(); + if (wantPtr == nullptr) { + APP_LOGE("wantPtr is nullptr"); + return ERR_INVALID_VALUE; + } + want = *wantPtr; + delete wantPtr; + + auto valid = parcel.ReadBool(); + if (valid) { + observer = parcel.ReadParcelable(); + if (!observer) { + APP_LOGE("observer is nullptr"); + return false; + } + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_client.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a19edea671213bc2611ada0e3d3295ec609d5c44 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_client.cpp @@ -0,0 +1,439 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_client.h" + +#include +#include +#include + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" + +#include "app_log_wrapper.h" +#include "app_mgr_interface.h" +#include "app_service_manager.h" + +namespace OHOS { +namespace AppExecFwk { +AppMgrClient::AppMgrClient() +{ + SetServiceManager(std::make_unique()); +} + +AppMgrClient::~AppMgrClient() +{} + +AppMgrResultCode AppMgrClient::LoadAbility(const sptr &token, const sptr &preToken, + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + // From here, separate AbilityInfo and ApplicationInfo from AA. + std::shared_ptr abilityInfoPtr = std::make_shared(abilityInfo); + std::shared_ptr appInfoPtr = std::make_shared(appInfo); + amsService->LoadAbility(token, preToken, abilityInfoPtr, appInfoPtr); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::TerminateAbility(const sptr &token) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->TerminateAbility(token); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::UpdateAbilityState(const sptr &token, const AbilityState state) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->UpdateAbilityState(token, state); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->UpdateExtensionState(token, state); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::RegisterAppStateCallback(const sptr &callback) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->RegisterAppStateCallback(callback); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::Reset() +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->Reset(); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::AbilityBehaviorAnalysis(const sptr &token, + const sptr &preToken, const int32_t visibility, const int32_t perceptibility, + const int32_t connectionState) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->AbilityBehaviorAnalysis(token, preToken, visibility, perceptibility, connectionState); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::KillProcessByAbilityToken(const sptr &token) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->KillProcessByAbilityToken(token); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::KillProcessesByUserId(int32_t userId) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->KillProcessesByUserId(userId); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::KillApplication(const std::string &bundleName) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + int32_t result = amsService->KillApplication(bundleName); + if (result == ERR_OK) { + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::KillApplicationByUid(const std::string &bundleName, const int uid) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + int32_t result = amsService->KillApplicationByUid(bundleName, uid); + if (result == ERR_OK) { + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::ClearUpApplicationData(const std::string &bundleName) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + int32_t result = service->ClearUpApplicationData(bundleName); + if (result == ERR_OK) { + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::GetAllRunningProcesses(std::vector &info) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + int32_t result = service->GetAllRunningProcesses(info); + if (result == ERR_OK) { + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + int32_t result = service->GetProcessRunningInfosByUserId(info, userId); + if (result == ERR_OK) { + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::GetConfiguration(Configuration& config) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + int32_t result = amsService->GetConfiguration(config); + if (result == ERR_OK) { + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::SetAppFreezingTime(int time) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + service->SetAppFreezingTime(time); + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::GetAppFreezingTime(int &time) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + service->GetAppFreezingTime(time); + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +AppMgrResultCode AppMgrClient::ConnectAppMgrService() +{ + if (!serviceManager_) { + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + remote_ = serviceManager_->GetAppMgrService(); + if (!remote_) { + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + return AppMgrResultCode::RESULT_OK; +} + +void AppMgrClient::SetServiceManager(std::unique_ptr serviceMgr) +{ + serviceManager_ = std::move(serviceMgr); +} + +void AppMgrClient::AbilityAttachTimeOut(const sptr &token) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + return; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + return; + } + amsService->AbilityAttachTimeOut(token); +} + +void AppMgrClient::PrepareTerminate(const sptr &token) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + return; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + return; + } + amsService->PrepareTerminate(token); +} + +int AppMgrClient::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + auto result = amsService->CompelVerifyPermission(permission, pid, uid, message); + if (result != ERR_OK) { + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + return AppMgrResultCode::RESULT_OK; +} + +/** + * Get system memory information. + * @param SystemMemoryAttr, memory information. + */ +void AppMgrClient::GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + APP_LOGE("service is nullptr"); + return; + } + + service->GetSystemMemoryAttr(memoryInfo, strConfig); +} + +void AppMgrClient::GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) +{ + sptr service = iface_cast(remote_); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->GetRunningProcessInfoByToken(token, info); + } + } +} + +void AppMgrClient::AddAbilityStageDone(const int32_t recordId) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + APP_LOGE("service is nullptr"); + return; + } + + service->AddAbilityStageDone(recordId); +} + +void AppMgrClient::StartupResidentProcess() +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + APP_LOGE("service is nullptr"); + return; + } + + service->StartupResidentProcess(); +} + +int AppMgrClient::StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &bundleInfo) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + APP_LOGE("service is nullptr"); + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + return service->StartUserTestProcess(want, observer, bundleInfo); +} + +void AppMgrClient::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + return; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + return; + } + amsService->StartSpecifiedAbility(want, abilityInfo); +} + +void AppMgrClient::RegisterStartSpecifiedAbilityResponse(const sptr &response) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + return; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + return; + } + amsService->RegisterStartSpecifiedAbilityResponse(response); +} + +void AppMgrClient::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + APP_LOGE("service is nullptr"); + return; + } + + service->ScheduleAcceptWantDone(recordId, want, flag); +} + +AppMgrResultCode AppMgrClient::UpdateConfiguration(const Configuration &config) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + amsService->UpdateConfiguration(config); + return AppMgrResultCode::RESULT_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac1495cd26018fc0f49743f230bd210167da9b79 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp @@ -0,0 +1,588 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_proxy.h" + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" + +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +AppMgrProxy::AppMgrProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +bool AppMgrProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(AppMgrProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void AppMgrProxy::AttachApplication(const sptr &obj) +{ + APP_LOGD("AppMgrProxy::AttachApplication start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(obj.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAppMgr::Message::APP_ATTACH_APPLICATION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AppMgrProxy::ApplicationForegrounded(const int32_t recordId) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteInt32(recordId); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppMgr::Message::APP_APPLICATION_FOREGROUNDED), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AppMgrProxy::ApplicationBackgrounded(const int32_t recordId) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteInt32(recordId); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppMgr::Message::APP_APPLICATION_BACKGROUNDED), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AppMgrProxy::ApplicationTerminated(const int32_t recordId) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteInt32(recordId); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppMgr::Message::APP_APPLICATION_TERMINATED), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +int32_t AppMgrProxy::CheckPermission(const int32_t recordId, const std::string &permission) +{ + APP_LOGD("start"); + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_PERMISSION_DENIED; + } + data.WriteInt32(recordId); + data.WriteString(permission); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_PERMISSION_DENIED; + } + int32_t ret = + remote->SendRequest(static_cast(IAppMgr::Message::APP_CHECK_PERMISSION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGE("SendRequest is failed, error code: %{public}d", ret); + return ERR_PERMISSION_DENIED; + } + APP_LOGD("end"); + return reply.ReadInt32(); +} + +void AppMgrProxy::AbilityCleaned(const sptr &token) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAppMgr::Message::APP_ABILITY_CLEANED), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +sptr AppMgrProxy::GetAmsMgr() +{ + APP_LOGD("begin to get Ams instance"); + MessageParcel data; + MessageParcel reply; + if (!WriteInterfaceToken(data)) { + return nullptr; + } + if (!SendTransactCmd(IAppMgr::Message::APP_GET_MGR_INSTANCE, data, reply)) { + return nullptr; + } + sptr object = reply.ReadParcelable(); + sptr amsMgr = iface_cast(object); + if (!amsMgr) { + APP_LOGE("ams instance is nullptr"); + return nullptr; + } + APP_LOGD("get ams instance success"); + return amsMgr; +} + +int32_t AppMgrProxy::ClearUpApplicationData(const std::string &bundleName) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + if (!data.WriteString(bundleName)) { + APP_LOGE("parcel WriteString failed"); + return ERR_FLATTEN_OBJECT; + } + int32_t ret = remote->SendRequest( + static_cast(IAppMgr::Message::APP_CLEAR_UP_APPLICATION_DATA), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ret; + } + APP_LOGD("end"); + return reply.ReadInt32(); +} + +int32_t AppMgrProxy::IsBackgroundRunningRestricted(const std::string &bundleName) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + if (!data.WriteString(bundleName)) { + APP_LOGE("parcel WriteString failed"); + return ERR_FLATTEN_OBJECT; + } + int32_t ret = remote->SendRequest( + static_cast(IAppMgr::Message::APP_IS_BACKGROUND_RUNNING_RESTRICTED), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ret; + } + APP_LOGD("end"); + return reply.ReadInt32(); +} + +int32_t AppMgrProxy::GetAllRunningProcesses(std::vector &info) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + if (!SendTransactCmd(IAppMgr::Message::APP_GET_ALL_RUNNING_PROCESSES, data, reply)) { + return ERR_NULL_OBJECT; + } + auto error = GetParcelableInfos(reply, info); + if (error != NO_ERROR) { + APP_LOGE("GetParcelableInfos fail, error: %{public}d", error); + return error; + } + int result = reply.ReadInt32(); + APP_LOGD("end"); + return result; +} + +int32_t AppMgrProxy::GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + + data.WriteInt32(userId); + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return ERR_NULL_OBJECT; + } + if (!SendTransactCmd(IAppMgr::Message::APP_GET_RUNNING_PROCESSES_BY_USER_ID, data, reply)) { + return ERR_NULL_OBJECT; + } + auto error = GetParcelableInfos(reply, info); + if (error != NO_ERROR) { + APP_LOGE("GetParcelableInfos fail, error: %{public}d", error); + return error; + } + int result = reply.ReadInt32(); + APP_LOGD("end"); + return result; +} + +bool AppMgrProxy::SendTransactCmd(IAppMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (!remote) { + APP_LOGE("fail to send transact cmd %{public}d due to remote object", code); + return false; + } + int32_t result = remote->SendRequest(static_cast(code), data, reply, option); + if (result != NO_ERROR) { + APP_LOGE("receive error transact code %{public}d in transact cmd %{public}d", result, code); + return false; + } + return true; +} + +void AppMgrProxy::SetAppFreezingTime(int time) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteInt32(time)) { + APP_LOGE("parcel WriteInt32 failed"); + return; + } + if (!SendTransactCmd(IAppMgr::Message::APP_SET_APP_FREEZING_TIME, data, reply)) { + APP_LOGE("SendTransactCmd faild"); + return; + } + APP_LOGD("end"); +} + +void AppMgrProxy::GetAppFreezingTime(int &time) +{ + APP_LOGD("start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + APP_LOGE("WriteInterfaceToken faild"); + return; + } + + if (!SendTransactCmd(IAppMgr::Message::APP_GET_APP_FREEZING_TIME, data, reply)) { + APP_LOGE("SendTransactCmd faild"); + return; + } + time = reply.ReadInt32(); + APP_LOGE("get freeze time : %{public}d ", time); +} + +/** + * Get system memory information. + * @param SystemMemoryAttr, memory information. + */ +void AppMgrProxy::GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig) +{ + MessageParcel data; + MessageParcel reply; + if (!WriteInterfaceToken(data)) { + APP_LOGE("WriteInterfaceToken faild"); + return; + } + + if (!data.WriteString(strConfig)) { + APP_LOGE("want write failed."); + return; + } + + if (!SendTransactCmd(IAppMgr::Message::APP_GET_SYSTEM_MEMORY_ATTR, data, reply)) { + APP_LOGE("SendTransactCmd faild"); + return; + } + + std::shared_ptr remoteRetsult(reply.ReadParcelable()); + if (remoteRetsult == nullptr) { + APP_LOGE("recv SystemMemoryAttr faild"); + return; + } + + memoryInfo = *remoteRetsult; +} + +void AppMgrProxy::AddAbilityStageDone(const int32_t recordId) +{ + MessageParcel data; + MessageParcel reply; + if (!WriteInterfaceToken(data)) { + APP_LOGE("WriteInterfaceToken faild"); + return; + } + + if (!data.WriteInt32(recordId)) { + APP_LOGE("want write failed."); + return; + } + + if (!SendTransactCmd(IAppMgr::Message::APP_ADD_ABILITY_STAGE_INFO_DONE, data, reply)) { + APP_LOGE("SendTransactCmd faild"); + return; + } + return; +} + +void AppMgrProxy::StartupResidentProcess() +{ + MessageParcel data; + MessageParcel reply; + if (!WriteInterfaceToken(data)) { + APP_LOGE("WriteInterfaceToken faild"); + return; + } + + if (!SendTransactCmd(IAppMgr::Message::STARTUP_RESIDENT_PROCESS, data, reply)) { + APP_LOGE("SendTransactCmd faild"); + return; + } + return; +} + +template +int AppMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("Read Parcelable infos failed"); + return ERR_INVALID_VALUE; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGD("get parcelable infos success"); + return NO_ERROR; +} + +int AppMgrProxy::RegisterApplicationStateObserver( + const sptr &observer) +{ + if (!observer) { + APP_LOGE("observer null"); + return ERR_INVALID_VALUE; + } + APP_LOGD("RegisterApplicationStateObserver start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteParcelable(observer->AsObject())) { + APP_LOGE("observer write failed."); + return ERR_FLATTEN_OBJECT; + } + + auto error = Remote()->SendRequest(static_cast(IAppMgr::Message::REGISTER_APPLICATION_STATE_OBSERVER), + data, reply, option); + if (error != NO_ERROR) { + APP_LOGE("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AppMgrProxy::UnregisterApplicationStateObserver( + const sptr &observer) +{ + if (!observer) { + APP_LOGE("observer null"); + return ERR_INVALID_VALUE; + } + APP_LOGD("UnregisterApplicationStateObserver start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteParcelable(observer->AsObject())) { + APP_LOGE("observer write failed."); + return ERR_FLATTEN_OBJECT; + } + + auto error = Remote()->SendRequest(static_cast(IAppMgr::Message::UNREGISTER_APPLICATION_STATE_OBSERVER), + data, reply, option); + if (error != NO_ERROR) { + APP_LOGE("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AppMgrProxy::GetForegroundApplications(std::vector &list) +{ + APP_LOGD("GetForegroundApplications start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + auto error = Remote()->SendRequest(static_cast(IAppMgr::Message::GET_FOREGROUND_APPLICATIONS), + data, reply, option); + if (error != NO_ERROR) { + APP_LOGE("GetForegroundApplications fail, error: %{public}d", error); + return error; + } + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("Read Parcelable infos failed."); + return ERR_INVALID_VALUE; + } + list.emplace_back(*info); + } + return reply.ReadInt32(); +} + +int AppMgrProxy::StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &bundleInfo) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("want write failed."); + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteParcelable(observer)) { + APP_LOGE("observer write failed."); + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteParcelable(&bundleInfo)) { + APP_LOGE("bundleInfo write failed."); + return ERR_FLATTEN_OBJECT; + } + int32_t ret = + Remote()->SendRequest(static_cast(IAppMgr::Message::START_USER_TEST_PROCESS), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + return ret; + } + return reply.ReadInt32(); +} + +void AppMgrProxy::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag) +{ + MessageParcel data; + MessageParcel reply; + if (!WriteInterfaceToken(data)) { + APP_LOGE("WriteInterfaceToken faild"); + return; + } + + if (!data.WriteInt32(recordId) || !data.WriteParcelable(&want) || !data.WriteString(flag)) { + APP_LOGE("want write failed."); + return; + } + + if (!SendTransactCmd(IAppMgr::Message::SCHEDULE_ACCEPT_WANT_DONE, data, reply)) { + APP_LOGE("SendTransactCmd faild"); + return; + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cba183d4fc7c3aa74f38820b3861ca854f222636 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_stub.h" + +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +#include "ability_info.h" +#include "app_log_wrapper.h" +#include "app_mgr_proxy.h" +#include "app_scheduler_interface.h" +#include "appexecfwk_errors.h" +#include "bytrace.h" +#include "iapp_state_callback.h" +#include "want.h" +#include "bundle_info.h" + +namespace OHOS { +namespace AppExecFwk { +AppMgrStub::AppMgrStub() +{ + memberFuncMap_[static_cast(IAppMgr::Message::APP_ATTACH_APPLICATION)] = + &AppMgrStub::HandleAttachApplication; + memberFuncMap_[static_cast(IAppMgr::Message::APP_APPLICATION_FOREGROUNDED)] = + &AppMgrStub::HandleApplicationForegrounded; + memberFuncMap_[static_cast(IAppMgr::Message::APP_APPLICATION_BACKGROUNDED)] = + &AppMgrStub::HandleApplicationBackgrounded; + memberFuncMap_[static_cast(IAppMgr::Message::APP_APPLICATION_TERMINATED)] = + &AppMgrStub::HandleApplicationTerminated; + memberFuncMap_[static_cast(IAppMgr::Message::APP_CHECK_PERMISSION)] = + &AppMgrStub::HandleCheckPermission; + memberFuncMap_[static_cast(IAppMgr::Message::APP_ABILITY_CLEANED)] = + &AppMgrStub::HandleAbilityCleaned; + memberFuncMap_[static_cast(IAppMgr::Message::APP_GET_MGR_INSTANCE)] = &AppMgrStub::HandleGetAmsMgr; + memberFuncMap_[static_cast(IAppMgr::Message::APP_CLEAR_UP_APPLICATION_DATA)] = + &AppMgrStub::HandleClearUpApplicationData; + memberFuncMap_[static_cast(IAppMgr::Message::APP_IS_BACKGROUND_RUNNING_RESTRICTED)] = + &AppMgrStub::HandleIsBackgroundRunningRestricted; + memberFuncMap_[static_cast(IAppMgr::Message::APP_GET_ALL_RUNNING_PROCESSES)] = + &AppMgrStub::HandleGetAllRunningProcesses; + memberFuncMap_[static_cast(IAppMgr::Message::APP_GET_RUNNING_PROCESSES_BY_USER_ID)] = + &AppMgrStub::HandleGetProcessRunningInfosByUserId; + memberFuncMap_[static_cast(IAppMgr::Message::APP_SET_APP_FREEZING_TIME)] = + &AppMgrStub::HandleSetAppFreezingTime; + memberFuncMap_[static_cast(IAppMgr::Message::APP_GET_APP_FREEZING_TIME)] = + &AppMgrStub::HandleGetAppFreezingTime; + memberFuncMap_[static_cast(IAppMgr::Message::APP_GET_SYSTEM_MEMORY_ATTR)] = + &AppMgrStub::HandleGetSystemMemoryAttr; + memberFuncMap_[static_cast(IAppMgr::Message::APP_ADD_ABILITY_STAGE_INFO_DONE)] = + &AppMgrStub::HandleAddAbilityStageDone; + memberFuncMap_[static_cast(IAppMgr::Message::STARTUP_RESIDENT_PROCESS)] = + &AppMgrStub::HandleStartupResidentProcess; + memberFuncMap_[static_cast(IAppMgr::Message::REGISTER_APPLICATION_STATE_OBSERVER)] = + &AppMgrStub::HandleRegisterApplicationStateObserver; + memberFuncMap_[static_cast(IAppMgr::Message::UNREGISTER_APPLICATION_STATE_OBSERVER)] = + &AppMgrStub::HandleUnregisterApplicationStateObserver; + memberFuncMap_[static_cast(IAppMgr::Message::GET_FOREGROUND_APPLICATIONS)] = + &AppMgrStub::HandleGetForegroundApplications; + memberFuncMap_[static_cast(IAppMgr::Message::START_USER_TEST_PROCESS)] = + &AppMgrStub::HandleStartUserTestProcess; + memberFuncMap_[static_cast(IAppMgr::Message::SCHEDULE_ACCEPT_WANT_DONE)] = + &AppMgrStub::HandleScheduleAcceptWantDone; +} + +AppMgrStub::~AppMgrStub() +{ + memberFuncMap_.clear(); +} + +int AppMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("AppMgrStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = AppMgrStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr client = data.ReadParcelable(); + AttachApplication(client); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleApplicationForegrounded(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ApplicationForegrounded(data.ReadInt32()); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleApplicationBackgrounded(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ApplicationBackgrounded(data.ReadInt32()); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleApplicationTerminated(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ApplicationTerminated(data.ReadInt32()); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleCheckPermission(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + int32_t recordId = data.ReadInt32(); + std::string permission = data.ReadString(); + int32_t result = CheckPermission(recordId, permission); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleAbilityCleaned(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + AbilityCleaned(token); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleGetAmsMgr(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + int32_t result = NO_ERROR; + sptr amsMgr = GetAmsMgr(); + if (!amsMgr) { + APP_LOGE("abilitymgr instance is nullptr"); + result = ERR_NO_INIT; + } else { + if (!reply.WriteParcelable(amsMgr->AsObject())) { + APP_LOGE("failed to reply abilitymgr instance to client, for write parcel error"); + result = ERR_APPEXECFWK_PARCEL_ERROR; + } + } + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleClearUpApplicationData(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::string bundleName = data.ReadString(); + int32_t result = ClearUpApplicationData(bundleName); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleIsBackgroundRunningRestricted(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::string bundleName = data.ReadString(); + int32_t result = IsBackgroundRunningRestricted(bundleName); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleGetAllRunningProcesses(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::vector info; + auto result = GetAllRunningProcesses(info); + reply.WriteInt32(info.size()); + for (auto &it : info) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int32_t AppMgrStub::HandleGetProcessRunningInfosByUserId(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + int32_t userId = data.ReadInt32(); + std::vector info; + auto result = GetProcessRunningInfosByUserId(info, userId); + reply.WriteInt32(info.size()); + for (auto &it : info) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int32_t AppMgrStub::HandleSetAppFreezingTime(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + SetAppFreezingTime(data.ReadInt32()); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleGetAppFreezingTime(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + int time = 0; + GetAppFreezingTime(time); + reply.WriteInt32(time); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + SystemMemoryAttr memoryInfo; + std::string strConfig; + data.ReadString(strConfig); + GetSystemMemoryAttr(memoryInfo, strConfig); + if (reply.WriteParcelable(&memoryInfo)) { + APP_LOGE("want write failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int32_t AppMgrStub::HandleAddAbilityStageDone(MessageParcel &data, MessageParcel &reply) +{ + int32_t recordId = data.ReadInt32(); + AddAbilityStageDone(recordId); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleStartupResidentProcess(MessageParcel &data, MessageParcel &reply) +{ + StartupResidentProcess(); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleRegisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply) +{ + auto callback = iface_cast(data.ReadParcelable()); + int32_t result = RegisterApplicationStateObserver(callback); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleUnregisterApplicationStateObserver(MessageParcel &data, MessageParcel &reply) +{ + auto callback = iface_cast(data.ReadParcelable()); + int32_t result = UnregisterApplicationStateObserver(callback); + reply.WriteInt32(result); + return NO_ERROR; +} + + +int32_t AppMgrStub::HandleGetForegroundApplications(MessageParcel &data, MessageParcel &reply) +{ + std::vector appStateDatas; + int32_t result = GetForegroundApplications(appStateDatas); + reply.WriteInt32(appStateDatas.size()); + for (auto &it : appStateDatas) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} + +int32_t AppMgrStub::HandleStartUserTestProcess(MessageParcel &data, MessageParcel &reply) +{ + AAFwk::Want *want = data.ReadParcelable(); + if (want == nullptr) { + APP_LOGE("want is nullptr"); + return ERR_INVALID_VALUE; + } + BundleInfo *bundleInfo = data.ReadParcelable(); + if (want == nullptr) { + APP_LOGE("want is nullptr"); + return ERR_INVALID_VALUE; + } + auto observer = data.ReadParcelable(); + int32_t result = StartUserTestProcess(*want, observer, *bundleInfo); + reply.WriteInt32(result); + delete want; + return result; +} + +int32_t AppMgrStub::RegisterApplicationStateObserver(const sptr &observer) +{ + return NO_ERROR; +} + +int32_t AppMgrStub::UnregisterApplicationStateObserver(const sptr &observer) +{ + return NO_ERROR; +} + +int32_t AppMgrStub::GetForegroundApplications(std::vector &list) +{ + return NO_ERROR; +} + +int32_t AppMgrStub::HandleScheduleAcceptWantDone(MessageParcel &data, MessageParcel &reply) +{ + auto recordId = data.ReadInt32(); + AAFwk::Want *want = data.ReadParcelable(); + if (want == nullptr) { + APP_LOGE("want is nullptr"); + return ERR_INVALID_VALUE; + } + auto flag = data.ReadString(); + + ScheduleAcceptWantDone(recordId, *want, flag); + return NO_ERROR; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_process_data.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_process_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aaa30c12a3445c5ea4da09afb2c818b5dadca9e6 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_process_data.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_process_data.h" + +#include "app_log_wrapper.h" + +#include "nlohmann/json.hpp" +#include "string_ex.h" +#include "parcel_macro.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +bool ReadFromParcelAppData(std::vector &appDatas, Parcel &parcel) +{ + int32_t appDataSize; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, appDataSize); + for (auto i = 0; i < appDataSize; i++) { + AppData appDataInfo; + std::string appName = Str16ToStr8(parcel.ReadString16()); + int32_t uid = parcel.ReadInt32(); + appDataInfo.appName = appName; + appDataInfo.uid = uid; + appDatas.emplace_back(appDataInfo); + } + return true; +} +} // namespace + +bool AppProcessData::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(processName)); + + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(appState)); + + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, pid); + + const auto appDataSize = static_cast(appDatas.size()); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, appDataSize); + for (auto i = 0; i < appDataSize; i++) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(appDatas[i].appName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, appDatas[i].uid); + } + + return true; +} + +bool AppProcessData::ReadFromParcel(Parcel &parcel) +{ + processName = Str16ToStr8(parcel.ReadString16()); + + appState = static_cast(parcel.ReadInt32()); + + pid = parcel.ReadInt32(); + + ReadFromParcelAppData(appDatas, parcel); + + return true; +} + +AppProcessData *AppProcessData::Unmarshalling(Parcel &parcel) +{ + AppProcessData *appProcessData = new (std::nothrow) AppProcessData(); + if (appProcessData && !appProcessData->ReadFromParcel(parcel)) { + APP_LOGW("failed, because ReadFromParcel failed"); + delete appProcessData; + appProcessData = nullptr; + } + return appProcessData; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_record_id.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_record_id.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1b5ab57051d17d3361a77274f74fad7caa68f80 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_record_id.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_record_id.h" +namespace OHOS { +namespace AppExecFwk { +int32_t AppRecordId::Create() +{ + // Make it atomic to avoid multi app creating concurrently. + static std::atomic_int id(0); + return ++id; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_resident_process_info.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_resident_process_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9242a24ac7a79b0a0f74fa4d6d0af068846e8ba8 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_resident_process_info.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_resident_process_info.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +AppResidentProcessInfo *AppResidentProcessInfo::Unmarshalling(Parcel &parcel) +{ + AppResidentProcessInfo *residentProcess = new (std::nothrow) OHOS::AppExecFwk::AppResidentProcessInfo(); + if (residentProcess && !residentProcess->ReadFromParcel(parcel)) { + delete residentProcess; + residentProcess = nullptr; + } + return residentProcess; +} + +bool AppResidentProcessInfo::Marshalling(Parcel &parcel) const +{ + APP_LOGW("Marshalling"); + parcel.WriteBool(isKeepAliveApp_); + parcel.WriteInt32(abilityStage_.size()); + for (auto &info : abilityStage_) { + if (!parcel.WriteParcelable(&info)) { + return false; + } + } + return true; +} + +bool AppResidentProcessInfo::ReadFromParcel(Parcel &parcel) +{ + isKeepAliveApp_ = parcel.ReadBool(); + auto size = parcel.ReadInt32(); + for (int32_t i = 0; i < size; i++) { + std::unique_ptr hapModuleInfo(parcel.ReadParcelable()); + if (!hapModuleInfo) { + APP_LOGE("ReadParcelable failed"); + return false; + } + abilityStage_.emplace_back(*hapModuleInfo); + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5bcd6989b789f109092e2e1b75a7fcc814afd1b --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_scheduler_host.h" +#include "ability_info.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bytrace.h" +#include "ipc_types.h" + +namespace OHOS { +namespace AppExecFwk { +AppSchedulerHost::AppSchedulerHost() +{ + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_FOREGROUND_APPLICATION_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleForegroundApplication; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_BACKGROUND_APPLICATION_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleBackgroundApplication; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_TERMINATE_APPLICATION_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleTerminateApplication; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_LOWMEMORY_APPLICATION_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleLowMemory; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_SHRINK_MEMORY_APPLICATION_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleShrinkMemory; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_ABILITY_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleLaunchAbility; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_CLEAN_ABILITY_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleCleanAbility; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_APPLICATION_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleLaunchApplication; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_PROFILE_CHANGED_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleProfileChanged; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_CONFIGURATION_UPDATED)] = + &AppSchedulerHost::HandleScheduleConfigurationUpdated; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_PROCESS_SECURITY_EXIT_TRANSACTION)] = + &AppSchedulerHost::HandleScheduleProcessSecurityExit; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_ABILITY_STAGE_INFO)] = + &AppSchedulerHost::HandleScheduleAbilityStage; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_ACCEPT_WANT)] = + &AppSchedulerHost::HandleScheduleAcceptWant; +} + +AppSchedulerHost::~AppSchedulerHost() +{ + memberFuncMap_.clear(); +} + +int AppSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("AppSchedulerHost::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = AppSchedulerHost::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t AppSchedulerHost::HandleScheduleForegroundApplication(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ScheduleForegroundApplication(); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleBackgroundApplication(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ScheduleBackgroundApplication(); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleTerminateApplication(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ScheduleTerminateApplication(); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleLowMemory(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ScheduleLowMemory(); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleShrinkMemory(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ScheduleShrinkMemory(data.ReadInt32()); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleLaunchAbility(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::unique_ptr abilityInfo(data.ReadParcelable()); + if (!abilityInfo) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr token = data.ReadParcelable(); + ScheduleLaunchAbility(*abilityInfo, token); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleCleanAbility(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr token = data.ReadParcelable(); + ScheduleCleanAbility(token); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleLaunchApplication(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::unique_ptr launchData(data.ReadParcelable()); + std::unique_ptr config(data.ReadParcelable()); + if (!launchData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!config) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + ScheduleLaunchApplication(*launchData, *config); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleAbilityStage(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::unique_ptr abilityStage(data.ReadParcelable()); + if (!abilityStage) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + ScheduleAbilityStage(*abilityStage); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleProfileChanged(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::unique_ptr profile(data.ReadParcelable()); + if (!profile) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + ScheduleProfileChanged(*profile); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleConfigurationUpdated(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::unique_ptr configuration(data.ReadParcelable()); + if (!configuration) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + ScheduleConfigurationUpdated(*configuration); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleProcessSecurityExit(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + ScheduleProcessSecurityExit(); + return NO_ERROR; +} + +int32_t AppSchedulerHost::HandleScheduleAcceptWant(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + AAFwk::Want *want = data.ReadParcelable(); + if (want == nullptr) { + APP_LOGE("want is nullptr"); + return ERR_INVALID_VALUE; + } + auto moduleName = data.ReadString(); + ScheduleAcceptWant(*want, moduleName); + return NO_ERROR; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30f1b86ea73555958e4f7e567fd17a556e115aeb --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_scheduler_proxy.h" + +#include "app_log_wrapper.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +AppSchedulerProxy::AppSchedulerProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +bool AppSchedulerProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(AppSchedulerProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void AppSchedulerProxy::ScheduleForegroundApplication() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAppScheduler::Message::SCHEDULE_FOREGROUND_APPLICATION_TRANSACTION), + data, + reply, + option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleBackgroundApplication() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = + remote->SendRequest(static_cast(IAppScheduler::Message::SCHEDULE_BACKGROUND_APPLICATION_TRANSACTION), + data, + reply, + option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleTerminateApplication() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_TERMINATE_APPLICATION_TRANSACTION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleLowMemory() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_LOWMEMORY_APPLICATION_TRANSACTION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleShrinkMemory(const int32_t level) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteInt32(level); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_SHRINK_MEMORY_APPLICATION_TRANSACTION), + data, + reply, + option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&info); + data.WriteParcelable(token.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_ABILITY_TRANSACTION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleCleanAbility(const sptr &token) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_CLEAN_ABILITY_TRANSACTION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleLaunchApplication(const AppLaunchData &launchData, const Configuration &config) +{ + APP_LOGI("AppSchedulerProxy ScheduleLaunchApplication start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteParcelable(&launchData)) { + APP_LOGE("WriteParcelable launchData failed"); + return ; + } + + if (!data.WriteParcelable(&config)) { + APP_LOGE("WriteParcelable config failed"); + return ; + } + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_APPLICATION_TRANSACTION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + + APP_LOGI("AppSchedulerProxy ScheduleLaunchApplication end"); +} + +void AppSchedulerProxy::ScheduleAbilityStage(const HapModuleInfo &abilityStage) +{ + APP_LOGI("AppSchedulerProxy ScheduleAbilityStage start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteParcelable(&abilityStage)) { + return ; + } + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_ABILITY_STAGE_INFO), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGI("AppSchedulerProxy ScheduleAbilityStage end"); +} + +void AppSchedulerProxy::ScheduleProfileChanged(const Profile &profile) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&profile); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_PROFILE_CHANGED_TRANSACTION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleConfigurationUpdated(const Configuration &config) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&config); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_CONFIGURATION_UPDATED), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleProcessSecurityExit() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_PROCESS_SECURITY_EXIT_TRANSACTION), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void AppSchedulerProxy::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteParcelable(&want) || !data.WriteString(moduleName)) { + return; + } + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppScheduler::Message::SCHEDULE_ACCEPT_WANT), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_service_manager.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_service_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef8c513f7f671d4d761e60458eb6b9b55845aca9 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_service_manager.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_service_manager.h" + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "system_ability_definition.h" + +#include "app_mgr_constants.h" +#include "iservice_registry.h" + +namespace OHOS { +namespace AppExecFwk { +sptr AppServiceManager::GetAppMgrService() const +{ + sptr systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityMgr) { + return nullptr; + } + return systemAbilityMgr->GetSystemAbility(APP_MGR_SERVICE_ID); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_host.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_host.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a953aff5b962a590724a5b20502621b122e7785 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_host.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_state_callback_host.h" + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bytrace.h" +#include "ipc_types.h" +#include "iremote_object.h" + +#include "app_state_callback_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +AppStateCallbackHost::AppStateCallbackHost() +{ + memberFuncMap_[static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_STATE_CHANGED)] = + &AppStateCallbackHost::HandleOnAppStateChanged; + memberFuncMap_[static_cast(IAppStateCallback::Message::TRANSACT_ON_ABILITY_REQUEST_DONE)] = + &AppStateCallbackHost::HandleOnAbilityRequestDone; +} + +AppStateCallbackHost::~AppStateCallbackHost() +{ + memberFuncMap_.clear(); +} + +int AppStateCallbackHost::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("AppStateCallbackHost::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = AppStateCallbackHost::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +void AppStateCallbackHost::OnAbilityRequestDone(const sptr &, const AbilityState) +{ + APP_LOGD("called"); +} + +void AppStateCallbackHost::OnAppStateChanged(const AppProcessData &) +{ + APP_LOGD("called"); +} + +int32_t AppStateCallbackHost::HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnAppStateChanged(*processData); + return NO_ERROR; +} + +int32_t AppStateCallbackHost::HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + sptr obj = data.ReadParcelable(); + int32_t state = data.ReadInt32(); + OnAbilityRequestDone(obj, static_cast(state)); + return NO_ERROR; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d2a8eeb1fa38b347918bec77f5b05ca98b7445d --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_proxy.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_state_callback_proxy.h" + +#include "ipc_types.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +AppStateCallbackProxy::AppStateCallbackProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +bool AppStateCallbackProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(AppStateCallbackProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void AppStateCallbackProxy::OnAbilityRequestDone(const sptr &token, const AbilityState state) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(token.GetRefPtr()); + int32_t abilityState = static_cast(state); + data.WriteInt32(abilityState); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppStateCallback::Message::TRANSACT_ON_ABILITY_REQUEST_DONE), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void AppStateCallbackProxy::OnAppStateChanged(const AppProcessData &appProcessData) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&appProcessData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_STATE_CHANGED), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_state_data.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_state_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c32eb0f8952459eccf9be3abbaf51dd668592441 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_state_data.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_state_data.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +bool AppStateData::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString(bundleName) && parcel.WriteInt32(uid) && parcel.WriteInt32(state)); +} + +bool AppStateData::ReadFromParcel(Parcel &parcel) +{ + bundleName = parcel.ReadString(); + uid = parcel.ReadInt32(); + state = parcel.ReadInt32(); + + return true; +} + +AppStateData *AppStateData::Unmarshalling(Parcel &parcel) +{ + AppStateData *appStateData = new (std::nothrow) AppStateData(); + if (appStateData && !appStateData->ReadFromParcel(parcel)) { + APP_LOGW("appStateData failed, because ReadFromParcel failed"); + delete appStateData; + appStateData = nullptr; + } + return appStateData; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_task_info.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_task_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a81cd2c214cebd27a817659eccaffa4e00d5a44 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/app_task_info.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_task_info.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string &AppTaskInfo::GetName() const +{ + return appName_; +} + +const std::string &AppTaskInfo::GetProcessName() const +{ + return processName_; +} + +pid_t AppTaskInfo::GetPid() const +{ + return pid_; +} + +int32_t AppTaskInfo::GetRecordId() const +{ + return appRecordId_; +} + +void AppTaskInfo::SetName(const std::string &appName) +{ + appName_ = appName; +} + +void AppTaskInfo::SetProcessName(const std::string &processName) +{ + processName_ = processName; +} + +void AppTaskInfo::SetPid(const pid_t pid) +{ + pid_ = pid; +} + +void AppTaskInfo::SetRecordId(const int32_t appRecordId) +{ + appRecordId_ = appRecordId; +} + +bool AppTaskInfo::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString(appName_) && parcel.WriteString(processName_) && parcel.WriteInt32(pid_) && + parcel.WriteInt32(appRecordId_)); +} + +bool AppTaskInfo::ReadFromParcel(Parcel &parcel) +{ + return (parcel.ReadString(appName_) && parcel.ReadString(processName_) && parcel.ReadInt32(pid_) && + parcel.ReadInt32(appRecordId_)); +} + +AppTaskInfo *AppTaskInfo::Unmarshalling(Parcel &parcel) +{ + AppTaskInfo *appTaskInfo = new (std::nothrow) AppTaskInfo(); + if (appTaskInfo && !appTaskInfo->ReadFromParcel(parcel)) { + APP_LOGW("failed, because ReadFromParcel failed"); + delete appTaskInfo; + appTaskInfo = nullptr; + } + return appTaskInfo; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/application_state_observer_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/application_state_observer_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00f373e13e1c4fae223a14c9a8c6a78824556ffc --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/application_state_observer_proxy.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_state_observer_proxy.h" + +#include "ipc_types.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +ApplicationStateObserverProxy::ApplicationStateObserverProxy( + const sptr &impl) : IRemoteProxy(impl) +{} + +bool ApplicationStateObserverProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(ApplicationStateObserverProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void ApplicationStateObserverProxy::OnForegroundApplicationChanged(const AppStateData &appStateData) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&appStateData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnAbilityStateChanged(const AbilityStateData &abilityStateData) +{ + APP_LOGD("OnAbilityStateChanged begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&abilityStateData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_ABILITY_STATE_CHANGED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnExtensionStateChanged(const AbilityStateData &abilityStateData) +{ + APP_LOGD("OnExtensionStateChanged begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&abilityStateData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_EXTENSION_STATE_CHANGED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnProcessCreated(const ProcessData &processData) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&processData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_CREATED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnProcessDied(const ProcessData &processData) +{ + APP_LOGD("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&processData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_DIED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("end"); +} + +void ApplicationStateObserverProxy::OnApplicationStateChanged(const AppStateData &appStateData) +{ + APP_LOGI("begin"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteParcelable(&appStateData); + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IApplicationStateObserver::Message::TRANSACT_ON_APPLICATION_STATE_CHANGED), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGI("end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/application_state_observer_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/application_state_observer_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f168db54b02805dcb310664e070b54a2286f5f43 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/application_state_observer_stub.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_state_observer_stub.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { + +ApplicationStateObserverStub::ApplicationStateObserverStub() +{ + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED)] = + &ApplicationStateObserverStub::HandleOnForegroundApplicationChanged; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_ABILITY_STATE_CHANGED)] = + &ApplicationStateObserverStub::HandleOnAbilityStateChanged; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_EXTENSION_STATE_CHANGED)] = + &ApplicationStateObserverStub::HandleOnExtensionStateChanged; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_CREATED)] = + &ApplicationStateObserverStub::HandleOnProcessCreated; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_PROCESS_DIED)] = + &ApplicationStateObserverStub::HandleOnProcessDied; + memberFuncMap_[static_cast( + IApplicationStateObserver::Message::TRANSACT_ON_APPLICATION_STATE_CHANGED)] = + &ApplicationStateObserverStub::HandleOnApplicationStateChanged; +} + +ApplicationStateObserverStub::~ApplicationStateObserverStub() +{ + memberFuncMap_.clear(); +} + +int ApplicationStateObserverStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("ApplicationStateObserverStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = ApplicationStateObserverStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +void ApplicationStateObserverStub::OnForegroundApplicationChanged(const AppStateData &appStateData) +{} + +void ApplicationStateObserverStub::OnAbilityStateChanged(const AbilityStateData &abilityStateData) +{} + +void ApplicationStateObserverStub::OnExtensionStateChanged(const AbilityStateData &abilityStateData) +{} + +void ApplicationStateObserverStub::OnProcessCreated(const ProcessData &processData) +{} + +void ApplicationStateObserverStub::OnProcessDied(const ProcessData &processData) +{} + +void ApplicationStateObserverStub::OnApplicationStateChanged(const AppStateData &appStateData) +{} + +int32_t ApplicationStateObserverStub::HandleOnForegroundApplicationChanged(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnForegroundApplicationChanged(*processData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnAbilityStateChanged(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr abilityStateData(data.ReadParcelable()); + if (!abilityStateData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnAbilityStateChanged(*abilityStateData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnExtensionStateChanged(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr abilityStateData(data.ReadParcelable()); + if (!abilityStateData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnExtensionStateChanged(*abilityStateData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnProcessCreated(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnProcessCreated(*processData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnProcessDied(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnProcessDied(*processData); + return NO_ERROR; +} + +int32_t ApplicationStateObserverStub::HandleOnApplicationStateChanged(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr processData(data.ReadParcelable()); + if (!processData) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + OnApplicationStateChanged(*processData); + return NO_ERROR; +} + +void ApplicationStateObserverRecipient::OnRemoteDied(const wptr &__attribute__((unused)) remote) +{ + APP_LOGE("ApplicationStateObserverRecipient On remote died."); + if (handler_) { + handler_(remote); + } +} + +ApplicationStateObserverRecipient::ApplicationStateObserverRecipient(RemoteDiedHandler handler) : handler_(handler) +{} + +ApplicationStateObserverRecipient::~ApplicationStateObserverRecipient() +{} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp b/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp new file mode 100755 index 0000000000000000000000000000000000000000..85b24de01b3265375cd9c3f38ae671930de67da1 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "configuration.h" + +#include + +#include "app_log_wrapper.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +using json = nlohmann::json; +Configuration::Configuration() +{} + +Configuration::Configuration(const Configuration &other) : defaultDisplayId_(other.defaultDisplayId_) +{ + configParameter_ = other.configParameter_; +} + +Configuration& Configuration::operator= (const Configuration &other) +{ + if (this == &other) { + return *this; + } + + defaultDisplayId_ = other.defaultDisplayId_; + configParameter_.clear(); + configParameter_ = other.configParameter_; + return *this; +} + +Configuration::~Configuration() +{} + +bool Configuration::MakeTheKey(std::string &getKey, int id, const std::string ¶m) const +{ + if (param.empty()) { + return false; + } + + if (std::find(ConfigurationInner::SystemConfigurationKeyStore.begin(), + ConfigurationInner::SystemConfigurationKeyStore.end(), param) == + ConfigurationInner::SystemConfigurationKeyStore.end()) { + return false; + } + + getKey.clear(); + getKey += std::to_string(id); + getKey += ConfigurationInner::CONNECTION_SYMBOL; + getKey += param; + APP_LOGW(" getKey [%{public}s]", getKey.c_str()); + + return true; +} + +bool Configuration::AddItem(int displayId, const std::string &key, const std::string &value) +{ + if (key.empty() || value.empty()) { + return false; + } + + std::string getKey; + if (!MakeTheKey(getKey, displayId, key)) { + return false; + } + + configParameter_[getKey] = value; + return true; +} + +std::string Configuration::GetItem(int displayId, const std::string &key) const +{ + if (key.empty()) { + return ConfigurationInner::EMPTY_STRING; + } + + std::string getKey; + if (!MakeTheKey(getKey, displayId, key)) { + return ConfigurationInner::EMPTY_STRING; + } + + auto iter = configParameter_.find(getKey); + if (iter != configParameter_.end()) { + return iter->second; + } + + return ConfigurationInner::EMPTY_STRING; +} + +int Configuration::GetItemSize() const +{ + return configParameter_.size(); +} + +void Configuration::GetAllKey(std::vector &keychain) const +{ + keychain.clear(); + for (const auto &it :configParameter_) { + keychain.push_back(it.first); + } +} + +std::string Configuration::GetValue(const std::string &key) const +{ + auto iter = configParameter_.find(key); + if (iter != configParameter_.end()) { + return iter->second; + } + + return ConfigurationInner::EMPTY_STRING; +} + +void Configuration::CompareDifferent(std::vector &diffKeyV, const Configuration &other) +{ + if (other.GetItemSize() == 0) { + return; + } + + diffKeyV.clear(); + std::vector otherk; + other.GetAllKey(otherk); + for (const auto &iter : otherk) { + APP_LOGW(" iter : [%{public}s] | Val: [%{public}s]", iter.c_str(), other.GetValue(iter).c_str()); + // Insert new content directly + auto pair = configParameter_.insert(std::make_pair(iter, other.GetValue(iter))); + if (pair.second) { + diffKeyV.push_back(iter); // One of the changes this time + continue; + } + // Compare what you already have + if (!other.GetValue(iter).empty() && other.GetValue(iter) != GetValue(iter)) { + diffKeyV.push_back(iter); + } + } +} + +void Configuration::Merge(const std::vector &diffKeyV, const Configuration &other) +{ + if (diffKeyV.empty()) { + return; + } + for (const auto &mergeItemKey : diffKeyV) { + auto myItem = GetValue(mergeItemKey); + auto otherItem = other.GetValue(mergeItemKey); + // myItem possible empty + if (!otherItem.empty() && otherItem != myItem) { + configParameter_[mergeItemKey] = otherItem; + } + } +} + +int Configuration::RemoveItem(int displayId, const std::string &key) +{ + if (key.empty()) { + return 0; + } + + std::string getKey; + if (!MakeTheKey(getKey, displayId, key)) { + return 0; + } + + return configParameter_.erase(getKey); +} + +bool Configuration::AddItem(const std::string &key, const std::string &value) +{ + return AddItem(defaultDisplayId_, key, value); +} + +std::string Configuration::GetItem(const std::string &key) const +{ + return GetItem(defaultDisplayId_, key); +} + +int Configuration::RemoveItem(const std::string &key) +{ + return RemoveItem(defaultDisplayId_, key); +} + +const std::string& Configuration::GetName() const +{ + json configArray(configParameter_); + toStrintg_ = configArray.dump(); + return toStrintg_; +} + +bool Configuration::ReadFromParcel(Parcel &parcel) +{ + APP_LOGW("ReadFromParcel"); + defaultDisplayId_ = parcel.ReadInt32(); + int32_t configSize = parcel.ReadInt32(); + std::vector keys; + std::vector values; + keys.clear(); + values.clear(); + parcel.ReadStringVector(&keys); + parcel.ReadStringVector(&values); + + std::string key; + std::string val; + for (int32_t i = 0; i < configSize; i++) { + key = keys.at(i); + val = values.at(i); + configParameter_.emplace(key, val); + } + return true; +} + +Configuration *Configuration::Unmarshalling(Parcel &parcel) +{ + Configuration *Configuration = new (std::nothrow) OHOS::AppExecFwk::Configuration(); + if (Configuration && !Configuration->ReadFromParcel(parcel)) { + delete Configuration; + Configuration = nullptr; + } + return Configuration; +} + +bool Configuration::Marshalling(Parcel &parcel) const +{ + APP_LOGW("Marshalling"); + std::vector keys; + std::vector values; + keys.clear(); + values.clear(); + parcel.WriteInt32(defaultDisplayId_); + parcel.WriteInt32(configParameter_.size()); + for (const auto &config : configParameter_) { + keys.emplace_back(config.first); + values.emplace_back(config.second); + } + + parcel.WriteStringVector(keys); + parcel.WriteStringVector(values); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/priority_object.cpp b/interfaces/innerkits/app_manager/src/appmgr/priority_object.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23298807f98188427dae97f0b8309d17e71e7609 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/priority_object.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "priority_object.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +pid_t PriorityObject::GetPid() const +{ + return pid_; +} + +int32_t PriorityObject::GetMaxAdj() const +{ + return maxAdj_; +} + +int32_t PriorityObject::GetCurAdj() const +{ + return curAdj_; +} + +int32_t PriorityObject::GetCurCgroup() const +{ + return curCgroup_; +} + +int32_t PriorityObject::GetTimeLevel() const +{ + return timeLevel_; +} + +bool PriorityObject::GetVisibleStatus() const +{ + return visibleStatus_; +} + +bool PriorityObject::GetPerceptibleStatus() const +{ + return perceptibleStatus_; +} + +void PriorityObject::SetPid(const pid_t pid) +{ + pid_ = pid; +} + +void PriorityObject::SetMaxAdj(const int32_t maxAdj) +{ + maxAdj_ = maxAdj; +} + +void PriorityObject::SetCurAdj(const int32_t curAdj) +{ + curAdj_ = curAdj; +} + +void PriorityObject::SetCurCgroup(const int32_t curCgroup) +{ + curCgroup_ = curCgroup; +} + +void PriorityObject::SetTimeLevel(const int32_t timeLevel) +{ + timeLevel_ = timeLevel; +} + +void PriorityObject::SetVisibleStatus(bool status) +{ + visibleStatus_ = status; +} + +void PriorityObject::SetPerceptibleStatus(bool status) +{ + perceptibleStatus_ = status; +} + +bool PriorityObject::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(pid_)) { + return false; + } + if (!parcel.WriteInt32(maxAdj_)) { + return false; + } + if (!parcel.WriteInt32(curAdj_)) { + return false; + } + if (!parcel.WriteInt32(curCgroup_)) { + return false; + } + if (!parcel.WriteInt32(timeLevel_)) { + return false; + } + return true; +} + +bool PriorityObject::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadInt32(pid_)) { + return false; + } + if (!parcel.ReadInt32(maxAdj_)) { + return false; + } + if (!parcel.ReadInt32(curAdj_)) { + return false; + } + if (!parcel.ReadInt32(curCgroup_)) { + return false; + } + if (!parcel.ReadInt32(timeLevel_)) { + return false; + } + return true; +} + +PriorityObject *PriorityObject::Unmarshalling(Parcel &parcel) +{ + PriorityObject *priorityObject = new (std::nothrow) PriorityObject(); + if (priorityObject && !priorityObject->ReadFromParcel(parcel)) { + APP_LOGW("failed, because ReadFromParcel failed"); + delete priorityObject; + priorityObject = nullptr; + } + return priorityObject; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/process_data.cpp b/interfaces/innerkits/app_manager/src/appmgr/process_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d44edbf0e80a102b0c86a05c19adec87df946f6b --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/process_data.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "process_data.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +bool ProcessData::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString(bundleName) && parcel.WriteInt32(pid) && parcel.WriteInt32(uid)); +} + +bool ProcessData::ReadFromParcel(Parcel &parcel) +{ + bundleName = parcel.ReadString(); + pid = parcel.ReadInt32(); + uid = parcel.ReadInt32(); + + return true; +} + +ProcessData *ProcessData::Unmarshalling(Parcel &parcel) +{ + ProcessData *processData = new (std::nothrow) ProcessData(); + if (processData && !processData->ReadFromParcel(parcel)) { + APP_LOGW("processData failed, because ReadFromParcel failed"); + delete processData; + processData = nullptr; + } + return processData; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp b/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de768ed07722392f5b13dca05375697796cc0c42 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "process_info.h" + +#include "app_log_wrapper.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +ProcessInfo::ProcessInfo(const std::string &name, const pid_t &pid) : processName_(name), pid_(pid) +{} + +/** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ +bool ProcessInfo::ReadFromParcel(Parcel &parcel) +{ + processName_ = Str16ToStr8(parcel.ReadString16()); + pid_ = parcel.ReadInt32(); + return true; +} + +/** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ +ProcessInfo *ProcessInfo::Unmarshalling(Parcel &parcel) +{ + ProcessInfo *processInfo = new (std::nothrow) ProcessInfo(); + if (processInfo && !processInfo->ReadFromParcel(parcel)) { + APP_LOGE("ProcessInfo::Unmarshalling ReadFromParcel failed"); + delete processInfo; + processInfo = nullptr; + } + return processInfo; +} + +/** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ +bool ProcessInfo::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString16(Str8ToStr16(processName_)) && parcel.WriteInt32(pid_)); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/profile.cpp b/interfaces/innerkits/app_manager/src/appmgr/profile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8025773b660f3fca3ee371847eed5886efa28dbf --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/profile.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "profile.h" + +#include "string_ex.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +Profile::Profile(const std::string &name) : profileName_(name) +{} + +bool Profile::ReadFromParcel(Parcel &parcel) +{ + profileName_ = Str16ToStr8(parcel.ReadString16()); + + return true; +} + +Profile *Profile::Unmarshalling(Parcel &parcel) +{ + Profile *profile = new (std::nothrow) Profile(); + if (profile && !profile->ReadFromParcel(parcel)) { + APP_LOGW("failed, because ReadFromParcel failed"); + delete profile; + profile = nullptr; + } + return profile; +} + +bool Profile::Marshalling(Parcel &parcel) const +{ + return (parcel.WriteString16(Str8ToStr16(profileName_))); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/start_specified_ability_response_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/start_specified_ability_response_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0c3bdccc4dd9e80d3b71eb2a7a1af493b368820 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/start_specified_ability_response_proxy.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "start_specified_ability_response_proxy.h" +#include "ipc_types.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +StartSpecifiedAbilityResponseProxy::StartSpecifiedAbilityResponseProxy(const sptr &impl) + : IRemoteProxy(impl) +{} + +bool StartSpecifiedAbilityResponseProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(StartSpecifiedAbilityResponseProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void StartSpecifiedAbilityResponseProxy::OnAcceptWantResponse( + const AAFwk::Want &want, const std::string &flag) +{ + APP_LOGD("On accept want by proxy."); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + if (!data.WriteParcelable(&want) || !data.WriteString(flag)) { + APP_LOGE("Write data failed."); + return; + } + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote is nullptr."); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IStartSpecifiedAbilityResponse::Message::ON_ACCEPT_WANT_RESPONSE), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} + +void StartSpecifiedAbilityResponseProxy::OnTimeoutResponse(const AAFwk::Want &want) +{ + APP_LOGD("On timeout response by proxy."); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("Write data failed."); + return; + } + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote is nullptr."); + return; + } + int32_t ret = remote->SendRequest(static_cast( + IStartSpecifiedAbilityResponse::Message::ON_TIMEOUT_RESPONSE), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/start_specified_ability_response_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/start_specified_ability_response_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3749d5ff135bf22f4677b1e4d7e7e4c88eee6121 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/start_specified_ability_response_stub.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "start_specified_ability_response_stub.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std::placeholders; +StartSpecifiedAbilityResponseStub::StartSpecifiedAbilityResponseStub() +{ + auto a = std::bind(&StartSpecifiedAbilityResponseStub::HandleOnAcceptWantResponse, this, _1, _2); + responseFuncMap_.emplace(static_cast( + IStartSpecifiedAbilityResponse::Message::ON_ACCEPT_WANT_RESPONSE), std::move(a)); + auto b = std::bind(&StartSpecifiedAbilityResponseStub::HandleOnTimeoutResponse, this, _1, _2); + responseFuncMap_.emplace(static_cast( + IStartSpecifiedAbilityResponse::Message::ON_TIMEOUT_RESPONSE), std::move(b)); +} + +StartSpecifiedAbilityResponseStub::~StartSpecifiedAbilityResponseStub() +{ + responseFuncMap_.clear(); +} + +int32_t StartSpecifiedAbilityResponseStub::HandleOnAcceptWantResponse(MessageParcel &data, MessageParcel &reply) +{ + AAFwk::Want *want = data.ReadParcelable(); + if (want == nullptr) { + APP_LOGE("want is nullptr"); + return ERR_INVALID_VALUE; + } + + auto flag = Str16ToStr8(data.ReadString16()); + OnAcceptWantResponse(*want, flag); + return NO_ERROR; +} + +int32_t StartSpecifiedAbilityResponseStub::HandleOnTimeoutResponse(MessageParcel &data, MessageParcel &reply) +{ + AAFwk::Want *want = data.ReadParcelable(); + if (want == nullptr) { + APP_LOGE("want is nullptr"); + return ERR_INVALID_VALUE; + } + + OnTimeoutResponse(*want); + return NO_ERROR; +} + +int StartSpecifiedAbilityResponseStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("StartSpecifiedAbilityResponseStub::OnReceived, code = %{public}d, flags= %{public}d.", + code, option.GetFlags()); + std::u16string descriptor = StartSpecifiedAbilityResponseStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = responseFuncMap_.find(code); + if (itFunc != responseFuncMap_.end()) { + auto func = itFunc->second; + if (func != nullptr) { + return func(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/base/BUILD.gn b/interfaces/innerkits/base/BUILD.gn index 071b0770b7a159e066602a36adb10ad79aecb53e..c41394fc0457daf3357f2ac9b6d7703ae1e986ee 100644 --- a/interfaces/innerkits/base/BUILD.gn +++ b/interfaces/innerkits/base/BUILD.gn @@ -56,5 +56,5 @@ ohos_shared_library("base") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/innerkits/dataobs_manager/BUILD.gn b/interfaces/innerkits/dataobs_manager/BUILD.gn index 7ed2457436958af100b87976b9b6861ff1754c47..28daad3e8af2c41c3a54e5c0d10277765fbb7618 100644 --- a/interfaces/innerkits/dataobs_manager/BUILD.gn +++ b/interfaces/innerkits/dataobs_manager/BUILD.gn @@ -57,5 +57,5 @@ ohos_shared_library("dataobs_manager") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/innerkits/form_manager/BUILD.gn b/interfaces/innerkits/form_manager/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..73d6404cc3ec3d18192628863b833f8fd068f5bd --- /dev/null +++ b/interfaces/innerkits/form_manager/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("formmgr_sdk_config") { + visibility = [ ":*" ] + include_dirs = [ + "include/", + "//third_party/json/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/appexecfwk/standard/common/log/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_shared_library("form_manager") { + sources = [ + "src/form_host_proxy.cpp", + "src/form_host_stub.cpp", + "src/form_js_info.cpp", + "src/form_mgr_proxy.cpp", + "src/form_mgr_stub.cpp", + "src/form_provider_data.cpp", + "src/form_provider_info.cpp", + "src/form_provider_proxy.cpp", + "src/form_provider_stub.cpp", + "src/form_supply_proxy.cpp", + "src/form_supply_stub.cpp", + "src/provider_connect_proxy.cpp", + "src/provider_connect_stub.cpp", + ] + + public_configs = [ + ":formmgr_sdk_config", + "${services_path}/formmgr:formmgr_config", + ] + + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${innerkits_path}/want:want", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + + subsystem_name = "aafwk" + part_name = "form_runtime" +} diff --git a/interfaces/innerkits/form_manager/include/form_constants.h b/interfaces/innerkits/form_manager/include/form_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..796d214f81f2ffa58b6aaec3babb59ee898d9bcd --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_constants.h @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_CONSTANTS_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_CONSTANTS_H + +#include +#include + +namespace OHOS { +namespace AppExecFwk { +namespace Constants { + const std::string PERMISSION_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; + const std::string PARAM_FORM_IDENTITY_KEY = "ohos.extra.param.key.form_identity"; + const std::string PARAM_FORM_CALLING_IDENTITY_KEY = "ohos.extra.param.key.form_calling_identity"; + const std::string PARAM_MODULE_NAME_KEY = "ohos.extra.param.key.module_name"; + const std::string PARAM_FORM_NAME_KEY = "ohos.extra.param.key.form_name"; + const std::string PARAM_FORM_DIMENSION_KEY = "ohos.extra.param.key.form_dimension"; + const std::string PARAM_MESSAGE_KEY = "ohos.extra.param.key.message"; + const std::string PARAM_FORM_TEMPORARY_KEY = "ohos.extra.param.key.form_temporary"; + const int32_t ONE_HOST_MAX_FORM_SIZE = 256; + const std::string RECREATE_FORM_KEY = "ohos.extra.param.key.recreate"; + const std::string PARAM_FORM_CUSTOMIZE_KEY = "ohos.extra.param.key.form_customize"; + const std::string PARAM_FORM_ORIENTATION_KEY = "ohos.extra.param.key.form_orientation"; + const int32_t ORIENTATION_PORTRAIT = 1; + const int32_t ORIENTATION_LANDSCAPE = 2; + const std::string PARAM_FORM_ABILITY_NAME_KEY = "abilityName"; + const std::string PARAM_FORM_USER_ID = "ohos.extra.param.key.form_user_id"; + const std::string KEY_IS_TIMER = "isTimerRefresh"; + const std::string SYSTEM_PARAM_FORM_UPDATE_TIME = "persist.sys.fms.form.update.time"; + const std::string SYSTEM_PARAM_FORM_REFRESH_MIN_TIME = "persist.sys.fms.form.refresh.min.time"; + const std::string ACTION_UPDATEATTIMER = "form_update_at_timer"; + const std::string KEY_WAKEUP_TIME = "wakeUpTime"; + const std::string KEY_ACTION_TYPE = "form_update_action_type"; + const int TYPE_RESET_LIMIT = 1; + const int TYPE_STATIC_UPDATE = 2; + const int TYPE_DYNAMIC_UPDATE = 3; + const long ABS_REFRESH_MS = 2500; + + // The form events type which means that the form becomes visible. + const int32_t FORM_VISIBLE = 1; + // The form events type which means that the form becomes invisible. + const int32_t FORM_INVISIBLE = 2; + + // The default user id + const int32_t DEFAULT_USER_ID = 0; + + // The max uid of system app. + const int32_t MAX_SYSTEM_APP_UID = 10000; + + const int MAX_HOUR = 23; + const int MAX_MININUTE = 59; + const int MAX_SECOND = 60; + const int MIN_TIME = 0; + const int HOUR_PER_DAY = 24; + const int MIN_PER_HOUR = 60; + const long TIME_1000 = 1000; + const long TIME_1000000 = 1000000; + const long TIME_CONVERSION = 30 * 60 * TIME_1000; + const int MIN_CONFIG_DURATION = 1; // 1 means 30 min + const int MAX_CONFIG_DURATION = 2 * 24 * 7; // one week + const long MIN_PERIOD = MIN_CONFIG_DURATION * TIME_CONVERSION; // 30 min in ms unit + const long MAX_PERIOD = MAX_CONFIG_DURATION * TIME_CONVERSION; // 1 week in ms unit + const long ABS_TIME = 5 * TIME_1000; // 5s abs time + const int WORK_POOL_SIZE = 4; + const std::string TIME_DELIMETER = ":"; + const int UPDATE_AT_CONFIG_COUNT = 2; + + const int LIMIT_COUNT = 50; + const int MIN_NEXT_TIME = 300; // seconds + + // The max retry times of reconnection. + const int32_t MAX_RETRY_TIME = 30; + // The time interval between reconnections(milliseconds). + const int32_t SLEEP_TIME = 1000; + + const int64_t MS_PER_SECOND = 1000; + + // form host bundlename + const std::string PARAM_FORM_HOST_BUNDLENAME_KEY = "form_host_bundlename"; + + // form manager service bundlename + const std::string PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY = "form_manager_service_bundlename"; + + // PROVIDER_FLAG false:ProviderFormInfo is null;true: ProviderFormInfo not null + const std::string PROVIDER_FLAG = "provider_flag"; + const std::string FORM_CONNECT_ID = "form_connect_id"; + const std::string FORM_SUPPLY_INFO = "form_supply_info"; + + // the delimiter between bundleName and abilityName + const std::string NAME_DELIMITER = "::"; + + const std::string PARAM_FORM_ADD_COUNT = "form.add.count"; + + const size_t MAX_LAYOUT = 8; + const std::map DIMENSION_MAP = { + {1, "1*2"}, + {2, "2*2"}, + {3, "2*4"}, + {4, "4*4"}, + }; + const int MAX_FORMS = 512; + const int MAX_RECORD_PER_APP = 256; + const int MAX_TEMP_FORMS = 256; + const int MAX_FORM_DATA_SIZE = 1024; + + const int NOT_IN_RECOVERY = 0; + const int RECOVER_FAIL = 1; + const int IN_RECOVERING = 2; + + const int FLAG_HAS_OBJECT = 1; + const int FLAG_NO_OBJECT = 0; + + const int DEATH_RECIPIENT_FLAG = 0; + const int MAX_VISIBLE_NOTIFY_LIST = 32; + + const std::string ACQUIRE_TYPE = "form_acquire_form"; + const int ACQUIRE_TYPE_CREATE_FORM = 1; + const int ACQUIRE_TYPE_RECREATE_FORM = 2; + + const int DELETE_FORM = 3; + const int RELEASE_FORM = 8; + const int RELEASE_CACHED_FORM = 9; + + const int64_t INVALID_UDID_HASH = 0L; + + enum class FormMgrMessage { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for add form (3001) + FORM_MGR_ADD_FORM = 3001, + + // ipc id for delete form (3002) + FORM_MGR_DELETE_FORM, + + // ipc id for form done release form (3003) + FORM_MGR_RELEASE_FORM, + + // ipc id for connecting update form (3004) + FORM_MGR_UPDATE_FORM, + + // ipc id for form visible notify (3005) + FORM_MGR_NOTIFY_FORM_VISIBLE, + + // ipc id for form invisible notify (3006) + FORM_MGR_NOTIFY_FORM_INVISIBLE, + + // ipc id for refreshing data cache (3007) + FORM_MGR_CAST_TEMP_FORM, + + // ipc id 2001-3000 for tools + // ipc id for dumping state (2001) + FORM_MGR_DUMP_STATE = 2001, + }; +} // namespace Constants +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_CONSTANTS_H diff --git a/interfaces/innerkits/form_manager/include/form_death_callback.h b/interfaces/innerkits/form_manager/include/form_death_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..795d7f8f19cff4f511293e586ecc50074eb2c7b9 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_death_callback.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_DEATH_CALLBACK_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_DEATH_CALLBACK_H + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief The form death callback. + */ +class FormDeathCallback { +public: + virtual void OnDeathReceived() = 0; + virtual void OnReconnectFailed() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_DEATH_CALLBACK_H diff --git a/interfaces/innerkits/form_manager/include/form_host_interface.h b/interfaces/innerkits/form_manager/include/form_host_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..07812871c50cf471347cc3b146757ac794b147b5 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_host_interface.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_INTERFACE_H + +#include + +#include "form_js_info.h" +#include "ipc_types.h" +#include "iremote_broker.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class IFormHost + * IFormHost interface is used to access form host service. + */ +class IFormHost : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormHost"); + + /** + * @brief Request to give back a Form. + * @param formInfo Form info. + */ + virtual void OnAcquired(const FormJsInfo &formInfo) = 0; + + /** + * @brief Form is updated. + * @param formInfo Form info. + */ + virtual void OnUpdate(const FormJsInfo &formInfo) = 0; + + /** + * @brief Form provider is uninstalled. + * @param formIds The Id list of the forms. + */ + virtual void OnUninstall(const std::vector &formIds) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for create (3001) + FORM_HOST_ON_ACQUIRED = 3681, + + // ipc id for update (3682) + FORM_HOST_ON_UPDATE, + + // ipc id for uninstall (3683) + FORM_HOST_ON_UNINSTALL, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_INTERFACE_H diff --git a/interfaces/innerkits/form_manager/include/form_host_proxy.h b/interfaces/innerkits/form_manager/include/form_host_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..255fa5d39e76e303dec31e2aad2a6a97ed21ea7a --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_host_proxy.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_PROXY_H + +#include "app_log_wrapper.h" +#include "form_host_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostProxy + * Form host proxy is used to access form host service. + */ +class FormHostProxy : public IRemoteProxy { +public: + explicit FormHostProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormHostProxy() = default; + + /** + * @brief Request to give back a Form. + * @param formInfo Form info. + */ + virtual void OnAcquired(const FormJsInfo &formInfo) override; + + /** + * @brief Form is updated. + * @param formInfo Form info. + */ + virtual void OnUpdate(const FormJsInfo &formInfo) override; + + /** + * @brief Form provider is uninstalled. + * @param formIds The Id list of the forms. + */ + virtual void OnUninstall(const std::vector &formIds) override; + +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_PROXY_H diff --git a/interfaces/innerkits/form_manager/include/form_host_stub.h b/interfaces/innerkits/form_manager/include/form_host_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..1c32be18be7194a8d3c98913e80327d4ad81047d --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_host_stub.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_STUB_H + +#include + +#include "form_host_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostStub + * Form host service stub. + */ +class FormHostStub : public IRemoteStub { +public: + FormHostStub(); + virtual ~FormHostStub(); + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief handle OnAcquired message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleAcquired(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle OnUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnUpdate(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle OnUnInstall message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnUninstall(MessageParcel &data, MessageParcel &reply); +private: + using FormHostFunc = int32_t (FormHostStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormHostStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_STUB_H diff --git a/interfaces/innerkits/form_manager/include/form_js_info.h b/interfaces/innerkits/form_manager/include/form_js_info.h new file mode 100644 index 0000000000000000000000000000000000000000..68fe090331db8f5586118bdbdc872d4ab124ffee --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_js_info.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H + + +#include +#include "form_provider_data.h" +#include "form_info_base.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @struct FormJsInfo + * Defines form js info. + */ +struct FormJsInfo : public Parcelable { + int64_t formId; + std::string formName; + std::string bundleName; + std::string abilityName; + bool formTempFlg = false; + std::string jsFormCodePath; + std::string formData; + FormProviderData formProviderData; + + std::string htmlPath; + std::string cssPath; + std::string jsPath; + std::string fileReousePath; + std::string formSrc; + FormWindow formWindow; + uint32_t versionCode = 0; + std::string versionName; + uint32_t compatibleVersion = 0; + std::string icon; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static FormJsInfo *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/include/form_mgr_interface.h b/interfaces/innerkits/form_manager/include/form_mgr_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..f48099b5342440121c21c6f8fc95fdeeccb70f75 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_mgr_interface.h @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_INTERFACE_H + +#include +#include "form_info.h" +#include "form_js_info.h" +#include "form_provider_data.h" +#include "ipc_types.h" +#include "iremote_broker.h" + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; + +/** + * @class IFormMgr + * IFormMgr interface is used to access form manager service. + */ +class IFormMgr : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormMgr") + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo) = 0; + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DeleteForm(const int64_t formId, const sptr &callerToken) = 0; + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) = 0; + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const std::string &bundleName, + const FormProviderData &formProviderData) = 0; + + /** + * @brief Set next refresh time. + * @param formId The Id of the form to update. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetNextRefreshTime(const int64_t formId, const int64_t nextTime) = 0; + + /** + * @brief Lifecycle update. + * @param formIds The Id of the forms. + * @param callerToken Caller ability token. + * @param updateType update type. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType) = 0; + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to request. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) = 0; + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType) = 0; + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CastTempForm(const int64_t formId, const sptr &callerToken) = 0; + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpStorageFormInfos(std::string &formInfos) = 0; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) = 0; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) = 0; + /** + * @brief Dump form timer by form id. + * @param formId The id of the form. + * @param formInfo Form timer. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) = 0; + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + virtual int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) = 0; + + /** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int BatchAddFormRecords(const Want &want) = 0; + /** + * @brief Clear form records for st limit value test. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ClearFormRecords() = 0; + + /** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DistributedDataAddForm(const Want &want) = 0; + + /** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DistributedDataDeleteForm(const std::string &formId) = 0; + + /** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetAllFormsInfo(std::vector &formInfos) = 0; + + /** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) = 0; + + /** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, + std::vector &formInfos) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for create (3001) + FORM_MGR_ADD_FORM = 3001, + FORM_MGR_ADD_FORM_OHOS, + FORM_MGR_DELETE_FORM, + FORM_MGR_UPDATE_FORM, + FORM_MGR_LIFECYCLE_UPDATE, + FORM_MGR_REQUEST_FORM, + FORM_MGR_RELEASE_FORM, + FORM_MGR_RELEASE_CACHED_FORM, + FORM_MGR_CAST_TEMP_FORM, + FORM_MGR_EVENT_NOTIFY, + FORM_MGR_CHECK_AND_DELETE_INVALID_FORMS, + FORM_MGR_SET_NEXT_REFRESH_TIME, + FORM_MGR_ACQUIRE_FORM_STATE, + FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE, + FORM_MGR_STORAGE_FORM_INFOS, + FORM_MGR_FORM_INFOS_BY_NAME, + FORM_MGR_FORM_INFOS_BY_ID, + FORM_MGR_FORM_TIMER_INFO_BY_ID, + FORM_MGR_MESSAGE_EVENT, + FORM_MGR_BATCH_ADD_FORM_RECORDS_ST, + FORM_MGR_CLEAR_FORM_RECORDS_ST, + FORM_MGR_DISTRIBUTED_DATA_ADD_FORM__ST, + FORM_MGR_DISTRIBUTED_DATA_DELETE_FORM__ST, + FORM_MGR_GET_ALL_FORMS_INFO, + FORM_MGR_GET_FORMS_INFO_BY_APP, + FORM_MGR_GET_FORMS_INFO_BY_MODULE, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_INTERFACE_H diff --git a/interfaces/innerkits/form_manager/include/form_mgr_proxy.h b/interfaces/innerkits/form_manager/include/form_mgr_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..f4e48460c2c46eb555698168be0133f915ca8bb9 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_mgr_proxy.h @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_PROXY_H + +#include "form_db_info.h" +#include "form_info.h" +#include "form_mgr_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormMgrProxy + * FormMgrProxy is used to access form manager service. + */ +class FormMgrProxy : public IRemoteProxy { +public: + explicit FormMgrProxy(const sptr &impl); + virtual ~FormMgrProxy() = default; + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo) override; + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DeleteForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) override; + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param FormProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const std::string &bundleName, + const FormProviderData &FormProviderData) override; + + /** + * @brief Set next refresh time. + * @param formId The Id of the form to update. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetNextRefreshTime(const int64_t formId, const int64_t nextTime) override; + + /** + * @brief Lifecycle update. + * @param formIds The Id of the forms. + * @param callerToken Caller ability token. + * @param updateType update type. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType) override; + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) override; + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType) override; + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CastTempForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpStorageFormInfos(std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) override; + /** + * @brief Dump timer info by form id. + * @param formId The id of the form. + * @param formInfo Form timer info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) override; + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + virtual int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) override; + + /** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int BatchAddFormRecords(const Want &want) override; + /** + * @brief Clear form records for st limit value test. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ClearFormRecords() override; + + /** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DistributedDataAddForm(const Want &want) override; + + /** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DistributedDataDeleteForm(const std::string &formId) override; + + /** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetAllFormsInfo(std::vector &formInfos) override; + + /** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) override; + + /** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, + std::vector &formInfos) override; +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + template + int GetParcelableInfo(IFormMgr::Message code, MessageParcel &data, T &parcelableInfo); + int SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply); + int GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo); + int GetFormsInfo(IFormMgr::Message code, MessageParcel &data, std::vector &formInfos); +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_PROXY_H diff --git a/interfaces/innerkits/form_manager/include/form_mgr_stub.h b/interfaces/innerkits/form_manager/include/form_mgr_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..f2f7bca7e9b7c9a7a785efd938a6481d6786d59d --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_mgr_stub.h @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_STUB_H + +#include + +#include "form_mgr_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormMgrStub + * Form manager service stub. + */ +class FormMgrStub : public IRemoteStub { +public: + FormMgrStub(); + virtual ~FormMgrStub(); + /** + * @brief Handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief Handle AddForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleAddForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DeleteForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDeleteForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle ReleaseForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleReleaseForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle UpdateForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleUpdateForm(MessageParcel &data, MessageParcel &reply); + + /** + * @brief handle LifecycleUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleLifecycleUpdate(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle SetNextRefreshTime message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleSetNextRefreshTime(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle RequestForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleRequestForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle NotifyWhetherVisibleForms message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleNotifyWhetherVisibleForms(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle CastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleCastTempForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpStorageFormInfos message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDumpStorageFormInfos(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpFormInfoByBundleName message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDumpFormInfoByBundleName(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDumpFormInfoByFormId(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpFormTimerByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDumpFormTimerByFormId(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleMessageEvent(MessageParcel &data, MessageParcel &reply); + + /** + * @brief Handle BatchAddFormRecords message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleBatchAddFormRecords(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle ClearFormRecords message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleClearFormRecords(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DistributedDataAddForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDistributedDataAddForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DistributedDataDeleteForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDistributedDataDeleteForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle GetAllFormsInfo message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleGetAllFormsInfo(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle GetFormsInfoByApp message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleGetFormsInfoByApp(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle GetFormsInfoByModule message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleGetFormsInfoByModule(MessageParcel &data, MessageParcel &reply); +private: + using FormMgrFunc = int32_t (FormMgrStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormMgrStub); + + /** + * @brief Write a parcelabe vector objects to the proxy node. + * @param parcelableVector Indicates the objects to be write. + * @param reply Indicates the reply to be sent; + * @return Returns true if objects send successfully; returns false otherwise. + */ + template + bool WriteParcelableVector(std::vector &parcelableVector, Parcel &reply); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_STUB_H diff --git a/interfaces/innerkits/form_manager/include/form_provider_data.h b/interfaces/innerkits/form_manager/include/form_provider_data.h new file mode 100644 index 0000000000000000000000000000000000000000..4ca3c98964632d39e82d337b552ede76f8ed8469 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_provider_data.h @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H + +#include +#include +#include + +#include "ashmem.h" +#include "message_parcel.h" +#include "nlohmann/json.hpp" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderData + * Defines form provider data. + */ +class FormProviderData : public Parcelable { +public: + /** + * @brief Constructor. + */ + FormProviderData(); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ + FormProviderData(nlohmann::json &jsonData); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, in JSON + * string format. + */ + FormProviderData(std::string jsonDataString); + + /** + * @brief Destructor. + */ + virtual ~FormProviderData(){}; + + /** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code nlohmann::json} format. + */ + void UpdateData(nlohmann::json &jsonData); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ + std::string GetDataString() const; + + /** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ + void AddImageData(std::string picName, char *data); + + /** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ + void RemoveImageData(std::string picName); + + /** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ + int32_t GetImageDataState(); + + /** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ + void SetImageDataState(int32_t imageDataState); + + /** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ + std::map, int32_t>> GetImageDataMap(); + + /** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ + void SetImageDataMap(std::map, int32_t>> imageDataMap); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ + nlohmann::json GetData() const; + /** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ + void SetDataString(std::string &jsonDataString); + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + /** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + /** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return Returns FormProviderData. + */ + static FormProviderData* Unmarshalling(Parcel &parcel); + + /** + * @brief Clear imageDataMap, rawImageBytesMap, imageDataState and jsonFormProviderData. + */ + void ClearData(); + +private: + bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; + +private: + nlohmann::json jsonFormProviderData_; + std::map, int32_t>> imageDataMap_; + std::map rawImageBytesMap_; + int32_t imageDataState_ = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H diff --git a/interfaces/innerkits/form_manager/include/form_provider_info.h b/interfaces/innerkits/form_manager/include/form_provider_info.h new file mode 100644 index 0000000000000000000000000000000000000000..522b8584d0550a395022032aa42dd9a85c6d93f6 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_provider_info.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H + +#include +#include "form_provider_data.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @struct FormProviderInfo + * Defines form provider info. + */ +class FormProviderInfo : public Parcelable { +public: + FormProviderInfo() = default; + ~FormProviderInfo() = default; + + /** + * @brief Set the form data. + * @param formProviderData The form data. + */ + inline void SetFormData(const FormProviderData &formProviderData) + { + jsBindingData_ = formProviderData; + } + + /** + * @brief Get the form data. + * @return the form data. + */ + inline FormProviderData GetFormData() const + { + return jsBindingData_; + } + /** + * @brief Get the form data. + * @return the form data. + */ + inline std::string GetFormDataString() const + { + return jsBindingData_.GetDataString(); + } + + /** + * @brief Set the upgrade flg. + * @param upgradeFlg The upgrade flg. + */ + inline void SetUpgradeFlg(const bool upgradeFlg) + { + upgradeFlg_ = upgradeFlg; + } + /** + * @brief Get the upgrade flg. + * @return the upgrade flg. + */ + inline bool GetUpgradeFlg() const + { + return upgradeFlg_; + } + + /** + * @brief Set form date by string. + * @param dataString string json data. + */ + void SetFormDataString(std::string &dataString); + + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static FormProviderInfo *Unmarshalling(Parcel &parcel); +private: + FormProviderData jsBindingData_; + bool upgradeFlg_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H diff --git a/interfaces/innerkits/form_manager/include/form_provider_interface.h b/interfaces/innerkits/form_manager/include/form_provider_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..5594a23a0f6ecf296312008373632a0afab9f2e5 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_provider_interface.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_INTERFACE_H + +#include + +#include "ipc_types.h" +#include "iremote_broker.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; +/** + * @class IFormProvider + * IFormProvider interface is used to access form provider service. + */ +class IFormProvider : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormProvider"); + + /** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the from. + * @param want Indicates the {@link Want} structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) = 0; + + /** + * @brief Notify provider when the form was deleted. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormDelete(const int64_t formId, const Want &want, const sptr &callerToken) = 0; + + /** + * @brief Notify provider when the forms was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) = 0; + /** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &callerToken) = 0; + + /** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) = 0; + + /** + * @brief Notify provider when the temp form was cast to normal form. + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) = 0; + + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for add form (3001) + FORM_ACQUIRE_PROVIDER_FORM_INFO = 3051, + + // ipc id for delete form (3052) + FORM_PROVIDER_NOTIFY_FORM_DELETE, + + // ipc id for form done release form (3053) + FORM_PROVIDER_NOTIFY_FORMS_DELETE, + + // ipc id for connecting update form (3054) + FORM_PROVIDER_NOTIFY_FORM_UPDATE, + + // ipc id for form visible notify (3055) + FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST, + + // ipc id for event notify (3056) + FORM_PROVIDER_EVENT_NOTIFY, + + // ipc id for event notify (3057) + FORM_PROVIDER_EVENT_MESSAGE, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_INTERFACE_H diff --git a/interfaces/innerkits/form_manager/include/form_provider_proxy.h b/interfaces/innerkits/form_manager/include/form_provider_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..e2e59e1bdc6784a623849ab53fa6538bca23812f --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_provider_proxy.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_PROXY_H + +#include "app_log_wrapper.h" +#include "form_provider_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderProxy + * FormProviderProxy is used to access form provider service. + */ +class FormProviderProxy : public IRemoteProxy { +public: + explicit FormProviderProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormProviderProxy() = default; + + /** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the from. + * @param want Indicates the {@link Want} structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form was deleted. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormDelete(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the forms was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormUpdate(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) override; + + /** + * @brief Notify provider when the temp form was cast to normal form. + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) override; + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) override; + +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_PROXY_H diff --git a/interfaces/innerkits/form_manager/include/form_provider_stub.h b/interfaces/innerkits/form_manager/include/form_provider_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..5c0751e96dbce5622ac43682238143346b68ccad --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_provider_stub.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_STUB_H + +#include + +#include "form_provider_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderStub + * form provider service stub. + */ +class FormProviderStub : public IRemoteStub { +public: + FormProviderStub(); + virtual ~FormProviderStub(); + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief handle AcquireProviderFormInfo message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleAcquireProviderFormInfo(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormDelete(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormsDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormsDelete(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormUpdate(MessageParcel &data, MessageParcel &reply); + + /** + * @brief handle EventNotify message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleEventNotify(MessageParcel &data, MessageParcel &reply); + + /** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormCastTempForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleFireFormEvent(MessageParcel &data, MessageParcel &reply); +private: + using FormProviderFunc = int32_t (FormProviderStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormProviderStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_STUB_H diff --git a/interfaces/innerkits/form_manager/include/form_supply_interface.h b/interfaces/innerkits/form_manager/include/form_supply_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..9e8ec1562ee2e02a551461f3136a862f56cebab0 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_supply_interface.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_INTERFACE_H + +#include + +#include "form_provider_info.h" +#include "ipc_types.h" +#include "iremote_broker.h" + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; + +/** + * @class IFormSupply + * IFormSupply interface is used to access form supply service. + */ +class IFormSupply : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormSupply"); + + /** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnAcquire(const FormProviderInfo &formInfo, const Want &want) = 0; + + /** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnEventHandle(const Want &want) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for create (3201) + TRANSACTION_FORM_ACQUIRED = 3201, + TRANSACTION_EVENT_HANDLE, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_INTERFACE_H diff --git a/interfaces/innerkits/form_manager/include/form_supply_proxy.h b/interfaces/innerkits/form_manager/include/form_supply_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..095130a67388efb2f98ce1f554e129fa6f2d6063 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_supply_proxy.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_PROXY_H + +#include "app_log_wrapper.h" +#include "form_supply_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyProxy + * FormSupplyProxy is used to access form supply service. + */ +class FormSupplyProxy : public IRemoteProxy { +public: + explicit FormSupplyProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormSupplyProxy() = default; + + /** + * @brief Send form binding data from form provider to fms. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; + + /** + * @brief Send other event to fms. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnEventHandle(const Want &want) override; + +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_PROXY_H diff --git a/interfaces/innerkits/form_manager/include/form_supply_stub.h b/interfaces/innerkits/form_manager/include/form_supply_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..796012eb146f20167aaf092cb853a25f71678f45 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/form_supply_stub.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_STUP_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_STUP_H + +#include +#include "form_supply_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyStub + * form supply service stub. + */ +class FormSupplyStub : public IRemoteStub { +public: + FormSupplyStub(); + virtual ~FormSupplyStub(); + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief handle OnAcquire message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnAcquire(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle OnEventHandle message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnEventHandle(MessageParcel &data, MessageParcel &reply); +private: + using FormSupplyFunc = int32_t (FormSupplyStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormSupplyStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_STUP_H diff --git a/interfaces/innerkits/form_manager/include/provider_connect_proxy.h b/interfaces/innerkits/form_manager/include/provider_connect_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..194c8804b30efe350816306afaeb8b5071d25a79 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/provider_connect_proxy.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_PROXY_H + +#include "ability_connect_callback_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; + +/** + * @class ProviderConnectProxy + * Provider connect proxy is used to connect form ability service. + */ +class ProviderConnectProxy : public IRemoteProxy { +public: + explicit ProviderConnectProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~ProviderConnectProxy() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + /** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_PROXY_H \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/include/provider_connect_stub.h b/interfaces/innerkits/form_manager/include/provider_connect_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..c8f52b8eea7562878842cd47d860ed58653baea3 --- /dev/null +++ b/interfaces/innerkits/form_manager/include/provider_connect_stub.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_STUB_H + +#include "ability_connect_callback_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; + +/** + * @class ProviderConnectStub + * Form ability service stub. + */ +class ProviderConnectStub : public IRemoteStub { +public: + ProviderConnectStub() = default; + virtual ~ProviderConnectStub() = default; + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + DISALLOW_COPY_AND_MOVE(ProviderConnectStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_STUB_H diff --git a/interfaces/innerkits/form_manager/src/form_host_proxy.cpp b/interfaces/innerkits/form_manager/src/form_host_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48bf9d8f121ed76931903504e783ab0113f84d0b --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_host_proxy.cpp @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "form_host_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Request to give back a Form. + * @param formInfo Form info. + */ +void FormHostProxy::OnAcquired(const FormJsInfo &formInfo) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + } + + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + } + + error = Remote()->SendRequest( + static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } +} + + +/** +* @brief Form is updated. +* @param bundleName Provider ability bundleName. +*/ +void FormHostProxy::OnUpdate(const FormJsInfo &formInfo) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + } + + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + } + + error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_UPDATE), data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } +} + + +/** + * @brief Form provider is uninstalled + * @param formIds The Id list of the forms. + */ +void FormHostProxy::OnUninstall(const std::vector &formIds) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + } + + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds", __func__); + } + + error = Remote()->SendRequest( + static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } +} + +template +int FormHostProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to read Parcelable infos", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("%{public}s, get parcelable infos success", __func__); + return ERR_OK; +} + +bool FormHostProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormHostProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/form_host_stub.cpp b/interfaces/innerkits/form_manager/src/form_host_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..066c32df93ef8f20badca19fb7d9d7f5e978607a --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_host_stub.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "app_scheduler_interface.h" +#include "errors.h" +#include "form_host_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormHostStub::FormHostStub() +{ + memberFuncMap_[static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED)] = + &FormHostStub::HandleAcquired; + memberFuncMap_[static_cast(IFormHost::Message::FORM_HOST_ON_UPDATE)] = + &FormHostStub::HandleOnUpdate; + memberFuncMap_[static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL)] = + &FormHostStub::HandleOnUninstall; +} + +FormHostStub::~FormHostStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormHostStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormHostStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle OnAcquired event. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::HandleAcquired(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr formInfo(data.ReadParcelable()); + if (!formInfo) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + OnAcquired(*formInfo); + reply.WriteInt32(ERR_OK); + return ERR_OK; +} +/** + * @brief handle OnUpdate event. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::HandleOnUpdate(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr formInfo(data.ReadParcelable()); + if (!formInfo) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + OnUpdate(*formInfo); + reply.WriteInt32(ERR_OK); + return ERR_OK; +} + +/** + * @brief handle OnUnInstall event. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::HandleOnUninstall(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (ret) { + OnUninstall(formIds); + reply.WriteInt32(ERR_OK); + return ERR_OK; + } + return ERR_APPEXECFWK_PARCEL_ERROR; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/src/form_js_info.cpp b/interfaces/innerkits/form_manager/src/form_js_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14fa30ff8ced8400bab4f2faa4d5490fe76e778c --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_js_info.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_js_info.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool FormJsInfo::ReadFromParcel(Parcel &parcel) +{ + formId = parcel.ReadInt64(); + formName = Str16ToStr8(parcel.ReadString16()); + bundleName = Str16ToStr8(parcel.ReadString16()); + abilityName = Str16ToStr8(parcel.ReadString16()); + + formTempFlg = parcel.ReadBool(); + jsFormCodePath = Str16ToStr8(parcel.ReadString16()); + formData = Str16ToStr8(parcel.ReadString16()); + + formSrc = Str16ToStr8(parcel.ReadString16()); + formWindow.designWidth = parcel.ReadInt32(); + formWindow.autoDesignWidth = parcel.ReadBool(); + + versionCode = parcel.ReadUint32(); + versionName = Str16ToStr8(parcel.ReadString16()); + compatibleVersion = parcel.ReadUint32(); + icon = Str16ToStr8(parcel.ReadString16()); + + auto bindingData = parcel.ReadParcelable(); + if (nullptr == bindingData){ + return false; + } + formProviderData = *bindingData; + return true; +} + +FormJsInfo *FormJsInfo::Unmarshalling(Parcel &parcel) +{ + std::unique_ptr formJsInfo = std::make_unique(); + if (formJsInfo && !formJsInfo->ReadFromParcel(parcel)) { + formJsInfo = nullptr; + } + return formJsInfo.release(); +} + +bool FormJsInfo::Marshalling(Parcel &parcel) const +{ + // write formId + if (!parcel.WriteInt64(formId)) { + return false; + } + // write formName + if (!parcel.WriteString16(Str8ToStr16(formName))) { + return false; + } + // write bundleName + if (!parcel.WriteString16(Str8ToStr16(bundleName))) { + return false; + } + // write abilityName + if (!parcel.WriteString16(Str8ToStr16(abilityName))) { + return false; + } + + // write tempFlag + if (!parcel.WriteBool(formTempFlg)) { + return false; + } + + // write jsFormCodePath + if (!parcel.WriteString16(Str8ToStr16(jsFormCodePath))) { + return false; + } + + // write formData + if (!parcel.WriteString16(Str8ToStr16(formData))) { + return false; + } + + // write formSrc + if (!parcel.WriteString16(Str8ToStr16(formSrc))) { + return false; + } + + // write formWindow + if (!parcel.WriteInt32(formWindow.designWidth)) { + return false; + } + if (!parcel.WriteBool(formWindow.autoDesignWidth)) { + return false; + } + + // write version + if (!parcel.WriteUint32(versionCode)) { + return false; + } + if (!parcel.WriteString16(Str8ToStr16(versionName))) { + return false; + } + if (!parcel.WriteUint32(compatibleVersion)) { + return false; + } + + // write icon + if (!parcel.WriteString16(Str8ToStr16(icon))) { + return false; + } + + // write formProviderData + if (!parcel.WriteParcelable(&formProviderData)) { + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/src/form_mgr_proxy.cpp b/interfaces/innerkits/form_manager/src/form_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec68b0181c021312735192d1a63e4c71ca412f90 --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_mgr_proxy.cpp @@ -0,0 +1,802 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_mgr_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +FormMgrProxy::FormMgrProxy(const sptr &impl) : IRemoteProxy(impl) +{} +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::AddForm( + const int64_t formId, + const Want &want, + const sptr &callerToken, + FormJsInfo &formInfo) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetParcelableInfo(IFormMgr::Message::FORM_MGR_ADD_FORM, data, formInfo); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + + return error; +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteBool(delCache)) { + APP_LOGE("%{public}s, failed to write delCache", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param FormProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::UpdateForm( + const int64_t formId, + const std::string &bundleName, + const FormProviderData &FormProviderData) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&FormProviderData)) { + APP_LOGE("%{public}s, failed to write formBindingData", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Set next refresh time. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + MessageParcel data; + MessageParcel reply; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(nextTime)) { + APP_LOGE("%{public}s, failed to write nextTime", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} +/** + * @brief Lifecycle update. + * @param formIds The Id of the forms. + * @param callerToken Caller ability token. + * @param updateType update type. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::LifecycleUpdate( + const std::vector &formIds, + const sptr &callerToken, + const int32_t updateType) +{ + MessageParcel data; + MessageParcel reply; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt32(updateType)) { + APP_LOGE("%{public}s, failed to write nextTime", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + + return reply.ReadInt32(); +} +/** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::NotifyWhetherVisibleForms( + const std::vector &formIds, + const sptr &callerToken, + const int32_t formVisibleType) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt32(formVisibleType)) { + APP_LOGE("%{public}s, failed to write formVisibleType", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast( + IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DumpStorageFormInfos(std::string &formInfos) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetStringInfo(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS, data, formInfos); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + } + + return error; +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME, data, formInfos); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + } + + return error; +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + } + + return error; +} +/** + * @brief Dump timer info by form id. + * @param formId The id of the form. + * @param formInfo Form timer info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_TIMER_INFO_BY_ID, data, isTimingService); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + } + + return error; +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgrProxy::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::BatchAddFormRecords(const Want &want) +{ + // must not implement, just for st + return ERR_OK; +} +/** + * @brief Clear form records for st limit value test. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::ClearFormRecords() +{ + // must not implement, just for st + return ERR_OK; +} + +template +int FormMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to Read Parcelable infos", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("get parcelable infos success"); + return ERR_OK; +} +bool FormMgrProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(IFormMgr::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +int FormMgrProxy::GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to read reply result", __func__); + return error; + } + std::vector stringInfoList; + if (!reply.ReadStringVector(&stringInfoList)) { + APP_LOGE("%{public}s, failed to read string vector from reply", __func__); + return false; + } + if (stringInfoList.empty()) { + APP_LOGI("%{public}s, No string info", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + for (auto &info : stringInfoList) { + stringInfo += info; + } + APP_LOGD("get string info success"); + return ERR_OK; +} +int FormMgrProxy::GetFormsInfo(IFormMgr::Message code, MessageParcel &data, std::vector &formInfos) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to read reply result", __func__); + return error; + } + + return GetParcelableInfos(reply, formInfos); +} +template +int FormMgrProxy::GetParcelableInfo(IFormMgr::Message code, MessageParcel &data, T &parcelableInfo) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to read reply result", __func__); + return error; + } + + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to readParcelableInfo", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + parcelableInfo = *info; + APP_LOGD("get parcelable info success"); + return ERR_OK; +} +int FormMgrProxy::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + MessageOption option(MessageOption::TF_SYNC); + + sptr remote = Remote(); + if (!remote) { + APP_LOGE("%{public}s, failed to get remote object, cmd: %{public}d", __func__, code); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + int32_t result = remote->SendRequest(static_cast(code), data, reply, option); + if (result != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return ERR_OK; +} + +/** + * @brief Add forms to storage for st . + * @param Want The formDBInfo of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DistributedDataAddForm(const Want &want) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_DISTRIBUTED_DATA_ADD_FORM__ST), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DistributedDataDeleteForm(const std::string &formId) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(std::stoll(formId))) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_DISTRIBUTED_DATA_DELETE_FORM__ST), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::GetAllFormsInfo(std::vector &formInfos) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetFormsInfo(IFormMgr::Message::FORM_MGR_GET_ALL_FORMS_INFO, data, formInfos); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetAllFormsInfo: %{public}d", __func__, error); + } + + return error; +} + +/** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetFormsInfo(IFormMgr::Message::FORM_MGR_GET_FORMS_INFO_BY_APP, data, formInfos); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetAllFormsInfo: %{public}d", __func__, error); + } + + return error; +} + +/** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, + std::vector &formInfos) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(moduleName)) { + APP_LOGE("%{public}s, failed to write moduleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetFormsInfo(IFormMgr::Message::FORM_MGR_GET_FORMS_INFO_BY_MODULE, data, formInfos); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetAllFormsInfo: %{public}d", __func__, error); + } + + return error; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/form_mgr_stub.cpp b/interfaces/innerkits/form_manager/src/form_mgr_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..848b1e935d9347beba6a23d6516deca2040cee79 --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_mgr_stub.cpp @@ -0,0 +1,588 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_info.h" +#include "form_mgr_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +const int32_t LIMIT_PARCEL_SIZE = 1024; + +void SplitString(const std::string &source, std::vector &strings) +{ + int splitSize = (source.size() / LIMIT_PARCEL_SIZE); + if ((source.size() % LIMIT_PARCEL_SIZE) != 0) { + splitSize++; + } + APP_LOGD("the dump string split into %{public}d size", splitSize); + for (int i = 0; i < splitSize; i++) { + int32_t start = LIMIT_PARCEL_SIZE * i; + strings.emplace_back(source.substr(start, LIMIT_PARCEL_SIZE)); + } +} + +FormMgrStub::FormMgrStub() +{ + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_ADD_FORM)] = + &FormMgrStub::HandleAddForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM)] = + &FormMgrStub::HandleDeleteForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM)] = + &FormMgrStub::HandleReleaseForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM)] = + &FormMgrStub::HandleUpdateForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM)] = + &FormMgrStub::HandleRequestForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE)] = + &FormMgrStub::HandleNotifyWhetherVisibleForms; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM)] = + &FormMgrStub::HandleCastTempForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS)] = + &FormMgrStub::HandleDumpStorageFormInfos; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME)] = + &FormMgrStub::HandleDumpFormInfoByBundleName; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID)] = + &FormMgrStub::HandleDumpFormInfoByFormId; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_FORM_TIMER_INFO_BY_ID)] = + &FormMgrStub::HandleDumpFormTimerByFormId; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME)] = + &FormMgrStub::HandleSetNextRefreshTime; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE)] = + &FormMgrStub::HandleLifecycleUpdate; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT)] = + &FormMgrStub::HandleMessageEvent; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_BATCH_ADD_FORM_RECORDS_ST)] = + &FormMgrStub::HandleBatchAddFormRecords; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_CLEAR_FORM_RECORDS_ST)] = + &FormMgrStub::HandleClearFormRecords; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_DISTRIBUTED_DATA_ADD_FORM__ST)] = + &FormMgrStub::HandleDistributedDataAddForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_DISTRIBUTED_DATA_DELETE_FORM__ST)] = + &FormMgrStub::HandleDistributedDataDeleteForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_GET_ALL_FORMS_INFO)] = + &FormMgrStub::HandleGetAllFormsInfo; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_GET_FORMS_INFO_BY_APP)] = + &FormMgrStub::HandleGetFormsInfoByApp; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_GET_FORMS_INFO_BY_MODULE)] = + &FormMgrStub::HandleGetFormsInfoByModule; +} + +FormMgrStub::~FormMgrStub() +{ + memberFuncMap_.clear(); +} + +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormMgrStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormMgrStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle AddForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleAddForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to RemoteObject invalidate", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + FormJsInfo formInfo; + int32_t result = AddForm(formId, *want, client, formInfo); + reply.WriteInt32(result); + reply.WriteParcelable(&formInfo); + + return result; +} +/** + * @brief handle DeleteForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDeleteForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + int32_t result = DeleteForm(formId, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle ReleaseForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleReleaseForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + bool delCache = data.ReadBool(); + + int32_t result = ReleaseForm(formId, client, delCache); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle UpdateForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleUpdateForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::string bundleName = data.ReadString(); + std::unique_ptr formBindingData(data.ReadParcelable()); + int32_t result = UpdateForm(formId, bundleName, *formBindingData); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle SetNextRefreshTime message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleSetNextRefreshTime(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + int64_t nextTime = data.ReadInt64(); + int32_t result = SetNextRefreshTime(formId, nextTime); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle LifecycleUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleLifecycleUpdate(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (!ret) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + int32_t updateType = data.ReadInt32(); + int32_t result = LifecycleUpdate(formIds, client, updateType); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle RequestForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleRequestForm(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + + int64_t formId = data.ReadInt64(); + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = RequestForm(formId, client, *want); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyVisibleForms message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleNotifyWhetherVisibleForms(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (!ret) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + int32_t formVisibleType = data.ReadInt32(); + + int32_t result = NotifyWhetherVisibleForms(formIds, client, formVisibleType); + reply.WriteInt32(result); + return result; +} + +/** + * @brief handle CastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleCastTempForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = CastTempForm(formId, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief Handle DumpStorageFormInfos message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDumpStorageFormInfos(MessageParcel &data, MessageParcel &reply) +{ + std::string formInfos; + int32_t result = DumpStorageFormInfos(formInfos); + reply.WriteInt32(result); + if (result == ERR_OK) { + std::vector dumpInfos; + SplitString(formInfos, dumpInfos); + if (!reply.WriteStringVector(dumpInfos)) { + APP_LOGE("%{public}s, failed to WriteStringVector", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + return result; +} +/** + * @brief Handle DumpFormInfoByBundleName message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDumpFormInfoByBundleName(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string formInfos; + int32_t result = DumpFormInfoByBundleName(bundleName, formInfos); + reply.WriteInt32(result); + if (result == ERR_OK) { + APP_LOGD("%{public}s, formInfos: %{public}s", __func__, formInfos.c_str()); + std::vector dumpInfos; + SplitString(formInfos, dumpInfos); + if (!reply.WriteStringVector(dumpInfos)) { + APP_LOGE("%{public}s, failed to WriteStringVector", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + return result; +} +/** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDumpFormInfoByFormId(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::string formInfo; + int32_t result = DumpFormInfoByFormId(formId, formInfo); + reply.WriteInt32(result); + if (result == ERR_OK) { + std::vector dumpInfos; + SplitString(formInfo, dumpInfos); + if (!reply.WriteStringVector(dumpInfos)) { + APP_LOGE("%{public}s, failed to WriteStringVector", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return result; +} +/** + * @brief Handle DumpFormTimerByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDumpFormTimerByFormId(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::string isTimingService; + int32_t result = DumpFormTimerByFormId(formId, isTimingService); + reply.WriteInt32(result); + if (result == ERR_OK) { + std::vector dumpInfos; + SplitString(isTimingService, dumpInfos); + if (!reply.WriteStringVector(dumpInfos)) { + APP_LOGE("%{public}s, failed to WriteStringVector", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return result; +} + +/** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleMessageEvent(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + int64_t formId = data.ReadInt64(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = MessageEvent(formId, *want, client); + reply.WriteInt32(result); + return result; +} + +/** + * @brief Handle BatchAddFormRecords message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleBatchAddFormRecords(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = BatchAddFormRecords(*want); + reply.WriteInt32(result); + return result; +} + +/** + * @brief Handle BatchDeleteFormRecords message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleClearFormRecords(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + int32_t result = ClearFormRecords(); + reply.WriteInt32(result); + return result; +} + +/** + * @brief Handle DistributedDataAddForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDistributedDataAddForm(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = DistributedDataAddForm(*want); + reply.WriteInt32(result); + return result; +} + +/** + * @brief Handle DistributedDataDeleteForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDistributedDataDeleteForm(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + + std::string formId = data.ReadString(); + if (formId.empty()) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = DistributedDataDeleteForm(formId); + reply.WriteInt32(result); + return result; +} + +/** + * @brief Handle GetAllFormsInfo message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleGetAllFormsInfo(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + std::vector infos; + int32_t result = GetAllFormsInfo(infos); + reply.WriteInt32(result); + if (result == ERR_OK) { + if (!WriteParcelableVector(infos, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return result; +} + +/** + * @brief Handle GetFormsInfoByApp message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleGetFormsInfoByApp(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + std::string bundleName = data.ReadString(); + std::vector infos; + int32_t result = GetFormsInfoByApp(bundleName, infos); + reply.WriteInt32(result); + if (result == ERR_OK) { + if (!WriteParcelableVector(infos, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return result; +} + +/** + * @brief Handle GetFormsInfoByModule message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleGetFormsInfoByModule(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + std::string bundleName = data.ReadString(); + std::string moduleName = data.ReadString(); + std::vector infos; + int32_t result = GetFormsInfoByModule(bundleName, moduleName, infos); + reply.WriteInt32(result); + if (result == ERR_OK) { + if (!WriteParcelableVector(infos, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return result; +} + +/** + * @brief Write a parcelabe vector objects to the proxy node. + * @param parcelableVector Indicates the objects to be write. + * @param reply Indicates the reply to be sent; + * @return Returns true if objects send successfully; returns false otherwise. + */ +template +bool FormMgrStub::WriteParcelableVector(std::vector &parcelableVector, Parcel &reply) +{ + if (!reply.WriteInt32(parcelableVector.size())) { + APP_LOGE("write ParcelableVector failed"); + return false; + } + + for (auto &parcelable: parcelableVector) { + if (!reply.WriteParcelable(&parcelable)) { + APP_LOGE("write ParcelableVector failed"); + return false; + } + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/form_provider_data.cpp b/interfaces/innerkits/form_manager/src/form_provider_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40d5b20312207811300db613864cceaa74d9f95c --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_provider_data.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "form_provider_data.h" +#include "message_parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +const int IMAGE_DATA_STATE_REMOVED = -1; +const int IMAGE_DATA_STATE_NO_OPERATION = 0; +const int IMAGE_DATA_STATE_ADDED = 1; +const std::string JSON_EMPTY_STRING = "{}"; + +/** + * @brief Constructor. + */ +FormProviderData::FormProviderData() +{ + jsonFormProviderData_.clear(); +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ +FormProviderData::FormProviderData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, + * in JSON string format. + */ +FormProviderData::FormProviderData(std::string jsonDataString) +{ + if (jsonDataString.empty()) { + jsonDataString = JSON_EMPTY_STRING; + } + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} + +/** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code ZSONObject} format. + */ +void FormProviderData::UpdateData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ +nlohmann::json FormProviderData::GetData() const +{ + return jsonFormProviderData_; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ +std::string FormProviderData::GetDataString() const +{ + APP_LOGI("%{public}s called", __func__); + std::string dataStr = jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); + APP_LOGI("%{public}s, data: %{public}s", __func__, dataStr.c_str()); + return dataStr; +} + +/** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ +void FormProviderData::AddImageData(std::string picName, char *data) +{ + if ((picName.length() == 0) || (sizeof(data) == 0)) { + APP_LOGE("input param is NULL!"); + return; + } + + rawImageBytesMap_[picName] = data; + + imageDataState_ = IMAGE_DATA_STATE_ADDED; +} + +/** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ +void FormProviderData::RemoveImageData(std::string picName) +{ + rawImageBytesMap_.erase(picName); +} + +/** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ +void FormProviderData::SetDataString(std::string &jsonDataString) +{ + APP_LOGI("%{public}s called", __func__); + if (jsonDataString.empty()) { + jsonDataString = JSON_EMPTY_STRING; + } + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} +/** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ +void FormProviderData::MergeData(nlohmann::json &addJsonData) +{ + APP_LOGI("%{public}s called", __func__); + if (addJsonData.empty()) { + return; + } + + if (jsonFormProviderData_.empty()) { + jsonFormProviderData_ = addJsonData; + return; + } + + for (auto && [key, value] : addJsonData.items()) { + jsonFormProviderData_[key] = value; + } +} + +/** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ +std::map, int32_t>> FormProviderData::GetImageDataMap() +{ + return imageDataMap_; +} + +/** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ +int32_t FormProviderData::GetImageDataState() +{ + return imageDataState_; +} + +/** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ +void FormProviderData::SetImageDataState(int32_t imageDataState) +{ + imageDataState_ = imageDataState; +} + +/** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ +void FormProviderData::SetImageDataMap(std::map, int32_t>> imageDataMap) +{ + imageDataMap_ = imageDataMap; +} + +/** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::ReadFromParcel(Parcel &parcel) +{ + jsonFormProviderData_ = nlohmann::json::parse(Str16ToStr8(parcel.ReadString16())); + + imageDataState_ = parcel.ReadInt32(); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + int32_t imageDataNum = parcel.ReadInt32(); + for (int32_t i = 0; i < imageDataNum; i++) { + MessageParcel* messageParcel = (MessageParcel*)&parcel; + sptr ashmem = messageParcel->ReadAshmem(); + if (ashmem == nullptr) { + APP_LOGE("%{public}s failed, ashmem is nullptr", __func__); + return false; + } + + int32_t len = parcel.ReadInt32(); + std::pair, int32_t> imageDataRecord = std::make_pair(ashmem, len); + imageDataMap_.emplace(Str16ToStr8(parcel.ReadString16()), imageDataRecord); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::Marshalling(Parcel &parcel) const +{ + APP_LOGI("%{public}s called, jsonFormProviderData_: %{public}s", __func__, jsonFormProviderData_.dump().c_str()); + if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? JSON_EMPTY_STRING : jsonFormProviderData_.dump()))) { + return false; + } + + parcel.WriteInt32(imageDataState_); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + if (rawImageBytesMap_.size() == 0) { + APP_LOGE("%{public}s failed, rawImageBytesMap_ is empty", __func__); + return false; + } + parcel.WriteInt32(rawImageBytesMap_.size()); // firstly write the number of shared image to add + for (auto &entry : rawImageBytesMap_) { + if (!WriteImageDataToParcel(parcel, entry.first, entry.second)) { + APP_LOGE("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); + return false; + } + parcel.WriteInt32(sizeof(entry.second)); + parcel.WriteString16(Str8ToStr16(entry.first)); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return FormProviderData. + */ +FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) +{ + std::unique_ptr formProviderData = std::make_unique(); + if (formProviderData && !formProviderData->ReadFromParcel(parcel)) { + formProviderData = nullptr; + } + return formProviderData.release(); +} + +/** + * @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_. + */ +void FormProviderData::ClearData() +{ + jsonFormProviderData_.clear(); +} + +bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const +{ + sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), sizeof(data)); + if (ashmem == nullptr) { + APP_LOGE("create shared memory fail"); + return false; + } + + bool ret = ashmem->MapReadAndWriteAshmem(); + if (!ret) { + APP_LOGE("map shared memory fail"); + return false; + } + + ret = ashmem->WriteToAshmem(data, sizeof(data), 0); + if (!ret) { + APP_LOGE("write image data to shared memory fail"); + return false; + } + + ashmem->UnmapAshmem(); + + MessageParcel* messageParcel = (MessageParcel*)&parcel; + ret = messageParcel->WriteAshmem(ashmem); + + ashmem->CloseAshmem(); // close ashmem after writeAshmem because writeAshmem will dup fd + if (!ret) { + APP_LOGE("writeAshmem fail, the picture name is %{public}s", picName.c_str()); + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/form_provider_info.cpp b/interfaces/innerkits/form_manager/src/form_provider_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0af60cc16357003853a63b7753c4431e5a758cab --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_provider_info.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_provider_info.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool FormProviderInfo::ReadFromParcel(Parcel &parcel) +{ + auto bindingData = parcel.ReadParcelable(); + jsBindingData_ = *bindingData; + return true; +} + +FormProviderInfo *FormProviderInfo::Unmarshalling(Parcel &parcel) +{ + std::unique_ptr formProviderInfo = std::make_unique(); + if (formProviderInfo && !formProviderInfo->ReadFromParcel(parcel)) { + formProviderInfo = nullptr; + } + return formProviderInfo.release(); +} + +bool FormProviderInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(&jsBindingData_)) { + return false; + } + return true; +} +void FormProviderInfo::SetFormDataString(std::string &dataString) +{ + jsBindingData_.SetDataString(dataString); +} +/** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ +void FormProviderInfo::MergeData(nlohmann::json &addJsonData) +{ + jsBindingData_.MergeData(addJsonData); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/form_provider_proxy.cpp b/interfaces/innerkits/form_manager/src/form_provider_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..edef08731a269b36a7355bdb747acc6445a75db9 --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_provider_proxy.cpp @@ -0,0 +1,376 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "form_provider_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the from. + * @param want Indicates the {@link Want} structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::AcquireProviderFormInfo( + const int64_t formId, + const Want &want, + const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s fail, write want error", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Notify provider when the form was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} +/** + * @brief Notify provider when the forms was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormsDelete( + const std::vector &formIds, + const Want &want, + const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt32(formVisibleType)) { + APP_LOGE("%{public}s, failed to write formVisibleType.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Notify provider when the temp form was cast to normal form. + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormCastTempForm( + const int64_t formId, + const Want &want, + const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::FireFormEvent( + const int64_t formId, + const std::string &message, + const Want &want, + const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteString(message)) { + APP_LOGE("%{public}s, failed to write message", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_MESSAGE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +template +int FormProviderProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to Read Parcelable infos", __func__); + return ERR_NULL_OBJECT; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("%{public}s, get parcelable infos success", __func__); + return ERR_OK; +} + +bool FormProviderProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormProviderProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/form_provider_stub.cpp b/interfaces/innerkits/form_manager/src/form_provider_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5577337a202d69592a35af0edd4a58b5a30d6ebb --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_provider_stub.cpp @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "app_scheduler_interface.h" +#include "errors.h" +#include "form_provider_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormProviderStub::FormProviderStub() +{ + memberFuncMap_[static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO)] = + &FormProviderStub::HandleAcquireProviderFormInfo; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE)] = + &FormProviderStub::HandleNotifyFormDelete; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE)] = + &FormProviderStub::HandleNotifyFormsDelete; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE)] = + &FormProviderStub::HandleNotifyFormUpdate; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY)] = + &FormProviderStub::HandleEventNotify; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST)] = + &FormProviderStub::HandleNotifyFormCastTempForm; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_MESSAGE)] = + &FormProviderStub::HandleFireFormEvent; +} + +FormProviderStub::~FormProviderStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormProviderStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormProviderStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle AcquireProviderFormInfo message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleAcquireProviderFormInfo(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = AcquireProviderFormInfo(formId, *want, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyFormDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormDelete(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = NotifyFormDelete(formId, *want, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyFormsDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormsDelete(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (ret) { + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = NotifyFormsDelete(formIds, *want, client); + reply.WriteInt32(result); + return result; + } + + return ERR_INVALID_DATA; +} +/** + * @brief handle NotifyFormUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormUpdate(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = NotifyFormUpdate(formId, *want, client); + reply.WriteInt32(result); + return result; +} + +/** + * @brief handle EventNotify message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleEventNotify(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (ret) { + int32_t formVisibleType = data.ReadInt32(); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = EventNotify(formIds, formVisibleType, *want, client); + reply.WriteInt32(result); + return result; + } + + return ERR_INVALID_DATA; +} + +/** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormCastTempForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = NotifyFormCastTempForm(formId, *want, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleFireFormEvent(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::string message = data.ReadString(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = FireFormEvent(formId, message, *want, client); + reply.WriteInt32(result); + return result; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/src/form_supply_proxy.cpp b/interfaces/innerkits/form_manager/src/form_supply_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c6429c672e12dbb4d7946e65f786555021cfce8 --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_supply_proxy.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "form_constants.h" +#include "form_supply_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Send form binding data from form provider to fms. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnAcquire(const FormProviderInfo &formInfo, const Want& want) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to WriteInterfaceToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK) == ERR_OK) { + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + + +/** + * @brief Send other event to fms. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnEventHandle(const Want& want) +{ + MessageParcel data; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + +template +int FormSupplyProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_INVALID_VALUE; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("get parcelable infos success"); + return ERR_OK; +} + +bool FormSupplyProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormSupplyProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token failed", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/form_supply_stub.cpp b/interfaces/innerkits/form_manager/src/form_supply_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d90492e1f04f1babc0790868e494432e44cbce1c --- /dev/null +++ b/interfaces/innerkits/form_manager/src/form_supply_stub.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_supply_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormSupplyStub::FormSupplyStub() +{ + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED)] = + &FormSupplyStub::HandleOnAcquire; + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE)] = + &FormSupplyStub::HandleOnEventHandle; +} + +FormSupplyStub::~FormSupplyStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormSupplyStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormSupplyStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle OnAcquire message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnAcquire(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_APPEXECFWK_PARCEL_ERROR); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int errCode = ERR_OK; + do { + errCode = want->GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s, provider error", __func__); + break; + } + std::unique_ptr formInfo(data.ReadParcelable()); + if (formInfo == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + errCode = ERR_APPEXECFWK_PARCEL_ERROR; + break; + } + int32_t result = OnAcquire(*formInfo, *want); + reply.WriteInt32(result); + return result; + } while (true); + + FormProviderInfo formProviderInfo; + want->SetParam(Constants::PROVIDER_FLAG, errCode); + OnAcquire(formProviderInfo, *want); + reply.WriteInt32(errCode); + return errCode; +} +/** + * @brief handle OnEventHandle message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnEventHandle(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_APPEXECFWK_PARCEL_ERROR); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = OnEventHandle(*want); + reply.WriteInt32(result); + return result; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/src/provider_connect_proxy.cpp b/interfaces/innerkits/form_manager/src/provider_connect_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14cf4a2ebc4ecb1363b083e60c0e73c477516b55 --- /dev/null +++ b/interfaces/innerkits/form_manager/src/provider_connect_proxy.cpp @@ -0,0 +1,108 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "provider_connect_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void ProviderConnectProxy::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGD("%{public}s, abilityName:%{public}s,resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return; + } + + if (!data.WriteParcelable(&element)) { + APP_LOGE("%{public}s, failed to write element", __func__); + return; + } + + if (!data.WriteRemoteObject(remoteObject)) { + APP_LOGE("%{public}s, failed to write remote object ", __func__); + return; + } + + if (!data.WriteInt32(resultCode)) { + APP_LOGE("%{public}s, failed to write resultCode", __func__); + return; + } + + error = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return; + } +} +/** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ +void ProviderConnectProxy::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + APP_LOGD("%{public}s, element:%{public}s, resultCode:%{public}d", __func__, element.GetURI().c_str(), resultCode); + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return; + } + if (!data.WriteParcelable(&element)) { + APP_LOGE("%{public}s, failed to write element", __func__); + return; + } + if (!data.WriteInt32(resultCode)) { + APP_LOGE("%{public}s, failed to write resultCode", __func__); + return; + } + + error = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_DISCONNECT_DONE, data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return; + } +} + +bool ProviderConnectProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(ProviderConnectProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/form_manager/src/provider_connect_stub.cpp b/interfaces/innerkits/form_manager/src/provider_connect_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d925c349a3de9606f17a04b1cf8720ba18b512ed --- /dev/null +++ b/interfaces/innerkits/form_manager/src/provider_connect_stub.cpp @@ -0,0 +1,74 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "provider_connect_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int ProviderConnectStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::u16string descriptor = ProviderConnectStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGI("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_INVALID_STATE; + } + + auto element = data.ReadParcelable(); + switch (code) { + case IAbilityConnection::ON_ABILITY_CONNECT_DONE: { + if (element == nullptr) { + APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + auto remoteObject = data.ReadRemoteObject(); + auto resultCode = data.ReadInt32(); + OnAbilityConnectDone(*element, remoteObject, resultCode); + delete element; + return ERR_OK; + } + case IAbilityConnection::ON_ABILITY_DISCONNECT_DONE: { + if (element == nullptr) { + APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + auto resultCode = data.ReadInt32(); + OnAbilityDisconnectDone(*element, resultCode); + delete element; + return ERR_OK; + } + default: { + if (element != nullptr) { + delete element; + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/intent/BUILD.gn b/interfaces/innerkits/intent/BUILD.gn index 176dd580ba056aae46d997671ac8ad53825b4851..e1b8cbd00689c35c350a6b8e9a9c430b67a51df4 100644 --- a/interfaces/innerkits/intent/BUILD.gn +++ b/interfaces/innerkits/intent/BUILD.gn @@ -69,5 +69,5 @@ ohos_shared_library("intent") { configs = [ ":intent_config" ] public_configs = [ ":intent_public_config" ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/innerkits/napi_base_context/BUILD.gn b/interfaces/innerkits/napi_base_context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..05a3d810a6713cf7bcb1df3ce80ea8dcd64e3bde --- /dev/null +++ b/interfaces/innerkits/napi_base_context/BUILD.gn @@ -0,0 +1,32 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +config("napi_context_base_public_config") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +ohos_shared_library("napi_base_context") { + sources = [ "src/napi_base_context.cpp" ] + + configs = [] + + public_configs = [ ":napi_context_base_public_config" ] + + external_deps = [ "napi:ace_napi" ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/innerkits/napi_base_context/include/napi_base_context.h b/interfaces/innerkits/napi_base_context/include/napi_base_context.h new file mode 100644 index 0000000000000000000000000000000000000000..2207ae2564961cc747d33a9be9492e0042ddf56c --- /dev/null +++ b/interfaces/innerkits/napi_base_context/include/napi_base_context.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_RUNTIME_NAPI_BASE_CONTEXT_H +#define ABILITY_RUNTIME_NAPI_BASE_CONTEXT_H + +#include + +#include "napi/native_api.h" + +namespace OHOS { +namespace AppExecFwk { +class Ability; +} +namespace AbilityRuntime { +napi_value* GetFAModeContextClassObject(); + +napi_status IsStageContext(napi_env env, napi_value object, bool& stageMode); + +class Context; +std::shared_ptr GetStageModeContext(napi_env env, napi_value object); + +AppExecFwk::Ability* GetCurrentAbility(napi_env env); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_NAPI_BASE_CONTEXT_H \ No newline at end of file diff --git a/interfaces/innerkits/napi_base_context/src/napi_base_context.cpp b/interfaces/innerkits/napi_base_context/src/napi_base_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e386b3c6eefaf5594ca99c3ed189189d7766d0fe --- /dev/null +++ b/interfaces/innerkits/napi_base_context/src/napi_base_context.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "napi_base_context.h" + +#define OHOS_CALL_NAPI_RETURN(call) \ + do { \ + napi_status ret = (call); \ + if (ret != napi_ok) { \ + return ret; \ + } \ + } while (0) + +namespace OHOS { +namespace AbilityRuntime { +namespace { +napi_status GetStageModeContextClassObject(napi_env env, napi_value& classObject) +{ + static thread_local napi_ref contextClassObjectRef = {0}; + + napi_status ret = napi_get_reference_value(env, contextClassObjectRef, &classObject); + if (ret == napi_ok) { + return napi_ok; + } + + napi_value global; + OHOS_CALL_NAPI_RETURN(napi_get_global(env, &global)); + + napi_value requireNapi; + OHOS_CALL_NAPI_RETURN(napi_get_named_property(env, global, "requireNapi", &requireNapi)); + + napi_value className; + OHOS_CALL_NAPI_RETURN(napi_create_string_utf8(env, "application.Context", NAPI_AUTO_LENGTH, &className)); + + OHOS_CALL_NAPI_RETURN(napi_call_function(env, global, requireNapi, 1, &className, &classObject)); + + // Ignore return value + napi_create_reference(env, classObject, 1, &contextClassObjectRef); + return napi_ok; +} +} // namespace + +napi_value* GetFAModeContextClassObject() +{ + static thread_local napi_value contextClassObject = {0}; + return &contextClassObject; +} + +napi_status IsStageContext(napi_env env, napi_value object, bool& stageMode) +{ + napi_value boolValue; + OHOS_CALL_NAPI_RETURN(napi_get_named_property(env, object, "stageMode", &boolValue)); + + bool value = false; + OHOS_CALL_NAPI_RETURN(napi_get_value_bool(env, boolValue, &value)); + + napi_value classObject; + if (value) { + OHOS_CALL_NAPI_RETURN(GetStageModeContextClassObject(env, classObject)); + } else { + napi_value* clsObjPtr = GetFAModeContextClassObject(); + if (clsObjPtr == nullptr) { + return napi_generic_failure; + } + classObject = *clsObjPtr; + } + + bool result = false; + OHOS_CALL_NAPI_RETURN(napi_instanceof(env, object, classObject, &result)); + if (!result) { + return napi_generic_failure; + } + + stageMode = value; + return napi_ok; +} + +std::shared_ptr GetStageModeContext(napi_env env, napi_value object) +{ + void* wrapped = nullptr; + napi_status ret = napi_unwrap(env, object, &wrapped); + if (ret != napi_ok) { + return nullptr; + } + + auto weakContext = static_cast*>(wrapped); + return weakContext != nullptr ? weakContext->lock() : nullptr; +} + +AppExecFwk::Ability* GetCurrentAbility(napi_env env) +{ + napi_value global; + napi_status status = napi_get_global(env, &global); + if (status != napi_ok) { + return nullptr; + } + + napi_value abilityObj; + status = napi_get_named_property(env, global, "ability", &abilityObj); + if (status != napi_ok || abilityObj == nullptr) { + return nullptr; + } + + void* pointer = nullptr; + status = napi_get_value_external(env, abilityObj, &pointer); + if (status != napi_ok) { + return nullptr; + } + + return static_cast(pointer); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/runtime/BUILD.gn b/interfaces/innerkits/runtime/BUILD.gn index 19aa60c882da8434e685de3a2f797c7fa56c7bf4..5d48fb098fa90ef1b6d04e23dc6ab6fb664be5d7 100644 --- a/interfaces/innerkits/runtime/BUILD.gn +++ b/interfaces/innerkits/runtime/BUILD.gn @@ -57,18 +57,20 @@ ohos_shared_library("runtime") { deps = [ "//ark/js_runtime:libark_jsruntime", + "//foundation/ace/ace_engine/interfaces/innerkits/ace:ace_uicontent", "//foundation/ace/napi:ace_napi", "//foundation/ace/napi:ace_napi_ark", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:libeventhandler", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/innerkits/runtime/include/js_data_struct_converter.h b/interfaces/innerkits/runtime/include/js_data_struct_converter.h index 739234ffd28951c31cdc3adb093c3d124dab91b3..1471092d179e3e95c3c5fc5fa4db4aefad7ac8c5 100644 --- a/interfaces/innerkits/runtime/include/js_data_struct_converter.h +++ b/interfaces/innerkits/runtime/include/js_data_struct_converter.h @@ -21,6 +21,7 @@ #include "launch_param.h" #include "module_info.h" #include "want.h" +#include "configuration.h" class NativeEngine; class NativeValue; @@ -32,6 +33,9 @@ NativeValue* CreateJsAbilityInfo(NativeEngine& engine, const AppExecFwk::Ability NativeValue* CreateJsModuleInfo(NativeEngine& engine, const AppExecFwk::ModuleInfo &moduleInfo); NativeValue* CreateJsApplicationInfo(NativeEngine& engine, const AppExecFwk::ApplicationInfo &applicationInfo); NativeValue* CreateJsLaunchParam(NativeEngine& engine, const AAFwk::LaunchParam& launchParam); +NativeValue* CreateJsCustomizeData(NativeEngine& engine, const AppExecFwk::CustomizeData &Info); +NativeValue* CreateJsCustomizeDataArray(NativeEngine& engine, const std::vector &info); +NativeValue* CreateJsConfiguration(NativeEngine& engine, const AppExecFwk::Configuration& configuration); } // namespace AbilityRuntime } // namespace OHOS #endif // ABILITY_RUNTIME_JS_DATA_STRUCT_CONVERTER_H \ No newline at end of file diff --git a/interfaces/innerkits/runtime/include/js_runtime.h b/interfaces/innerkits/runtime/include/js_runtime.h index 0165f2f7908f6cd35026f514de1bb0de9e14a667..c7299a2964346113135a61ac8b22cf7abcc62360 100644 --- a/interfaces/innerkits/runtime/include/js_runtime.h +++ b/interfaces/innerkits/runtime/include/js_runtime.h @@ -56,6 +56,7 @@ public: void RemoveTask(const std::string& name); NativeValue* SetCallbackTimer(NativeEngine& engine, NativeCallbackInfo& info, bool isInterval); NativeValue* ClearCallbackTimer(NativeEngine& engine, NativeCallbackInfo& info); + std::string BuildNativeAndJsBackStackTrace(); protected: JsRuntime() = default; @@ -73,7 +74,6 @@ protected: uint32_t callbackId_ = 0; std::unordered_map modules_; - std::function idleTask_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/innerkits/want/BUILD.gn b/interfaces/innerkits/want/BUILD.gn index 2568619f53b9a4d968a21879146d6e8737057126..22c3ae7cb8490f3cf15c605647b90dbde531c512 100644 --- a/interfaces/innerkits/want/BUILD.gn +++ b/interfaces/innerkits/want/BUILD.gn @@ -70,7 +70,7 @@ ohos_shared_library("want") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -78,5 +78,5 @@ ohos_shared_library("want") { configs = [ ":want_config" ] public_configs = [ ":want_public_config" ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h index 0127fedd27838ad0535f84011dfd7888aa17f401..1c571636cbb2f9e46917b6855e9d9debf3c16f59 100644 --- a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h @@ -787,6 +787,12 @@ public: static constexpr int HEX_STRING_BUF_LEN = 36; static constexpr int HEX_STRING_LEN = 10; + // reserved param definition + static const std::string PARAM_RESV_WINDOW_MODE; + static const std::string PARAM_RESV_CALLER_TOKEN; + static const std::string PARAM_RESV_CALLER_UID; + static const std::string PARAM_RESV_CALLER_PID; + private: WantParams parameters_; Operation operation_; diff --git a/interfaces/kits/js/@ohos.app.abilityManager.d.ts b/interfaces/kits/js/@ohos.app.abilityManager.d.ts index f5b7ce142bba7689cf309a9a71ed5d8c977fa426..8bec57baa5f2a473ed744824999f645e61eba59a 100644 --- a/interfaces/kits/js/@ohos.app.abilityManager.d.ts +++ b/interfaces/kits/js/@ohos.app.abilityManager.d.ts @@ -28,13 +28,6 @@ import { ActiveProcessInfo } from './app/activeProcessInfo'; */ declare namespace abilityManager { - enum ProcessErrCode { - NO_ERROR = 0, - CRASHED, - NO_RESPONSE, - } - - /** * Get information about running processes * @since 7 diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn index ebe5c1800964205ae79537daf02f07c77c235c2e..56167c6d2addf26c81fa85ec9ee9b09786ac5bb6 100644 --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -18,19 +18,36 @@ group("napi_packages") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/ability:ability_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/abilityManager:abilitymanager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/ability_context:abilitycontext_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/ability_manager:abilitymanager_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/ability_delegator:abilitydelegatorregistry", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/ability_stage:abilitystage_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/ability_stage_context:abilitystagecontext_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/appMgr:napi_app_mgr", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/app_manager:appmanager_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/context:context_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/test_runner:testrunner_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/callee:callee_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/caller:caller_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/extensioncontext:extensioncontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility:featureability", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/formManager:formmanager", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/form_binding_data:formbindingdata_napi", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/form_extension:formextension_napi", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/form_extension_context:formextensioncontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/mission_manager:distributedmissionmanager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/mission_manager:missionmanager_napi", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/mission_manager:missionregistration_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/particleAbility:particleability", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/service_extension_context:serviceextensioncontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/serviceextension:serviceextension_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/static_subscriber_extension:staticsubscriberextension_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/static_subscriber_extension_context:staticsubscriberextensioncontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/wantConstant:wantconstant", ] } + +group("form_napi_packages") { + deps = [ + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/formManager:formmanager", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/form_binding_data:formbindingdata_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/form_extension:formextension_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/form_extension_context:formextensioncontext_napi", + ] +} diff --git a/interfaces/kits/napi/aafwk/ability/BUILD.gn b/interfaces/kits/napi/aafwk/ability/BUILD.gn index adb988d4ea612835f21305a06880c9b38176c9ca..d74b3879e510c6b221e84568730cd93690b09d02 100644 --- a/interfaces/kits/napi/aafwk/ability/BUILD.gn +++ b/interfaces/kits/napi/aafwk/ability/BUILD.gn @@ -45,5 +45,5 @@ ohos_shared_library("ability_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/ability/ability.js b/interfaces/kits/napi/aafwk/ability/ability.js old mode 100644 new mode 100755 index 01d390e9d6e66d810f00f87a5b87ee0095b12383..2586a5e1d1ccccce2a85c5ea73950647390805d5 --- a/interfaces/kits/napi/aafwk/ability/ability.js +++ b/interfaces/kits/napi/aafwk/ability/ability.js @@ -12,9 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +var Callee = requireNapi("application.Callee") class Ability { - constructor() {} + constructor() { + this.callee = new Callee("rpc.application.callee"); + console.log("Ability::constructor callee is " + typeof this.callee + " " + this.callee); + } onCreate(want) {} onDestroy() {} onWindowStageCreate(windowStage) {} @@ -22,6 +26,13 @@ class Ability { onForeground(want) {} onBackground() {} onWindowStageRestore(windowStage) {} + onCallRequest() { + console.log("Ability::onCallRequest callee is " + typeof this.callee + " " + this.callee); + return this.callee; + } + onContinue(wantParams) {} + onConfigurationUpdated(config) {} + onNewWant(want) {} } -export default Ability +export default Ability \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/abilityManager/BUILD.gn b/interfaces/kits/napi/aafwk/abilityManager/BUILD.gn index 37e7973e84402a8286c460dc23115573ff4c2e19..d53939b18a2ca698b8e4e90bdf0bb8f846f4ebd6 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/BUILD.gn +++ b/interfaces/kits/napi/aafwk/abilityManager/BUILD.gn @@ -27,21 +27,21 @@ ohos_shared_library("abilitymanager") { "napi_ability_manager.cpp", "native_module.cpp", ] - ldflags = [ "-Wl,-rpath=/system/lib/module/multimedia/" ] deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/appmgr:libams", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_target", - "//foundation/appexecfwk/standard/services/appmgr:libams", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimedia/image_standard/interfaces/innerkits:image", @@ -57,5 +57,5 @@ ohos_shared_library("abilitymanager") { relative_install_dir = "module/app" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h index c4c8b11ad11ba5538d2a10b36a1e42d8e06d73f1..63ef91ff3c7300ad20dbe09f65e94526fbf4570d 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h +++ b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h @@ -19,6 +19,7 @@ #include #include "ability_mission_info.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" #include "pixel_map_napi.h" @@ -161,4 +162,4 @@ napi_value NapiGetNull(napi_env env); napi_value NAPI_GetSystemMemoryAttr(napi_env env, napi_callback_info); } // namespace AppExecFwk } // namespace OHOS -#endif // NAPI_ABILITY_MANAGER_H \ No newline at end of file +#endif // NAPI_ABILITY_MANAGER_H diff --git a/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp b/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp index 0a458fc94ae189594fc93e0b686999235506afac..63dbcc6530773c55e7492e2927dc53285cae191c 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp +++ b/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp @@ -46,6 +46,7 @@ static napi_value Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("queryRecentAbilityMissionInfos", NAPI_QueryRecentAbilityMissionInfos), DECLARE_NAPI_FUNCTION("getPreviousAbilityMissionInfos", NAPI_GetPreviousAbilityMissionInfos), DECLARE_NAPI_FUNCTION("removeMission", NAPI_RemoveMission), + DECLARE_NAPI_FUNCTION("removeRecentTask", NAPI_RemoveMission), DECLARE_NAPI_FUNCTION("removeMissions", NAPI_RemoveMissions), DECLARE_NAPI_FUNCTION("deleteMissions", NAPI_RemoveMissions), DECLARE_NAPI_FUNCTION("clearMissions", NAPI_ClearMissions), diff --git a/interfaces/kits/napi/aafwk/ability_context/BUILD.gn b/interfaces/kits/napi/aafwk/ability_context/BUILD.gn index 60aae2e24ee50ff5c3310555eb5f5cc1c5ef2804..1c7998668d7530dbad0975254c7f42141229dc2c 100644 --- a/interfaces/kits/napi/aafwk/ability_context/BUILD.gn +++ b/interfaces/kits/napi/aafwk/ability_context/BUILD.gn @@ -46,5 +46,5 @@ ohos_shared_library("abilitycontext_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/ability_context/ability_context.js b/interfaces/kits/napi/aafwk/ability_context/ability_context.js index 98e7334cd04df442230442ae9a003ebf099bacd6..7922079eeaaa6a0c0c615a57a16d828d290a6fb2 100755 --- a/interfaces/kits/napi/aafwk/ability_context/ability_context.js +++ b/interfaces/kits/napi/aafwk/ability_context/ability_context.js @@ -14,26 +14,60 @@ */ var Context = requireNapi("application.Context") +var Caller = requireNapi("application.Caller") class AbilityContext extends Context { constructor(obj) { super(obj) this.abilityInfo = obj.abilityInfo this.currentHapModuleInfo = obj.currentHapModuleInfo + this.configuration = obj.configuration + } + + onUpdateConfiguration(config) { + this.configuration = config } startAbility(want, options, callback) { return this.__context_impl__.startAbility(want, options, callback) } + startAbilityWithAccount(want, accountId, options, callback) { + return this.__context_impl__.startAbilityWithAccount(want, accountId, options, callback) + } + + startAbilityByCall(want) { + if (typeof want !== 'object' || want == null) { + console.log("AbilityContext::startAbilityByCall input param error"); + return null; + } + + let callee = this.__context_impl__.startAbilityByCall(want); + if (typeof callee === 'object' && callee != null) { + console.log("AbilityContext::startAbilityByCall"); + return new Caller(callee); + } else { + console.log("AbilityContext::startAbilityByCall Obtain remoteObject falied"); + return null; + } + } + startAbilityForResult(want, callback) { return this.__context_impl__.startAbilityForResult(want, callback) } + startAbilityForResultWithAccount(want, accountId, callback) { + return this.__context_impl__.startAbilityForResultWithAccount(want, accountId, callback) + } + connectAbility(want, options) { return this.__context_impl__.connectAbility(want, options); } + connectAbilityWithAccount(want, accountId, options) { + return this.__context_impl__.connectAbilityWithAccount(want, accountId, options); + } + disconnectAbility(connection, callback) { return this.__context_impl__.disconnectAbility(connection, callback); } @@ -46,8 +80,8 @@ class AbilityContext extends Context { return this.__context_impl__.terminateSelfWithResult(abilityResult, callback) } - requestPermissionsFromUser(permissions, requestCode, resultCallback) { - return this.__context_impl__.requestPermissionsFromUser(permissions, requestCode, resultCallback) + requestPermissionsFromUser(permissions, resultCallback) { + return this.__context_impl__.requestPermissionsFromUser(permissions, resultCallback) } restoreWindowStage(contentStorage) { @@ -55,4 +89,4 @@ class AbilityContext extends Context { } } -export default AbilityContext +export default AbilityContext \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/ability_manager/BUILD.gn b/interfaces/kits/napi/aafwk/ability_manager/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8db081cd2dec7ef8cfd3670ad4c2c404c0421cc8 --- /dev/null +++ b/interfaces/kits/napi/aafwk/ability_manager/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("abilitymanager_napi") { + include_dirs = [] + + sources = [ + "ability_manager_module.cpp", + "js_ability_manager.cpp", + "js_ability_manager_utils.cpp", + ] + + configs = [ "//foundation/aafwk/standard/services/common:common_config" ] + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/ability_manager", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + "//base/global/resmgr_standard/interfaces/innerkits/include", + "//third_party/icu/icu4c/source/common", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/kits", + "//foundation/communication/ipc/ipc/native/src/napi/include", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "ipc_js:rpc", + ] + + relative_install_dir = "module/application" + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/ability_manager/ability_manager_module.cpp b/interfaces/kits/napi/aafwk/ability_manager/ability_manager_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..261cba341f053ad4b60460a78c7dfe9f37f11ccf --- /dev/null +++ b/interfaces/kits/napi/aafwk/ability_manager/ability_manager_module.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" +#include "js_ability_manager.h" + +extern "C" __attribute__((constructor)) +void NAPI_application_AbilityManager_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AbilityManager", + .fileName = "application/abilitymanager_napi.so/ability_manager.js", + .registerCallback = OHOS::AbilityRuntime::JsAbilityManagerInit, + }; + + moduleManager->Register(&newModuleInfo); +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager.cpp b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61d80b2627a738612eb6879cebda03522997968e --- /dev/null +++ b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_ability_manager.h" + +#include + +#include "ability_manager_client.h" +#include "hilog_wrapper.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "js_ability_manager_utils.h" +#include "event_runner.h" +#include "napi_common_configuration.h" + +namespace OHOS { +namespace AbilityRuntime { +using AbilityManagerClient = AAFwk::AbilityManagerClient; +namespace { +class JsAbilityManager final { +public: + JsAbilityManager() = default; + ~JsAbilityManager() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsAbilityManager::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static NativeValue* GetAbilityRunningInfos(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAbilityManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetAbilityRunningInfos(*engine, *info) : nullptr; + } + + static NativeValue* GetExtensionRunningInfos(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAbilityManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetExtensionRunningInfos(*engine, *info) : nullptr; + } + + static NativeValue* UpdateConfiguration(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAbilityManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnUpdateConfiguration(*engine, *info) : nullptr; + } + +private: + NativeValue* OnGetAbilityRunningInfos(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + AsyncTask::CompleteCallback complete = + [](NativeEngine &engine, AsyncTask &task, int32_t status) { + std::vector infos; + auto errcode = AbilityManagerClient::GetInstance()->GetAbilityRunningInfos(infos); + if (errcode == 0) { + task.Resolve(engine, CreateJsAbilityRunningInfoArray(engine, infos)); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Get mission infos failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnGetExtensionRunningInfos(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + int upperLimit = -1; + if (!ConvertFromJsValue(engine, info.argv[0], upperLimit)) { + HILOG_ERROR("Parse missionId failed"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = + [upperLimit](NativeEngine &engine, AsyncTask &task, int32_t status) { + std::vector infos; + auto errcode = AbilityManagerClient::GetInstance()->GetExtensionRunningInfos(upperLimit, infos); + if (errcode == 0) { + task.Resolve(engine, CreateJsExtensionRunningInfoArray(engine, infos)); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Get mission infos failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnUpdateConfiguration(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + AppExecFwk::Configuration changeConfig; + if (!UnwrapConfiguration(reinterpret_cast(&engine), + reinterpret_cast(info.argv[0]), changeConfig)) { + HILOG_INFO("OnStartAbility start options is used."); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [changeConfig](NativeEngine& engine, AsyncTask& task, int32_t status) { + auto errcode = AbilityManagerClient::GetInstance()->UpdateConfiguration(changeConfig); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "update config failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } +}; +} // namespace + +NativeValue* JsAbilityManagerInit(NativeEngine* engine, NativeValue* exportObj) +{ + HILOG_INFO("JsAbilityManagerInit is called"); + + if (engine == nullptr || exportObj == nullptr) { + HILOG_INFO("engine or exportObj null"); + return nullptr; + } + + NativeObject* object = ConvertNativeValueTo(exportObj); + if (object == nullptr) { + HILOG_INFO("object null"); + return nullptr; + } + + std::unique_ptr jsAbilityManager = std::make_unique(); + object->SetNativePointer(jsAbilityManager.release(), JsAbilityManager::Finalizer, nullptr); + + HILOG_INFO("JsAbilityManagerInit BindNativeFunction called"); + BindNativeFunction(*engine, *object, "getAbilityRunningInfos", JsAbilityManager::GetAbilityRunningInfos); + BindNativeFunction(*engine, *object, "getExtensionRunningInfos", JsAbilityManager::GetExtensionRunningInfos); + BindNativeFunction(*engine, *object, "updateConfiguration", JsAbilityManager::UpdateConfiguration); + HILOG_INFO("JsAbilityManagerInit end"); + return engine->CreateUndefined(); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_manager.h b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager.h similarity index 74% rename from frameworks/kits/ability/native/src/ability_runtime/window/js_window_manager.h rename to interfaces/kits/napi/aafwk/ability_manager/js_ability_manager.h index d6f32d1641d0b83a34968da2ab23b856896c0d6f..d209c8dd966d5c05d2125a608d435e4e7b3927d5 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_manager.h +++ b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager.h @@ -14,13 +14,14 @@ */ #include "native_engine/native_engine.h" -#include "native_engine/native_value.h" -#ifndef OHOS_JS_WINDOW_MANAGER_H -#define OHOS_JS_WINDOW_MANAGER_H +#include "event_handler.h" + +#ifndef OHOS_ABILITY_RUNTIME_ABILITY_MANAGER_H +#define OHOS_ABILITY_RUNTIME_ABILITY_MANAGER_H + namespace OHOS { namespace AbilityRuntime { -NativeValue* JsWindowManagerInit(NativeEngine* engine, NativeValue* exportObj); +NativeValue* JsAbilityManagerInit(NativeEngine* engine, NativeValue* exportObj); } // namespace AbilityRuntime } // namespace OHOS - -#endif +#endif // OHOS_ABILITY_RUNTIME_ABILITY_MANAGER_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager_utils.cpp b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6bd63887cc47803c35442f8968dc681bb17f170 --- /dev/null +++ b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager_utils.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_ability_manager_utils.h" + +#include + +#include "hilog_wrapper.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +napi_value CreateJSToken(napi_env env, const sptr target) +{ + napi_value tokenClass = nullptr; + auto constructorcb = [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }; + napi_define_class( + env, "TokenClass", NAPI_AUTO_LENGTH, constructorcb, nullptr, 0, nullptr, &tokenClass); + napi_value jsToken = nullptr; + napi_new_instance(env, tokenClass, 0, nullptr, &jsToken); + auto finalizecb = [](napi_env env, void *data, void *hint) {}; + napi_wrap(env, jsToken, (void *)target.GetRefPtr(), finalizecb, nullptr, nullptr); + return jsToken; +} + +NativeValue* CreateJsAbilityRunningInfoArray( + NativeEngine &engine, const std::vector &infos) +{ + NativeValue* arrayValue = engine.CreateArray(infos.size()); + NativeArray* array = ConvertNativeValueTo(arrayValue); + uint32_t index = 0; + for (const auto &runningInfo : infos) { + array->SetElement(index++, CreateJsAbilityRunningInfo(engine, runningInfo)); + } + return arrayValue; +} + +NativeValue* CreateJsExtensionRunningInfoArray( + NativeEngine &engine, const std::vector &infos) +{ + NativeValue* arrayValue = engine.CreateArray(infos.size()); + NativeArray* array = ConvertNativeValueTo(arrayValue); + uint32_t index = 0; + for (const auto &runningInfo : infos) { + array->SetElement(index++, CreateJsExtensionRunningInfo(engine, runningInfo)); + } + return arrayValue; +} + +NativeValue* CreateJsAbilityRunningInfo(NativeEngine &engine, const AAFwk::AbilityRunningInfo &info) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + napi_value napiElementName = + OHOS::AppExecFwk::WrapElementName(reinterpret_cast(&engine), info.ability); + object->SetProperty("ability", reinterpret_cast(napiElementName)); + object->SetProperty("pid", CreateJsValue(engine, info.pid)); + object->SetProperty("uid", CreateJsValue(engine, info.uid)); + object->SetProperty("processName", CreateJsValue(engine, info.processName)); + object->SetProperty("startTime", CreateJsValue(engine, info.startTime)); + object->SetProperty("abilityState", CreateJsValue(engine, info.abilityState)); + return objValue; +} + +NativeValue* CreateJsExtensionRunningInfo(NativeEngine &engine, const AAFwk::ExtensionRunningInfo &info) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + napi_value napiElementName = + OHOS::AppExecFwk::WrapElementName(reinterpret_cast(&engine), info.extension); + object->SetProperty("extension", reinterpret_cast(napiElementName)); + object->SetProperty("pid", CreateJsValue(engine, info.pid)); + object->SetProperty("uid", CreateJsValue(engine, info.uid)); + object->SetProperty("type", CreateJsValue(engine, info.type)); + object->SetProperty("processName", CreateJsValue(engine, info.processName)); + object->SetProperty("startTime", CreateJsValue(engine, info.startTime)); + object->SetProperty("clientPackage", CreateNativeArray(engine, info.clientPackage)); + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager_utils.h b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..855a34720f7fffd1d975fcc8e326e68315169fce --- /dev/null +++ b/interfaces/kits/napi/aafwk/ability_manager/js_ability_manager_utils.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_running_info.h" +#include "extension_running_info.h" +#include "native_engine/native_engine.h" + +#ifndef OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H +#define OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsAbilityRunningInfoArray( + NativeEngine &engine, const std::vector &infos); +NativeValue* CreateJsExtensionRunningInfoArray( + NativeEngine &engine, const std::vector &infos); +NativeValue* CreateJsAbilityRunningInfo(NativeEngine &engine, const AAFwk::AbilityRunningInfo &info); +NativeValue* CreateJsExtensionRunningInfo(NativeEngine &engine, const AAFwk::ExtensionRunningInfo &info); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/BUILD.gn b/interfaces/kits/napi/aafwk/app/ability_delegator/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..da7a4cbcaafb060d2ae70696fef4d5a843ddc604 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("abilitydelegatorregistry") { + include_dirs = [ + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/", + "//foundation/communication/ipc/ipc/native/src/napi/include/", + "//foundation/ace/napi/native_engine/", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/ability_delegator/", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_delegator/include/", + ] + + sources = [ + "ability_monitor.cpp", + "js_ability_delegator.cpp", + "js_ability_delegator_registry.cpp", + "js_ability_delegator_utils.cpp", + "js_ability_monitor.cpp", + "native_module.cpp", + ] + + configs = [ "//foundation/aafwk/standard/services/common:common_config" ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + ] + + external_deps = [ + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "ipc_js:rpc", + ] + + relative_install_dir = "module/application" + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..600f104ba571c121bc6ad1fa5af9a3efa360b4e6 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_monitor.h" + +#include "hilog_wrapper.h" +#include "js_ability_delegator_utils.h" +#include "napi/native_common.h" + +namespace OHOS { +namespace AbilityDelegatorJs { +using namespace OHOS::AbilityRuntime; +AbilityMonitor::AbilityMonitor(const std::string &name, JSAbilityMonitor *jsAbilityMonitor) + : IAbilityMonitor(name), jsMonitor_(jsAbilityMonitor) +{} + +void AbilityMonitor::onAbilityStart() +{ + HILOG_INFO("onAbilityCreate is called"); + + if (jsMonitor_ == nullptr) { + return; + } + + jsMonitor_->onAbilityCreate(); + + HILOG_INFO("onAbilityCreate is called end"); +} + +void AbilityMonitor::onAbilityForeground() +{ + HILOG_INFO("onAbilityForeground is called"); + + if (jsMonitor_ == nullptr) { + return; + } + + jsMonitor_->onAbilityForeground(); + + HILOG_INFO("onAbilityForeground is called end"); +} + +void AbilityMonitor::onAbilityBackground() +{ + HILOG_INFO("onAbilityBackground is called"); + + if (jsMonitor_ == nullptr) { + return; + } + + jsMonitor_->onAbilityBackground(); + + HILOG_INFO("onAbilityBackground is called end"); +} + +void AbilityMonitor::onAbilityStop() +{ + HILOG_INFO("onAbilityDestroy is called"); + + if (jsMonitor_ == nullptr) { + return; + } + + jsMonitor_->onAbilityDestroy(); + + HILOG_INFO("onAbilityDestroy is called end"); +} + +void AbilityMonitor::onWindowStageCreate() +{ + HILOG_INFO("onWindowStageCreate is called"); + + if (jsMonitor_ == nullptr) { + return; + } + + jsMonitor_->onWindowStageCreate(); + + HILOG_INFO("onWindowStageCreate is called end"); +} + +void AbilityMonitor::onWindowStageRestore() +{ + HILOG_INFO("onWindowStageRestore is called"); + + if (jsMonitor_ == nullptr) { + return; + } + + jsMonitor_->onWindowStageRestore(); + + HILOG_INFO("onWindowStageRestore is called end"); +} + +void AbilityMonitor::onWindowStageDestroy() +{ + HILOG_INFO("onWindowStageDestroy is called"); + + if (jsMonitor_ == nullptr) { + return; + } + + jsMonitor_->onWindowStageDestroy(); + + HILOG_INFO("onWindowStageDestroy is called end"); +} +} // namespace AbilityDelegatorJs +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.h b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..1f00888d0e3f4d208e9728b0a79f338582f93f0e --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_DELEGATOR_ABILITY_MONITOR_H +#define OHOS_ABILITY_DELEGATOR_ABILITY_MONITOR_H + +#include +#include "iability_monitor.h" +#include "js_ability_monitor.h" +#include "native_engine/native_reference.h" + +class NativeReference; +class NativeValue; + +namespace OHOS { +namespace AbilityDelegatorJs { +using namespace OHOS::AppExecFwk; +using Function = void(*)(); +class AbilityMonitor : public IAbilityMonitor { +public: + AbilityMonitor(const std::string &name, JSAbilityMonitor *jsAbilityMonitor); + ~AbilityMonitor() = default; + + void onAbilityStart(); + void onAbilityForeground(); + void onAbilityBackground(); + void onAbilityStop(); + void onWindowStageCreate(); + void onWindowStageRestore(); + void onWindowStageDestroy(); + +private: + std::shared_ptr jsMonitor_; +}; +} // namespace AbilityDelegatorJs +} // namespace OHOS +#endif // OHOS_ABILITY_DELEGATOR_JS_ABILITY_MONITOR_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f7da618ea3cfa55b4d8ab662efd47c3e0268902e --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.cpp @@ -0,0 +1,515 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_ability_delegator.h" + +#include "ability_delegator_registry.h" +#include "ability_runtime/js_ability.h" +#include "hilog_wrapper.h" +#include "js_ability_delegator_utils.h" +#include "js_context_utils.h" +#include "js_runtime_utils.h" +#include "napi_remote_object.h" +#include "shell_cmd_result.h" + +namespace OHOS { +namespace AbilityDelegatorJs { +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; +constexpr size_t ARGC_THREE = 3; +constexpr size_t ARGC_FOUR = 4; +constexpr size_t INDEX_ZERO = 0; +constexpr size_t INDEX_ONE = 1; +constexpr size_t INDEX_TWO = 2; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; +std::map, std::shared_ptr> monitorRecord; +std::map, sptr> ablityRecord; + +void JSAbilityDelegator::Finalizer(NativeEngine *engine, void *data, void *hint) +{ + HILOG_INFO("JSAbilityDelegator::Finalizer is called"); + std::unique_ptr(static_cast(data)); +} + +NativeValue *JSAbilityDelegator::AddAbilityMonitor(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnAddAbilityMonitor(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::RemoveAbilityMonitor(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnRemoveAbilityMonitor(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::WaitAbilityMonitor(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnWaitAbilityMonitor(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::GetAppContext(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetAppContext(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::GetAbilityState(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetAbilityState(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::GetCurrentTopAbility(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetCurrentTopAbility(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::DoAbilityForeground(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnDoAbilityForeground(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::DoAbilityBackground(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnDoAbilityBackground(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::Print(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnPrint(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::ExecuteShellCommand(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnExecuteShellCommand(*engine, *info) : nullptr; +} + +NativeValue *JSAbilityDelegator::OnAddAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnAddAbilityMonitor is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + std::shared_ptr monitor = nullptr; + if (!ParseJSMonitorPara(engine, info.argv[INDEX_ZERO], monitor)) { + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [monitor](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnAddAbilityMonitor AsyncTask is called"); + AbilityDelegatorRegistry::GetAbilityDelegator()->AddAbilityMonitor(monitor); + task.Resolve(engine, engine.CreateUndefined()); + }; + + NativeValue *lastParam = (info.argc == ARGC_TWO) ? info.argv[INDEX_ONE] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnRemoveAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnRemoveAbilityMonitor is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + std::shared_ptr monitor = nullptr; + if (!ParseJSMonitorPara(engine, info.argv[INDEX_ZERO], monitor)) { + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = + [monitor](NativeEngine &engine, AsyncTask &task, int32_t status) mutable { + HILOG_INFO("OnRemoveAbilityMonitor AsyncTask is called"); + AbilityDelegatorRegistry::GetAbilityDelegator()->RemoveAbilityMonitor(monitor); + task.Resolve(engine, engine.CreateUndefined()); + }; + + NativeValue *lastParam = (info.argc == ARGC_TWO) ? info.argv[INDEX_ONE] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + + for (auto iter = monitorRecord.begin(); iter != monitorRecord.end(); ++iter) { + std::shared_ptr jsMonitor = iter->first; + if ((info.argv[INDEX_ZERO])->StrictEquals(jsMonitor->Get())) { + monitorRecord.erase(iter); + break; + } + } + + return result; +} + +NativeValue *JSAbilityDelegator::OnWaitAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnWaitAbilityMonitor is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_THREE) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + std::shared_ptr monitor = nullptr; + if (!ParseJSMonitorPara(engine, info.argv[INDEX_ZERO], monitor)) { + return engine.CreateUndefined(); + } + + bool hasTimeoutPara = false; + int64_t timeout = 0; + if (info.argc >= ARGC_TWO) { + if (!ConvertFromJsValue(engine, info.argv[INDEX_ONE], timeout)) { + HILOG_ERROR("Parse timeout failed"); + } else { + hasTimeoutPara = true; + } + } + + int argcnum = info.argc; + AsyncTask::CompleteCallback complete = + [argcnum, monitor, timeout, hasTimeoutPara, this](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnWaitAbilityMonitor AsyncTask is called"); + sptr remoteObject = nullptr; + if (((argcnum == ARGC_TWO) && !hasTimeoutPara) || (argcnum == ARGC_ONE)) { + remoteObject = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->WaitAbilityMonitor(monitor); + } else if (((argcnum == ARGC_TWO) && hasTimeoutPara) || (argcnum == ARGC_THREE)) { + remoteObject = + AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->WaitAbilityMonitor(monitor, timeout); + } + task.Resolve(engine, CreateJsAbilityObject(engine, remoteObject)); + }; + + NativeValue *lastParam = nullptr; + if ((argcnum == ARGC_ONE) || ((argcnum == ARGC_TWO) && hasTimeoutPara)) { + lastParam = nullptr; + } else if ((argcnum == ARGC_TWO) && !hasTimeoutPara) { + lastParam = info.argv[INDEX_ONE]; + } else if (argcnum == ARGC_THREE) { + lastParam = info.argv[INDEX_TWO]; + } + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnPrint(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnPrint is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + std::string msg; + if (!ConvertFromJsValue(engine, info.argv[INDEX_ZERO], msg)) { + HILOG_ERROR("Parse para failed"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [msg](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnPrint AsyncTask is called"); + AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->Print(msg); + task.Resolve(engine, engine.CreateUndefined()); + }; + + NativeValue *lastParam = (info.argc == ARGC_TWO) ? info.argv[INDEX_ONE] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnExecuteShellCommand(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnExecuteShellCommand is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_FOUR) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + std::string cmd; + bool hasTimeoutPara = false; + int64_t timeoutSecs = 0; + if (!ParseJSExecuteShellCommandPara(engine, info, cmd, timeoutSecs, hasTimeoutPara)) { + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [cmd, timeoutSecs](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnExecuteShellCommand AsyncTask is called"); + std::unique_ptr shellResult = + AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->ExecuteShellCommand(cmd, timeoutSecs); + task.Resolve(engine, CreateJsShellCmdResult(engine, shellResult)); + }; + + int argcnum = info.argc; + NativeValue *lastParam = nullptr; + if ((argcnum == ARGC_ONE) || ((argcnum == ARGC_TWO) && hasTimeoutPara)) { + lastParam = nullptr; + } else if ((argcnum == ARGC_TWO) && !hasTimeoutPara) { + lastParam = info.argv[INDEX_ONE]; + } else if (argcnum == ARGC_THREE) { + lastParam = info.argv[INDEX_TWO]; + } + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnGetAppContext(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnGetAppContext is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc > ARGC_ONE) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnGetAppContext AsyncTask is called"); + std::shared_ptr context = + AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->GetAppContext(); + task.Resolve(engine, CreateJsBaseContext(engine, context, false)); + }; + + NativeValue *lastParam = (info.argc == ARGC_ONE) ? info.argv[INDEX_ZERO] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnGetAbilityState(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnGetAbilityState is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + sptr remoteObject = nullptr; + if (!ParseJSAbilityPara(engine, info.argv[INDEX_ZERO], remoteObject)) { + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [remoteObject](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnGetAbilityState AsyncTask is called"); + AbilityDelegator::AbilityState lifeState = + AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->GetAbilityState(remoteObject); + task.Resolve(engine, CreateJsAbilityState(engine, lifeState)); + }; + + NativeValue *lastParam = (info.argc == ARGC_TWO) ? info.argv[INDEX_ONE] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnGetCurrentTopAbility(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnGetCurrentTopAbility is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc > ARGC_ONE) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [this](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnGetCurrentTopAbility AsyncTask is called"); + sptr remoteObject = + AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->GetCurrentTopAbility(); + task.Resolve(engine, CreateJsAbilityObject(engine, remoteObject)); + }; + + NativeValue *lastParam = (info.argc == ARGC_ONE) ? info.argv[INDEX_ZERO] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnDoAbilityForeground(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnDoAbilityForeground is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + sptr remoteObject = nullptr; + if (!ParseJSAbilityPara(engine, info.argv[INDEX_ZERO], remoteObject)) { + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [remoteObject](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnDoAbilityForeground AsyncTask is called"); + bool ret = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->DoAbilityForeground(remoteObject); + task.Resolve(engine, CreateJsBool(engine, ret)); + }; + + NativeValue *lastParam = (info.argc == ARGC_TWO) ? info.argv[INDEX_ONE] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::OnDoAbilityBackground(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnDoAbilityBackground is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + sptr remoteObject = nullptr; + if (!ParseJSAbilityPara(engine, info.argv[INDEX_ZERO], remoteObject)) { + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [remoteObject](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnDoAbilityBackground AsyncTask is called"); + bool ret = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->DoAbilityBackground(remoteObject); + task.Resolve(engine, CreateJsBool(engine, ret)); + }; + + NativeValue *lastParam = (info.argc == ARGC_TWO) ? info.argv[INDEX_ONE] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue *JSAbilityDelegator::ParseJSMonitorPara( + NativeEngine &engine, NativeValue *value, std::shared_ptr &monitor) +{ + HILOG_INFO("ParseJSMonitorPara is called, monitorRecord size = %{public}zu", monitorRecord.size()); + + for (auto iter = monitorRecord.begin(); iter != monitorRecord.end(); ++iter) { + std::shared_ptr jsMonitor = iter->first; + if (value->StrictEquals(jsMonitor->Get())) { + HILOG_ERROR("monitor existed"); + monitor = iter->second; + return monitor ? engine.CreateNull() : nullptr; + } + } + + NativeObject *object = ConvertNativeValueTo(value); + if (object == nullptr) { + HILOG_ERROR("Failed to get object"); + return nullptr; + } + + auto abilityNameValue = object->GetProperty("abilityName"); + if (abilityNameValue == nullptr) { + return nullptr; + } + std::string abilityName; + if (!ConvertFromJsValue(engine, abilityNameValue, abilityName)) { + return nullptr; + } + std::shared_ptr abilityMonitor = std::make_shared(abilityName); + abilityMonitor->SetJsAbilityMonitorEnv(&engine); + abilityMonitor->SetJsAbilityMonitor(value); + + monitor = std::make_shared(abilityName, abilityMonitor.get()); + if (!monitor) { + HILOG_INFO("Failed to create monitor"); + return nullptr; + } + + std::shared_ptr refence = nullptr; + refence.reset(engine.CreateReference(value, 1)); + monitorRecord[refence] = monitor; + + return engine.CreateNull(); +} + +NativeValue *JSAbilityDelegator::ParseJSAbilityPara( + NativeEngine &engine, NativeValue *value, sptr &remoteObject) +{ + HILOG_INFO("ParseJSAbilityPara is called"); + + for (auto iter = ablityRecord.begin(); iter != ablityRecord.end(); ++iter) { + if (value->StrictEquals(iter->first->Get())) { + remoteObject = iter->second; + return remoteObject ? engine.CreateNull() : nullptr; + } + } + + HILOG_ERROR("Ablity doesn't exist"); + remoteObject = nullptr; + + return nullptr; +} + +NativeValue *JSAbilityDelegator::ParseJSExecuteShellCommandPara( + NativeEngine &engine, NativeCallbackInfo &info, std::string &cmd, int64_t &timeoutSecs, bool &hasTimeoutPara) +{ + HILOG_INFO("ParseJSExecuteShellCommandPara is called"); + + if (!ConvertFromJsValue(engine, info.argv[INDEX_ZERO], cmd)) { + HILOG_ERROR("Parse para argv[0] failed"); + return nullptr; + } + + if ((info.argc >= ARGC_TWO) && ((info.argv[INDEX_ONE])->TypeOf() == NativeValueType::NATIVE_NUMBER)) { + if (!ConvertFromJsValue(engine, info.argv[INDEX_ONE], timeoutSecs)) { + HILOG_ERROR("Parse para argv[1] failed"); + return nullptr; + } + hasTimeoutPara = true; + } else { + hasTimeoutPara = false; + } + + return engine.CreateNull(); +} + +NativeValue *JSAbilityDelegator::CreateJsAbilityObject(NativeEngine &engine, const sptr &remoteObject) +{ + HILOG_INFO("CreateJsAbilityObject is called"); + + if (!remoteObject) { + return engine.CreateUndefined(); + } + + NativeValue *objValue = engine.CreateObject(); + NativeObject *object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("Failed to get object"); + return nullptr; + } + + std::shared_ptr refence = nullptr; + refence.reset(engine.CreateReference(objValue, 1)); + ablityRecord[refence] = remoteObject; + + return objValue; +} +} // namespace AbilityDelegatorJs +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.h b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.h new file mode 100644 index 0000000000000000000000000000000000000000..4ad09f07960689513c5c8ed9464b0bad6e0e21fe --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_DELEGATOR_JS_ABILITY_DELEGATOR_H +#define OHOS_ABILITY_DELEGATOR_JS_ABILITY_DELEGATOR_H + +#include +#include "ability_monitor.h" +#include "js_ability_monitor.h" + +namespace OHOS { +namespace AbilityDelegatorJs { +class JSAbilityDelegator { +public: + JSAbilityDelegator() = default; + ~JSAbilityDelegator() = default; + + static void Finalizer(NativeEngine *engine, void *data, void *hint); + + static NativeValue *AddAbilityMonitor(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *RemoveAbilityMonitor(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *WaitAbilityMonitor(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *Print(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *ExecuteShellCommand(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *GetAppContext(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *GetAbilityState(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *GetCurrentTopAbility(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *DoAbilityForeground(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *DoAbilityBackground(NativeEngine *engine, NativeCallbackInfo *info); + +private: + NativeValue *OnAddAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnRemoveAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnWaitAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnPrint(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnExecuteShellCommand(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnGetAppContext(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnGetAbilityState(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnGetCurrentTopAbility(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnDoAbilityForeground(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnDoAbilityBackground(NativeEngine &engine, NativeCallbackInfo &info); + +private: + NativeValue *CreateJsAbilityObject(NativeEngine &engine, const sptr &remoteObject); + NativeValue *ParseJSMonitorPara(NativeEngine &engine, NativeValue *value, std::shared_ptr &monitor); + NativeValue *ParseJSAbilityPara(NativeEngine &engine, NativeValue *value, sptr &remoteObject); + NativeValue *ParseJSExecuteShellCommandPara( + NativeEngine& engine, NativeCallbackInfo &info, std::string &cmd, int64_t &timeoutSecs, bool &hasTimeoutPara); + void SetJsAbilityMonitor(std::string jstring); +}; +} // namespace AbilityDelegatorJs +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_ABILITY_DELEGATOR_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9dfcbef1e0a5cd2771df79bc003d99500b998652 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_ability_delegator_registry.h" + +#include "ability_delegator.h" +#include "ability_delegator_registry.h" +#include "hilog_wrapper.h" +#include "js_ability_delegator.h" +#include "js_ability_delegator_utils.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityDelegatorJs { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; +namespace { +constexpr int32_t ARGC_ONE = 1; + +class JsAbilityDelegatorRegistry { +public: + JsAbilityDelegatorRegistry() = default; + ~JsAbilityDelegatorRegistry() = default; + + static void Finalizer(NativeEngine *engine, void *data, void *hint) + { + HILOG_INFO("JsAbilityDelegatorRegistry::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static NativeValue *GetAbilityDelegator(NativeEngine *engine, NativeCallbackInfo *info) + { + JsAbilityDelegatorRegistry *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetAbilityDelegator(*engine, *info) : nullptr; + } + + static NativeValue *GetArguments(NativeEngine *engine, NativeCallbackInfo *info) + { + JsAbilityDelegatorRegistry *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetArguments(*engine, *info) : nullptr; + } + +private: + NativeValue *OnGetAbilityDelegator(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc > ARGC_ONE) { + HILOG_ERROR("Params not match"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [](NativeEngine &engine, AsyncTask &task, int32_t status) { + task.Resolve(engine, CreateJsAbilityDelegator(engine)); + }; + + NativeValue *lastParam = (info.argc == ARGC_ONE) ? info.argv[0] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue *OnGetArguments(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc > ARGC_ONE) { + HILOG_ERROR("Params not match"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [](NativeEngine &engine, AsyncTask &task, int32_t status) { + std::shared_ptr abilityDelegatorArgs = + AppExecFwk::AbilityDelegatorRegistry::GetArguments(); + task.Resolve(engine, CreateJsAbilityDelegatorArguments(engine, abilityDelegatorArgs)); + }; + + NativeValue *lastParam = (info.argc == ARGC_ONE) ? info.argv[0] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } +}; +} // namespace + +NativeValue *JsAbilityDelegatorRegistryInit(NativeEngine *engine, NativeValue *exportObj) +{ + HILOG_INFO("JsAbilityDelegatorManagerInit is called"); + if (engine == nullptr || exportObj == nullptr) { + HILOG_ERROR("Invalid input parameters"); + return nullptr; + } + + NativeObject *object = ConvertNativeValueTo(exportObj); + if (object == nullptr) { + HILOG_ERROR("Failed to get object"); + return nullptr; + } + + std::unique_ptr jsDelegatorManager = + std::make_unique(); + object->SetNativePointer(jsDelegatorManager.release(), JsAbilityDelegatorRegistry::Finalizer, nullptr); + + BindNativeFunction(*engine, *object, "getAbilityDelegator", JsAbilityDelegatorRegistry::GetAbilityDelegator); + BindNativeFunction(*engine, *object, "getArguments", JsAbilityDelegatorRegistry::GetArguments); + + return engine->CreateUndefined(); +} +} // namespace AbilityDelegatorJs +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_utils.h b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.h similarity index 58% rename from frameworks/kits/ability/native/src/ability_runtime/window/js_window_utils.h rename to interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.h index 1e265dbe4f56c74e401406eb16951a0a17344360..950b08d021cb049c010309bba7fa875a9a98d03a 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/window/js_window_utils.h +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.h @@ -13,24 +13,14 @@ * limitations under the License. */ -#ifndef OHOS_JS_WINDOW_UTILS_H -#define OHOS_JS_WINDOW_UTILS_H +#ifndef OHOS_ABILITY_DELEGATOR_ABILITY_DELEGATOR_REGISTRY_H +#define OHOS_ABILITY_DELEGATOR_ABILITY_DELEGATOR_REGISTRY_H + #include "native_engine/native_engine.h" -#include "native_engine/native_value.h" -#include "window.h" -#include "window_option.h" -#include "wm_common.h" namespace OHOS { -namespace AbilityRuntime { -namespace { - constexpr size_t ARGC_ONE = 1; - constexpr size_t ARGC_TWO = 2; - constexpr int32_t INDEX_ONE = 1; - constexpr int32_t INDEX_TWO = 2; -} - - NativeValue* CreateJsWindowPropertiesObject(NativeEngine& engine, sptr& window); -} -} -#endif \ No newline at end of file +namespace AbilityDelegatorJs { +NativeValue *JsAbilityDelegatorRegistryInit(NativeEngine *engine, NativeValue *exportObj); +} // namespace AbilityDelegatorJs +} // namespace OHOS +#endif // OHOS_ABILITY_DELEGATOR_ABILITY_DELEGATOR_REGISTRY_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9af710d8deb636d8add38c1924fd1c1b537b6834 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_ability_delegator_utils.h" + +#include +#include "ability_runtime/js_ability.h" +#include "hilog_wrapper.h" +#include "js_ability_monitor.h" +#include "napi/native_common.h" + +namespace OHOS { +namespace AbilityDelegatorJs { +using namespace OHOS::AbilityRuntime; +NativeValue *CreateJsAbilityDelegator(NativeEngine &engine) +{ + HILOG_INFO("CreateJsAbilityDelegator is called"); + + NativeValue *objValue = engine.CreateObject(); + NativeObject *object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("Failed to get object"); + return nullptr; + } + + std::unique_ptr jsAbilityDelegator = std::make_unique(); + object->SetNativePointer(jsAbilityDelegator.release(), JSAbilityDelegator::Finalizer, nullptr); + + BindNativeFunction(engine, *object, "addAbilityMonitor", JSAbilityDelegator::AddAbilityMonitor); + BindNativeFunction(engine, *object, "removeAbilityMonitor", JSAbilityDelegator::RemoveAbilityMonitor); + BindNativeFunction(engine, *object, "waitAbilityMonitor", JSAbilityDelegator::WaitAbilityMonitor); + BindNativeFunction(engine, *object, "getAppContext", JSAbilityDelegator::GetAppContext); + BindNativeFunction(engine, *object, "getAbilityState", JSAbilityDelegator::GetAbilityState); + BindNativeFunction(engine, *object, "getCurrentTopAbility", JSAbilityDelegator::GetCurrentTopAbility); + BindNativeFunction(engine, *object, "doAbilityForeground", JSAbilityDelegator::DoAbilityForeground); + BindNativeFunction(engine, *object, "doAbilityBackground", JSAbilityDelegator::DoAbilityBackground); + BindNativeFunction(engine, *object, "print", JSAbilityDelegator::Print); + BindNativeFunction(engine, *object, "executeShellCommand", JSAbilityDelegator::ExecuteShellCommand); + return objValue; +} + +napi_value WrapStringToJS(napi_env env, const std::string &value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &result)); + return result; +} + +void SetAbilityDelegatorArgumentsPara(napi_env env, const std::map ¶s) +{ + HILOG_INFO("SetAbilityDelegatorArgumentsPara is called"); + napi_value parameter = nullptr; + napi_value result = nullptr; + + auto iter = paras.begin(); + for (; iter != paras.end(); ++iter) { + NAPI_CALL_RETURN_VOID( + env, napi_set_named_property(env, parameter, iter->first.c_str(), WrapStringToJS(env, iter->second))); + } + napi_set_named_property(env, result, "parameters", parameter); + return; +} + +NativeValue *CreateJsAbilityDelegatorArguments( + NativeEngine &engine, const std::shared_ptr &abilityDelegatorArgs) +{ + HILOG_INFO("CreateJsAbilityDelegatorArguments is called"); + + NativeValue *objValue = engine.CreateObject(); + NativeObject *object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("Failed to get object"); + return nullptr; + } + + object->SetProperty("bundleName", CreateJsValue(engine, abilityDelegatorArgs->GetTestBundleName())); + SetAbilityDelegatorArgumentsPara(reinterpret_cast(&engine), abilityDelegatorArgs->GetTestParam()); + object->SetProperty("testCaseNames", CreateJsValue(engine, abilityDelegatorArgs->GetTestCaseName())); + object->SetProperty("testRunnerClassName", CreateJsValue(engine, abilityDelegatorArgs->GetTestRunnerClassName())); + + return objValue; +} + +NativeValue *CreateJsAbilityState(NativeEngine &engine, AbilityDelegator::AbilityState &lifeState) +{ + HILOG_INFO("CreateJsAbilityState is called"); + NativeValue *objValue = CreateJsValue(engine, static_cast(lifeState)); + if (!objValue) { + HILOG_ERROR("CreateJsAbilityState objValue is nullptr"); + return nullptr; + } + return objValue; +} + +NativeValue *CreateJsBool(NativeEngine &engine, bool &flag) +{ + HILOG_INFO("CreateJsBool is called"); + NativeValue *objValue = CreateJsValue(engine, static_cast(flag)); + if (!objValue) { + HILOG_ERROR("CreateJsBool objValue is nullptr"); + return nullptr; + } + return objValue; +} + +NativeValue *CreateJsShellCmdResult(NativeEngine &engine, std::unique_ptr &shellResult) +{ + HILOG_INFO("CreateJsShellCmdResult is called"); + + NativeValue *objValue = engine.CreateObject(); + NativeObject *object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("Failed to get object"); + return nullptr; + } + + object->SetProperty("stdResult", CreateJsValue(engine, shellResult->GetStdResult())); + object->SetProperty("exitCode", CreateJsValue(engine, shellResult->GetExitCode())); + + return objValue; +} +} // namespace AbilityDelegatorJs +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.h b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..86f2aaebf0832e031ada3b6fae03bc76c1f50bd7 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_DELEGATOR_JS_ABILITY_DELEGATOR_UTILS_H +#define OHOS_ABILITY_DELEGATOR_JS_ABILITY_DELEGATOR_UTILS_H + +#include "js_runtime_utils.h" +#include "ability_delegator.h" +#include "ability_delegator_args.h" +#include "js_ability_delegator.h" +#include "native_engine/native_engine.h" +#include "shell_cmd_result.h" + +namespace OHOS { +namespace AbilityDelegatorJs { +using namespace OHOS::AppExecFwk; +NativeValue *CreateJsAbilityDelegator(NativeEngine &engine); +NativeValue *CreateJsAbilityDelegatorArguments( + NativeEngine &engine, const std::shared_ptr &abilityDelegatorArgs); +NativeValue *CreateJsAbilityState(NativeEngine &engine, AbilityDelegator::AbilityState &lifeState); +NativeValue *CreateJsBool(NativeEngine &engine, bool &flag); +NativeValue *CreateJsShellCmdResult(NativeEngine &engine, std::unique_ptr &shellResult); +} // namespace AbilityDelegatorJs +} // namespace OHOS +#endif // OHOS_ABILITY_DELEGATOR_JS_ABILITY_DELEGATOR_UTILS_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_monitor.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_monitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac6c93b53a8ecfe2ff84cb51a7debc9e877aa614 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_monitor.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_ability_monitor.h" + +#include "js_ability_delegator_utils.h" +#include "napi/native_common.h" + +namespace OHOS { +namespace AbilityDelegatorJs { +using namespace OHOS::AbilityRuntime; +JSAbilityMonitor::JSAbilityMonitor(const std::string &abilityName) : abilityName_(abilityName) +{} + +void JSAbilityMonitor::onAbilityCreate() +{ + HILOG_INFO("onAbilityCreate is called"); + + if (jsAbilityMonitor_ == nullptr) { + HILOG_ERROR("jsAbilityMonitor_ nullptr"); + return; + } + + NativeValue* value = jsAbilityMonitor_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue* method = obj->GetProperty("onAbilityCreate"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onAbilityCreate from object"); + return; + } + + NativeValue* argv[] = {}; + engine_->CallFunction(value, method, argv, 0); + HILOG_INFO("onAbilityCreate is called end"); +} + +void JSAbilityMonitor::onAbilityForeground() +{ + HILOG_INFO("onAbilityForeground is called"); + + if (jsAbilityMonitor_ == nullptr) { + HILOG_ERROR("jsAbilityMonitor_ nullptr"); + return; + } + + NativeValue *value = jsAbilityMonitor_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue *method = obj->GetProperty("onAbilityForeground"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onAbilityForeground from object"); + return; + } + + NativeValue *argv[] = {}; + engine_->CallFunction(value, method, argv, 0); + HILOG_INFO("onAbilityForeground is called end"); +} + +void JSAbilityMonitor::onAbilityBackground() +{ + HILOG_INFO("onAbilityBackground is called"); + + if (jsAbilityMonitor_ == nullptr) { + HILOG_ERROR("jsAbilityMonitor_ nullptr"); + return; + } + + NativeValue *value = jsAbilityMonitor_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue *method = obj->GetProperty("onAbilityBackground"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onAbilityBackground from object"); + return; + } + + NativeValue *argv[] = {}; + engine_->CallFunction(value, method, argv, 0); + HILOG_INFO("onAbilityBackground is called end"); +} + +void JSAbilityMonitor::onAbilityDestroy() +{ + HILOG_INFO("onAbilityDestroy is called"); + + if (jsAbilityMonitor_ == nullptr) { + HILOG_ERROR("jsAbilityMonitor_ nullptr"); + return; + } + + NativeValue *value = jsAbilityMonitor_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue *method = obj->GetProperty("onAbilityDestroy"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onAbilityDestroy from object"); + return; + } + + NativeValue *argv[] = {}; + engine_->CallFunction(value, method, argv, 0); + HILOG_INFO("onAbilityDestroy is called end"); +} + +void JSAbilityMonitor::onWindowStageCreate() +{ + HILOG_INFO("onWindowStageCreate is called"); + + if (jsAbilityMonitor_ == nullptr) { + HILOG_ERROR("jsAbilityMonitor_ nullptr"); + return; + } + + NativeValue *value = jsAbilityMonitor_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue *method = obj->GetProperty("onWindowStageCreate"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onWindowStageCreate from object"); + return; + } + + NativeValue *argv[] = {}; + engine_->CallFunction(value, method, argv, 0); + HILOG_INFO("onWindowStageCreate is called end"); +} + +void JSAbilityMonitor::onWindowStageRestore() +{ + HILOG_INFO("onWindowStageRestore is called"); + + if (jsAbilityMonitor_ == nullptr) { + HILOG_ERROR("jsAbilityMonitor_ nullptr"); + return; + } + + NativeValue *value = jsAbilityMonitor_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue *method = obj->GetProperty("onWindowStageRestore"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onWindowStageRestore from object"); + return; + } + + NativeValue *argv[] = {}; + engine_->CallFunction(value, method, argv, 0); + HILOG_INFO("onWindowStageRestore is called end"); +} + +void JSAbilityMonitor::onWindowStageDestroy() +{ + HILOG_INFO("onWindowStageDestroy is called"); + + NativeValue *value = jsAbilityMonitor_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue *method = obj->GetProperty("onWindowStageDestroy"); + if (method == nullptr) { + HILOG_ERROR("Failed to get onWindowStageDestroy from object"); + return; + } + + NativeValue *argv[] = {}; + engine_->CallFunction(value, method, argv, 0); + HILOG_INFO("onWindowStageDestroy is called end"); +} + +void JSAbilityMonitor::SetJsAbilityMonitor(NativeValue *jsAbilityMonitor) +{ + HILOG_INFO("SetJsAbilityMonitor is called"); + + jsAbilityMonitor_ = std::unique_ptr(engine_->CreateReference(jsAbilityMonitor, 1)); +} +} // namespace AbilityDelegatorJs +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_monitor.h b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..46dadacdff38d17775bba93ce2a1a32e39a31e14 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_monitor.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_DELEGATOR_JS_ABILITY_MONITOR_H +#define OHOS_ABILITY_DELEGATOR_JS_ABILITY_MONITOR_H + +#include +#include "iability_monitor.h" +#include "hilog_wrapper.h" +#include "native_engine/native_reference.h" + +class NativeReference; +class NativeValue; + +namespace OHOS { +namespace AbilityDelegatorJs { +using namespace OHOS::AppExecFwk; +class JSAbilityMonitor { +public: + explicit JSAbilityMonitor(const std::string &abilityName); + ~JSAbilityMonitor() = default; + + void onAbilityCreate(); + void onAbilityForeground(); + void onAbilityBackground(); + void onAbilityDestroy(); + void onWindowStageCreate(); + void onWindowStageRestore(); + void onWindowStageDestroy(); + + void SetJsAbilityMonitor(NativeValue *jsAbilityMonitor); + void SetJsAbilityMonitorEnv(NativeEngine *engine) + { + engine_ = engine; + } + std::unique_ptr &GetJsAbilityMonitor() + { + return jsAbilityMonitor_; + } + +private: + std::string abilityName_; + NativeEngine* engine_ = nullptr; + std::unique_ptr jsAbilityMonitor_ = nullptr; +}; +} // namespace AbilityDelegatorJs +} // namespace OHOS +#endif // OHOS_ABILITY_DELEGATOR_JS_ABILITY_MONITOR_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/native_module.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/native_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f0b7baf74590fc1dcbda469cd4beeeb89fa93de --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/native_module.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" +#include "js_ability_delegator_registry.h" + +extern "C" __attribute__((constructor)) void NAPI_application_AbilityDelegatorRegistry_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AbilityDelegatorRegistry", + .fileName = "application/libabilitydelegator_napi.so/ability_delegator_registry.js", + .registerCallback = OHOS::AbilityDelegatorJs::JsAbilityDelegatorRegistryInit, + }; + + moduleManager->Register(&newModuleInfo); +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_stage/BUILD.gn b/interfaces/kits/napi/aafwk/app/ability_stage/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cbf90366e8b84018875bd133d6fc867072602149 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_stage/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_ability_stage_abc") { + src_js = rebase_path("ability_stage.js") + dst_file = rebase_path(target_out_dir + "/ability_stage.abc") + in_puts = [ "ability_stage.js" ] + out_puts = [ target_out_dir + "/ability_stage.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("ability_stage_js") { + input = "ability_stage.js" + output = target_out_dir + "/ability_stage.o" +} + +gen_js_obj("ability_stage_abc") { + input = get_label_info(":gen_ability_stage_abc", "target_out_dir") + + "/ability_stage.abc" + output = target_out_dir + "/ability_stage_abc.o" + dep = ":gen_ability_stage_abc" +} + +ohos_shared_library("abilitystage_napi") { + sources = [ "ability_stage_module.cpp" ] + + deps = [ + ":ability_stage_abc", + ":ability_stage_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/app/ability_stage/ability_stage.js b/interfaces/kits/napi/aafwk/app/ability_stage/ability_stage.js new file mode 100644 index 0000000000000000000000000000000000000000..dad03b8e38195c8887fd9ea33f4c0179d057f595 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_stage/ability_stage.js @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +class AbilityStage { + constructor() {} + onCreate() {} + onAcceptWant(want) { + console.log('onAcceptWant, want:' + want.abilityName); + } +} + +export default AbilityStage diff --git a/interfaces/kits/napi/aafwk/app/ability_stage/ability_stage_module.cpp b/interfaces/kits/napi/aafwk/app/ability_stage/ability_stage_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..798d608b3479ae38e3f9d4aaeda2091776c6aed5 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_stage/ability_stage_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_ability_stage_js_start[]; +extern const char _binary_ability_stage_js_end[]; +extern const char _binary_ability_stage_abc_start[]; +extern const char _binary_ability_stage_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_AbilityStage_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AbilityStage", + .fileName = "application/libabilitystage_napi.so/ability_stage.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStage_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_ability_stage_js_end - _binary_ability_stage_js_start; + } +} + +// ability_stage JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStage_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_ability_stage_abc_end - _binary_ability_stage_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/ability_stage_context/BUILD.gn b/interfaces/kits/napi/aafwk/app/ability_stage_context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..79df34c9191d8011abb73ec2d24a09ab0d66d2fa --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_stage_context/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_ability_stage_context_abc") { + src_js = rebase_path("ability_stage_context.js") + dst_file = rebase_path(target_out_dir + "/ability_stage_context.abc") + in_puts = [ "ability_stage_context.js" ] + out_puts = [ target_out_dir + "/ability_stage_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("ability_stage_context_js") { + input = "ability_stage_context.js" + output = target_out_dir + "/ability_stage_context.o" +} + +gen_js_obj("ability_stage_context_abc") { + input = get_label_info(":gen_ability_stage_context_abc", "target_out_dir") + + "/ability_stage_context.abc" + output = target_out_dir + "/ability_stage_context_abc.o" + dep = ":gen_ability_stage_context_abc" +} + +ohos_shared_library("abilitystagecontext_napi") { + sources = [ "ability_stage_context_module.cpp" ] + + deps = [ + ":ability_stage_context_abc", + ":ability_stage_context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context.js b/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context.js new file mode 100644 index 0000000000000000000000000000000000000000..247b206e50015d8bdd40a3070c4f26fede3c63d8 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context.js @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +var Context = requireNapi("application.Context") + +class AbilityStageContext extends Context { + constructor(obj) { + super(obj) + + this.currentHapModuleInfo = obj.currentHapModuleInfo + } +} + +export default AbilityStageContext diff --git a/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context_module.cpp b/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d68251793cec9a5c44c54c1250fb20b7617ab83c --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_ability_stage_context_js_start[]; +extern const char _binary_ability_stage_context_js_end[]; +extern const char _binary_ability_stage_context_abc_start[]; +extern const char _binary_ability_stage_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_AbilityStageContext_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AbilityStageContext", + .fileName = "application/libabilitystagecontext_napi.so/ability_stage_context.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStageContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_ability_stage_context_js_end - _binary_ability_stage_context_js_start; + } +} + +// ability_stage_context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStageContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_ability_stage_context_abc_end - _binary_ability_stage_context_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/appMgr/BUILD.gn b/interfaces/kits/napi/aafwk/app/appMgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..01f861509d9b9c99e241eadda55bd973110aaf00 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/appMgr/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("napi_app_mgr") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits", + "//third_party/node/src", + "//foundation/aafwk/standard/services/common/include", + "//utils/system/safwk/native/include", + "./", + ] + + sources = [ + "app_mgr.cpp", + "native_module.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:app_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/app/appMgr/app_mgr.cpp b/interfaces/kits/napi/aafwk/app/appMgr/app_mgr.cpp new file mode 100755 index 0000000000000000000000000000000000000000..fb8a698d087c69359863a340f1f5ad0b1df20391 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/appMgr/app_mgr.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr.h" + +#include +#include +#include +#include + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +static napi_value ParseBundleName(napi_env env, std::string &bundleName, napi_value args) +{ + napi_status status; + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, args, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + char buf[BUFFER_LENGTH_MAX] = {0}; + size_t len = 0; + napi_get_value_string_utf8(env, args, buf, BUFFER_LENGTH_MAX, &len); + HILOG_INFO("bundleName= [%{public}s].", buf); + bundleName = std::string {buf}; + // create result code + napi_value result; + status = napi_create_int32(env, 1, &result); + NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); + return result; +} + +static int32_t AbilityMgrKillProcess(const std::string &bundleName) +{ + OHOS::sptr systemAbilityManager = + OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + OHOS::sptr abilityObject = + systemAbilityManager->GetSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID); + OHOS::sptr abilityManager = + OHOS::iface_cast(abilityObject); + + return abilityManager->KillProcess(bundleName); +} + +napi_value NAPI_KillProcessesByBundleName(napi_env env, napi_callback_info info) +{ + HILOG_INFO("NAPI_KillProcessesByBundleName called..."); + size_t argc = 2; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + size_t argcNum = 2; + if (argc >= argcNum) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + } + + AsyncCallbackInfo *async_callback_info = + new AsyncCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr }; + std::string bundleName; + ParseBundleName(env, bundleName, argv[0]); + + if (argc >= argcNum) { + async_callback_info->bundleName = bundleName; + napi_create_reference(env, argv[1], 1, &async_callback_info->callback[0]); + + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_KillProcessesByBundleNameCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("killProcessesByBundleName called(CallBack Mode)..."); + AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data; + async_callback_info->result = AbilityMgrKillProcess(async_callback_info->bundleName); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("killProcessesByBundleName compeleted(CallBack Mode)..."); + AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data; + + napi_value result; + napi_value callback; + napi_value undefined; + + napi_create_int32(async_callback_info->env, async_callback_info->result, &result); + napi_get_undefined(env, &undefined); + + napi_get_reference_value(env, async_callback_info->callback[0], &callback); + napi_call_function(env, undefined, callback, 1, &result, nullptr); + + if (async_callback_info->callback[0] != nullptr) { + napi_delete_reference(env, async_callback_info->callback[0]); + } + + napi_delete_async_work(env, async_callback_info->asyncWork); + delete async_callback_info; + }, + (void *)async_callback_info, + &async_callback_info->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork)); + return NULL; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_KillProcessesByBundleNamePromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + async_callback_info->deferred = deferred; + async_callback_info->bundleName = bundleName; + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("killProcessesByBundleName called(Promise Mode)..."); + AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data; + async_callback_info->result = AbilityMgrKillProcess(async_callback_info->bundleName); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("killProcessesByBundleName compeleted(Promise Mode)..."); + AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data; + napi_value result; + napi_create_int32(async_callback_info->env, async_callback_info->result, &result); + napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result); + napi_delete_async_work(env, async_callback_info->asyncWork); + delete async_callback_info; + }, + (void *)async_callback_info, + &async_callback_info->asyncWork); + napi_queue_async_work(env, async_callback_info->asyncWork); + return promise; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/appMgr/app_mgr.h b/interfaces/kits/napi/aafwk/app/appMgr/app_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..6c8044fc987075ce58596944ff5a28590f00f252 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/appMgr/app_mgr.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 APP_MGR_H +#define APP_MGR_H + +#include + +#include "ability_manager_interface.h" +#include "hilog_wrapper.h" +#include "napi/native_api.h" +#include "napi/native_common.h" + +struct AsyncCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::string bundleName; + int32_t result; +}; + +#define BUFFER_LENGTH_MAX (128) + +napi_value NAPI_KillProcessesByBundleName(napi_env env, napi_callback_info); + +#endif // APP_MGR_H diff --git a/tools/zip/kits/napi/native_module.cpp b/interfaces/kits/napi/aafwk/app/appMgr/native_module.cpp similarity index 64% rename from tools/zip/kits/napi/native_module.cpp rename to interfaces/kits/napi/aafwk/app/appMgr/native_module.cpp index cb33e5b0f863a61173a6fa6505063049dedcdeee..f1e4c8ae9fb3efb64c5129d222e659fc7429427c 100644 --- a/tools/zip/kits/napi/native_module.cpp +++ b/interfaces/kits/napi/aafwk/app/appMgr/native_module.cpp @@ -12,53 +12,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include + +#include +#include +#include #include +#include "app_mgr.h" #include "napi/native_api.h" #include "napi/native_node_api.h" -#include "napi_zlib.h" -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { EXTERN_C_START /* - * The module initialization. + * function for module exports */ static napi_value Init(napi_env env, napi_value exports) { - FlushTypeInit(env, exports); - CompressLevelInit(env, exports); - CompressStrategyInit(env, exports); - MemLevelInit(env, exports); - ErrorCodeInit(env, exports); - ZlibInit(env, exports); + HILOG_INFO("native_module Init start..."); + /* + * Propertise define + */ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("killProcessesByBundleName", NAPI_KillProcessesByBundleName), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + HILOG_INFO("native_module Init end..."); return exports; } EXTERN_C_END /* - * The module definition. + * Module define */ static napi_module _module = { .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, - .nm_modname = "zlib", + .nm_modname = "napi_app_mgr", .nm_priv = ((void *)0), - .reserved = {0} -}; - + .reserved = {0}, + }; /* - * The module registration. + * Module register function */ extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&_module); -} -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/app_manager/BUILD.gn b/interfaces/kits/napi/aafwk/app/app_manager/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f3d19a47027a4941a60543068187de1f9a19757e --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/app_manager/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("appmanager_napi") { + include_dirs = [ + "//foundation/multimedia/image_standard/interfaces/innerkits/include", + "//foundation/appexecfwk/standard/kits/appkit/napi/app_manager", + ] + + sources = [ + "app_manager_module.cpp", + "js_app_manager.cpp", + "js_app_manager_utils.cpp", + ] + + configs = [ "//foundation/aafwk/standard/services/common:common_config" ] + + deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module/application" + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/app/app_manager/app_manager_module.cpp b/interfaces/kits/napi/aafwk/app/app_manager/app_manager_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a6c06e0d33ec65cae940cd166496866f6e44be0 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/app_manager/app_manager_module.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" +#include "js_app_manager.h" + +extern "C" __attribute__((constructor)) +void NAPI_application_AppManager_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AppManager", + .fileName = "application/appmanager_napi.so/app_manager.js", + .registerCallback = OHOS::AbilityRuntime::JsAppManagerInit, + }; + + moduleManager->Register(&newModuleInfo); +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e864b0619ab41f277fc84869a28be429438f894 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp @@ -0,0 +1,531 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_app_manager.h" + +#include + +#include "ability_manager_interface.h" +#include "app_mgr_interface.h" +#include "hilog_wrapper.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "js_app_manager_utils.h" +#include "event_runner.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr int32_t INDEX_ZERO = 0; +constexpr int32_t INDEX_ONE = 1; +constexpr int32_t INDEX_TWO = 2; +constexpr int32_t ERROR_CODE_ONE = 1; +constexpr size_t ARGC_ZERO = 0; +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; + +class JsAppManager final { +public: + JsAppManager(sptr appManager, + sptr abilityManager) : appManager_(appManager), + abilityManager_(abilityManager) {} + ~JsAppManager() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsAbilityContext::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static NativeValue* RegisterApplicationStateObserver(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnRegisterApplicationStateObserver(*engine, *info) : nullptr; + } + + static NativeValue* UnregisterApplicationStateObserver(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnUnregisterApplicationStateObserver(*engine, *info) : nullptr; + } + + static NativeValue* GetForegroundApplications(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetForegroundApplications(*engine, *info) : nullptr; + } + + static NativeValue* GetProcessRunningInfos(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnGetProcessRunningInfos(*engine, *info) : nullptr; + } + + static NativeValue* IsRunningInStabilityTest(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnIsRunningInStabilityTest(*engine, *info) : nullptr; + } + + static NativeValue* KillProcessWithAccount(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnKillProcessWithAccount(*engine, *info) : nullptr; + } + +private: + sptr appManager_ = nullptr; + sptr abilityManager_ = nullptr; + + NativeValue* OnRegisterApplicationStateObserver(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("OnRegisterApplicationStateObserver is called"); + // only support one or two params + if (info.argc != ARGC_ONE) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + // unwarp observer + sptr observer = new JSApplicationStateObserver(engine); + observer->SetJsObserverObject(info.argv[0]); + int64_t observerId = serialNumber_; + observerIds_.emplace(observerId, observer); + if (serialNumber_ < INT64_MAX) { + serialNumber_++; + } else { + serialNumber_ = 0; + } + HILOG_INFO("%{public}s create observer:%{public}p", __func__, observer.GetRefPtr()); + AsyncTask::CompleteCallback complete = + [appManager = appManager_, observer](NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("RegisterApplicationStateObserver callback begin"); + if (appManager == nullptr) { + HILOG_ERROR("appManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "appManager nullptr")); + return; + } + int32_t err = appManager->RegisterApplicationStateObserver(observer); + if (err == 0) { + HILOG_INFO("RegisterApplicationStateObserver success err 0"); + } else { + HILOG_ERROR("RegisterApplicationStateObserver failed error:%{public}d", err); + } + }; + + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, nullptr, nullptr, std::move(complete), &result)); + return engine.CreateNumber(observerId); + } + + NativeValue* OnUnregisterApplicationStateObserver(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("OnUnregisterApplicationStateObserver is called"); + // only support one or two params + if (info.argc != ARGC_ONE && info.argc != ARGC_TWO) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + // unwrap connectId + int64_t observerId = -1; + sptr observer = nullptr; + napi_get_value_int64(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ZERO]), &observerId); + HILOG_INFO("OnUnregisterApplicationStateObserver observer:%{public}d", (int32_t)observerId); + auto item = observerIds_.find(observerId); + if (item != observerIds_.end()) { + // match id + observer = item->second; + HILOG_INFO("%{public}s find observer:%{public}p exist", __func__, item->second.GetRefPtr()); + } else { + HILOG_INFO("%{public}s not find observer exist.", __func__); + } + + AsyncTask::CompleteCallback complete = + [appManager = appManager_, observer, observerId]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("OnUnregisterApplicationStateObserver begin"); + if (observer == nullptr || appManager == nullptr) { + HILOG_ERROR("observer or appManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "observer or appManager nullptr")); + return; + } + HILOG_INFO("observer->UnregisterApplicationStateObserver"); + int32_t err = appManager->UnregisterApplicationStateObserver(observer); + if (err == 0) { + HILOG_INFO("UnregisterApplicationStateObserver success err 0"); + task.Resolve(engine, engine.CreateUndefined()); + observerIds_.erase(observerId); + HILOG_INFO("UnregisterApplicationStateObserver erase size:%{public}zu", observerIds_.size()); + } else { + HILOG_ERROR("UnregisterApplicationStateObserver failed error:%{public}d", err); + task.Reject(engine, CreateJsError(engine, err, "UnregisterApplicationStateObserver failed")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[INDEX_ONE]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnGetForegroundApplications(NativeEngine& engine, NativeCallbackInfo& info) + { + // only support 0 or 1 params + if (info.argc != ARGC_ONE && info.argc != ARGC_ZERO) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + AsyncTask::CompleteCallback complete = + [appManager = appManager_]( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("OnGetForegroundApplications begin"); + if (appManager == nullptr) { + HILOG_ERROR("appManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "appManager nullptr")); + return; + } + std::vector list; + int32_t err = appManager->GetForegroundApplications(list); + if (err == 0) { + HILOG_INFO("OnGetForegroundApplications success err 0"); + task.Resolve(engine, CreateJsAppStateDataArray(engine, list)); + } else { + HILOG_ERROR("OnGetForegroundApplications failed error:%{public}d", err); + task.Reject(engine, CreateJsError(engine, err, "OnGetForegroundApplications failed")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_ZERO) ? nullptr : info.argv[INDEX_ZERO]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnGetProcessRunningInfos(NativeEngine &engine, NativeCallbackInfo &info) + { + AsyncTask::CompleteCallback complete = + [appManager = appManager_]( + NativeEngine &engine, AsyncTask &task, int32_t status) { + std::vector infos; + auto errcode = appManager->GetAllRunningProcesses(infos); + if (errcode == 0) { + task.Resolve(engine, CreateJsProcessRunningInfoArray(engine, infos)); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Get mission infos failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnIsRunningInStabilityTest(NativeEngine& engine, NativeCallbackInfo& info) + { + // only support 0 or 1 params + if (info.argc != ARGC_ONE && info.argc != ARGC_ZERO) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + AsyncTask::CompleteCallback complete = + [abilityManager = abilityManager_](NativeEngine& engine, AsyncTask& task, int32_t status) { + if (abilityManager == nullptr) { + HILOG_WARN("abilityManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "abilityManager nullptr")); + return; + } + HILOG_INFO("IsRunningInStabilityTest begin"); + bool ret = abilityManager->IsRunningInStabilityTest(); + HILOG_INFO("IsRunningInStabilityTest result:%{public}d", ret); + task.Resolve(engine, CreateJsValue(engine, ret)); + }; + + NativeValue* lastParam = (info.argc == ARGC_ZERO) ? nullptr : info.argv[INDEX_ZERO]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnKillProcessWithAccount(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + std::string bundleName; + if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) { + HILOG_ERROR("Parse bundleName failed"); + return engine.CreateUndefined(); + } + int accountId = -1; + if (!ConvertFromJsValue(engine, info.argv[1], accountId)) { + HILOG_ERROR("Parse userId failed"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = + [appManager = appManager_, bundleName, accountId](NativeEngine &engine, AsyncTask &task, int32_t status) { + auto errcode = appManager->GetAmsMgr()->KillProcessWithAccount(bundleName, accountId); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Kill processes failed.")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_TWO) ? nullptr : info.argv[INDEX_TWO]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } +}; +} // namespace + +OHOS::sptr GetAppManagerInstance() +{ + OHOS::sptr systemAbilityManager = + OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + OHOS::sptr appObject = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID); + return OHOS::iface_cast(appObject); +} + +OHOS::sptr GetAbilityManagerInstance() +{ + OHOS::sptr systemAbilityManager = + OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + OHOS::sptr abilityObject = + systemAbilityManager->GetSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID); + return OHOS::iface_cast(abilityObject); +} + +NativeValue* JsAppManagerInit(NativeEngine* engine, NativeValue* exportObj) +{ + HILOG_INFO("JsAppManagerInit is called"); + + if (engine == nullptr || exportObj == nullptr) { + HILOG_INFO("engine or exportObj null"); + return nullptr; + } + + NativeObject* object = ConvertNativeValueTo(exportObj); + if (object == nullptr) { + HILOG_INFO("object null"); + return nullptr; + } + + std::unique_ptr jsAppManager = + std::make_unique(GetAppManagerInstance(), GetAbilityManagerInstance()); + object->SetNativePointer(jsAppManager.release(), JsAppManager::Finalizer, nullptr); + + //make handler + handler_ = std::make_shared(AppExecFwk::EventRunner::GetMainEventRunner()); + + HILOG_INFO("JsAppManagerInit BindNativeFunction called"); + BindNativeFunction(*engine, *object, "registerApplicationStateObserver", + JsAppManager::RegisterApplicationStateObserver); + BindNativeFunction(*engine, *object, "unregisterApplicationStateObserver", + JsAppManager::UnregisterApplicationStateObserver); + BindNativeFunction(*engine, *object, "getForegroundApplications", + JsAppManager::GetForegroundApplications); + BindNativeFunction(*engine, *object, "getProcessRunningInfos", + JsAppManager::GetProcessRunningInfos); + BindNativeFunction(*engine, *object, "isRunningInStabilityTest", + JsAppManager::IsRunningInStabilityTest); + BindNativeFunction(*engine, *object, "killProcessWithAccount", + JsAppManager::KillProcessWithAccount); + HILOG_INFO("JsAppManagerInit end"); + return engine->CreateUndefined(); +} + +JSApplicationStateObserver::JSApplicationStateObserver(NativeEngine& engine) : engine_(engine) {} + +JSApplicationStateObserver::~JSApplicationStateObserver() = default; + +void JSApplicationStateObserver::OnForegroundApplicationChanged(const AppStateData &appStateData) +{ + HILOG_DEBUG("onForegroundApplicationChanged bundleName:%{public}s, uid:%{public}d, state:%{public}d", + appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, appStateData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnForegroundApplicationChanged(appStateData); + }; + handler_->PostTask(task, "OnForegroundApplicationChanged"); +} + +void JSApplicationStateObserver::HandleOnForegroundApplicationChanged(const AppStateData &appStateData) +{ + HILOG_DEBUG("HandleOnForegroundApplicationChanged bundleName:%{public}s, uid:%{public}d, state:%{public}d", + appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); + NativeValue* argv[] = {CreateJsAppStateData(engine_, appStateData)}; + CallJsFunction("onForegroundApplicationChanged", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnAbilityStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("OnAbilityStateChanged begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, abilityStateData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnAbilityStateChanged(abilityStateData); + }; + handler_->PostTask(task, "OnAbilityStateChanged"); +} + +void JSApplicationStateObserver::HandleOnAbilityStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("HandleOnAbilityStateChanged begin"); + NativeValue* argv[] = {CreateJsAbilityStateData(engine_, abilityStateData)}; + CallJsFunction("onAbilityStateChanged", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnExtensionStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("OnExtensionStateChanged begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, abilityStateData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnExtensionStateChanged(abilityStateData); + }; + handler_->PostTask(task, "OnExtensionStateChanged"); +} + +void JSApplicationStateObserver::HandleOnExtensionStateChanged(const AbilityStateData &abilityStateData) +{ + HILOG_INFO("HandleOnExtensionStateChanged begin"); + NativeValue* argv[] = {CreateJsAbilityStateData(engine_, abilityStateData)}; + CallJsFunction("onExtensionStateChanged", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnProcessCreated(const ProcessData &processData) +{ + HILOG_INFO("OnProcessCreated begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, processData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnProcessCreated(processData); + }; + handler_->PostTask(task, "OnProcessCreated"); +} + +void JSApplicationStateObserver::HandleOnProcessCreated(const ProcessData &processData) +{ + HILOG_INFO("HandleOnProcessCreated begin"); + NativeValue* argv[] = {CreateJsProcessData(engine_, processData)}; + CallJsFunction("onProcessCreated", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::OnProcessDied(const ProcessData &processData) +{ + HILOG_INFO("OnProcessDied begin"); + if (handler_ == nullptr) { + HILOG_INFO("handler_ nullptr"); + return; + } + wptr jsObserver = this; + auto task = [jsObserver, processData]() { + sptr jsObserverSptr = jsObserver.promote(); + if (!jsObserverSptr) { + HILOG_INFO("jsObserverSptr nullptr"); + return; + } + jsObserverSptr->HandleOnProcessDied(processData); + }; + handler_->PostTask(task, "OnProcessDied"); +} + +void JSApplicationStateObserver::HandleOnProcessDied(const ProcessData &processData) +{ + HILOG_INFO("HandleOnProcessDied begin"); + NativeValue* argv[] = {CreateJsProcessData(engine_, processData)}; + CallJsFunction("onProcessDied", argv, ARGC_ONE); +} + +void JSApplicationStateObserver::CallJsFunction(const char* methodName, NativeValue* const* argv, size_t argc) +{ + HILOG_INFO("CallJsFunction begin, method:%{public}s", methodName); + if (jsObserverObject_ == nullptr) { + HILOG_ERROR("jsObserverObject_ nullptr"); + return; + } + NativeValue* value = jsObserverObject_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get object"); + return; + } + + NativeValue* method = obj->GetProperty(methodName); + if (method == nullptr) { + HILOG_ERROR("Failed to get from object"); + return; + } + HILOG_INFO("CallJsFunction CallFunction success"); + engine_.CallFunction(value, method, argv, argc); + HILOG_INFO("CallJsFunction end"); +} + +void JSApplicationStateObserver::SetJsObserverObject(NativeValue* jsObserverObject) +{ + jsObserverObject_ = std::unique_ptr(engine_.CreateReference(jsObserverObject, 1)); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.h b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..15d542346fa3bebcd2d3169626998677d2d49209 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_state_observer_stub.h" +#include "native_engine/native_engine.h" +#include "event_handler.h" + +#ifndef OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_H +#define OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_H + +namespace OHOS { +namespace AbilityRuntime { +using OHOS::AppExecFwk::ApplicationStateObserverStub; +using OHOS::AppExecFwk::AppStateData; +using OHOS::AppExecFwk::AbilityStateData; +using OHOS::AppExecFwk::ProcessData; +NativeValue* JsAppManagerInit(NativeEngine* engine, NativeValue* exportObj); + +class JSApplicationStateObserver : public ApplicationStateObserverStub { +public: + explicit JSApplicationStateObserver(NativeEngine& engine); + ~JSApplicationStateObserver(); + void OnForegroundApplicationChanged(const AppStateData &appStateData) override; + void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; + void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; + void OnProcessCreated(const ProcessData &processData) override; + void OnProcessDied(const ProcessData &processData) override; + void HandleOnForegroundApplicationChanged(const AppStateData &appStateData); + void HandleOnAbilityStateChanged(const AbilityStateData &abilityStateData); + void HandleOnExtensionStateChanged(const AbilityStateData &abilityStateData); + void HandleOnProcessCreated(const ProcessData &processData); + void HandleOnProcessDied(const ProcessData &processData); + void SetJsObserverObject(NativeValue* jsObserverObject); + void CallJsFunction(const char* methodName, NativeValue* const* argv, size_t argc); + +private: + NativeEngine& engine_; + std::unique_ptr jsObserverObject_ = nullptr; +}; + +static std::map> observerIds_; +static int64_t serialNumber_ = 0; +static std::shared_ptr handler_ = nullptr; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.cpp b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4d2c3e858e4e478dd7dfe3cdf2b28429c1a7c1b --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "js_app_manager_utils.h" + +#include + +#include "hilog_wrapper.h" +#include "iapplication_state_observer.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsAppStateData(NativeEngine &engine, const AppStateData &appStateData) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* objValue = engine.CreateObject(); + if (objValue == nullptr) { + HILOG_ERROR("objValue nullptr."); + return nullptr; + } + HILOG_INFO("%{public}s ConvertNativeValueTo begin.", __func__); + NativeObject* object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("object nullptr."); + return nullptr; + } + HILOG_INFO("%{public}s SetProperty begin.", __func__); + object->SetProperty("bundleName", CreateJsValue(engine, appStateData.bundleName)); + object->SetProperty("uid", CreateJsValue(engine, appStateData.uid)); + object->SetProperty("state", CreateJsValue(engine, appStateData.state)); + HILOG_INFO("%{public}s end.", __func__); + return objValue; +} + +NativeValue* CreateJsAbilityStateData(NativeEngine &engine, const AbilityStateData &abilityStateData) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* objValue = engine.CreateObject(); + if (objValue == nullptr) { + HILOG_ERROR("objValue nullptr."); + return nullptr; + } + HILOG_INFO("%{public}s ConvertNativeValueTo begin.", __func__); + NativeObject* object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("object nullptr."); + return nullptr; + } + HILOG_INFO("%{public}s SetProperty begin.", __func__); + object->SetProperty("bundleName", CreateJsValue(engine, abilityStateData.bundleName)); + object->SetProperty("abilityName", CreateJsValue(engine, abilityStateData.abilityName)); + object->SetProperty("pid", CreateJsValue(engine, abilityStateData.pid)); + object->SetProperty("uid", CreateJsValue(engine, abilityStateData.uid)); + object->SetProperty("state", CreateJsValue(engine, abilityStateData.abilityState)); + HILOG_INFO("%{public}s end.", __func__); + return objValue; +} + +NativeValue* CreateJsProcessData(NativeEngine &engine, const ProcessData &processData) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* objValue = engine.CreateObject(); + if (objValue == nullptr) { + HILOG_ERROR("objValue nullptr."); + return nullptr; + } + HILOG_INFO("%{public}s ConvertNativeValueTo begin.", __func__); + NativeObject* object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("object nullptr."); + return nullptr; + } + HILOG_INFO("%{public}s SetProperty begin.", __func__); + object->SetProperty("bundleName", CreateJsValue(engine, processData.bundleName)); + object->SetProperty("pid", CreateJsValue(engine, processData.pid)); + object->SetProperty("uid", CreateJsValue(engine, processData.uid)); + HILOG_INFO("%{public}s end.", __func__); + return objValue; +} + +NativeValue* CreateJsAppStateDataArray(NativeEngine &engine, std::vector &appStateDatas) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* arrayValue = engine.CreateArray(appStateDatas.size()); + NativeArray* array = ConvertNativeValueTo(arrayValue); + uint32_t index = 0; + for (const auto &appStateData : appStateDatas) { + array->SetElement(index++, CreateJsAppStateData(engine, appStateData)); + } + HILOG_INFO("%{public}s end.", __func__); + return arrayValue; +} + +NativeValue* CreateJsProcessRunningInfoArray(NativeEngine &engine, const std::vector &infos) +{ + NativeValue* arrayValue = engine.CreateArray(infos.size()); + NativeArray* array = ConvertNativeValueTo(arrayValue); + uint32_t index = 0; + for (const auto &runningInfo : infos) { + array->SetElement(index++, CreateJsProcessRunningInfo(engine, runningInfo)); + } + return arrayValue; +} + +NativeValue* CreateJsProcessRunningInfo(NativeEngine &engine, const RunningProcessInfo &info) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + object->SetProperty("processName", CreateJsValue(engine, info.processName_)); + object->SetProperty("pid", CreateJsValue(engine, info.pid_)); + object->SetProperty("uid", CreateJsValue(engine, info.uid_)); + object->SetProperty("bundleNames", CreateNativeArray(engine, info.bundleNames)); + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.h b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..83966d6fe0c848f1585832c2fe2f53d2532b8977 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "application_state_observer_stub.h" +#include "native_engine/native_engine.h" +#include "running_process_info.h" + +#ifndef OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H +#define OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H + +namespace OHOS { +namespace AbilityRuntime { +using OHOS::AppExecFwk::AppStateData; +using OHOS::AppExecFwk::AbilityStateData; +using OHOS::AppExecFwk::ProcessData; +using OHOS::AppExecFwk::RunningProcessInfo; +NativeValue* CreateJsAppStateData(NativeEngine &engine, const AppStateData &appStateData); +NativeValue* CreateJsAbilityStateData(NativeEngine &engine, const AbilityStateData &abilityStateData); +NativeValue* CreateJsProcessData(NativeEngine &engine, const ProcessData &processData); +NativeValue* CreateJsAppStateDataArray(NativeEngine &engine, std::vector &appStateDatas); +NativeValue* CreateJsProcessRunningInfoArray(NativeEngine &engine, const std::vector &infos); +NativeValue* CreateJsProcessRunningInfo(NativeEngine &engine, const RunningProcessInfo &info); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_APPEXECFWK_RUNTIME_APP_MANAGER_UTILS_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/context/BUILD.gn b/interfaces/kits/napi/aafwk/app/context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8de532fcce2124de3f58d5de1996eb1f592a76c6 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/context/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_context_abc") { + src_js = rebase_path("context.js") + dst_file = rebase_path(target_out_dir + "/context.abc") + in_puts = [ "context.js" ] + out_puts = [ target_out_dir + "/context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("context_js") { + input = "context.js" + output = target_out_dir + "/context.o" +} + +gen_js_obj("context_abc") { + input = get_label_info(":gen_context_abc", "target_out_dir") + "/context.abc" + output = target_out_dir + "/context_abc.o" + dep = ":gen_context_abc" +} + +ohos_shared_library("context_napi") { + sources = [ "context_module.cpp" ] + + deps = [ + ":context_abc", + ":context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/app/context/context.js b/interfaces/kits/napi/aafwk/app/context/context.js new file mode 100755 index 0000000000000000000000000000000000000000..a345d2dd4aa750554eb888ea47b1a8c2aeef0820 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/context/context.js @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +class EventHub { + constructor() { + this.eventMap = {}; + } + + on(event, callback) { + if ((typeof(event) != 'string') || (typeof(callback) != 'function')) { + return; + } + if (!this.eventMap[event]) { + this.eventMap[event] = []; + } + if (this.eventMap[event].indexOf(callback) == -1) { + this.eventMap[event].push(callback); + } + } + + off(event, callback) { + if (typeof(event) != 'string') { + return; + } + if (this.eventMap[event]) { + if (callback) { + let index = this.eventMap[event].indexOf(callback); + if (index > -1) { + this.eventMap[event].splice(index, 1); + } + } else { + this.eventMap[event].length = 0; + } + } + } + + emit(event, ...args) { + if (typeof(event) != 'string') { + return; + } + if (this.eventMap[event]) { + this.eventMap[event].map((callback) => { + callback(...args); + }); + } + } +} + +class Context { + constructor(obj) { + this.__context_impl__ = obj + this.__context_impl__.eventHub = new EventHub() + } + + createBundleContext(bundleName) { + return this.__context_impl__.createBundleContext(bundleName) + } + + getApplicationContext() { + return this.__context_impl__.getApplicationContext() + } + + switchArea(mode) { + return this.__context_impl__.switchArea(mode) + } + + get resourceManager() { + return this.__context_impl__.resourceManager + } + + get applicationInfo() { + return this.__context_impl__.applicationInfo + } + + get cacheDir() { + return this.__context_impl__.cacheDir + } + + get tempDir() { + return this.__context_impl__.tempDir + } + + get filesDir() { + return this.__context_impl__.filesDir + } + + get distributedFilesDir() { + return this.__context_impl__.distributedFilesDir + } + + get databaseDir() { + return this.__context_impl__.databaseDir + } + + get storageDir() { + return this.__context_impl__.storageDir + } + + get bundleCodeDir() { + return this.__context_impl__.bundleCodeDir + } + + get eventHub() { + return this.__context_impl__.eventHub + } + + get stageMode() { + return true; + } +} + +export default Context diff --git a/interfaces/kits/napi/aafwk/app/context/context_module.cpp b/interfaces/kits/napi/aafwk/app/context/context_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0f7b55e01a4490219bbd30c9f679ced4395c2f7 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/context/context_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_context_js_start[]; +extern const char _binary_context_js_end[]; +extern const char _binary_context_abc_start[]; +extern const char _binary_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_Context_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.Context", + .fileName = "application/libcontext_napi.so/context.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Context_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_context_js_end - _binary_context_js_start; + } +} + +// context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Context_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_context_abc_end - _binary_context_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/app/test_runner/BUILD.gn b/interfaces/kits/napi/aafwk/app/test_runner/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a3600724b9530fb62b63fe1c6ff159cc58d806b3 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/test_runner/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_test_runner_abc") { + src_js = rebase_path("test_runner.js") + dst_file = rebase_path(target_out_dir + "/test_runner.abc") + in_puts = [ "test_runner.js" ] + out_puts = [ target_out_dir + "/test_runner.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("test_runner_js") { + input = "test_runner.js" + output = target_out_dir + "/test_runner.o" +} + +gen_js_obj("test_runner_abc") { + input = get_label_info(":gen_test_runner_abc", "target_out_dir") + + "/test_runner.abc" + output = target_out_dir + "/test_runner_abc.o" + dep = ":gen_test_runner_abc" +} + +ohos_shared_library("testrunner_napi") { + sources = [ "test_runner_module.cpp" ] + + deps = [ + ":test_runner_abc", + ":test_runner_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/app/test_runner/test_runner.js b/interfaces/kits/napi/aafwk/app/test_runner/test_runner.js new file mode 100755 index 0000000000000000000000000000000000000000..4bd372f476960f9045f0a076cd86f148c45aa484 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/test_runner/test_runner.js @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +class TestRunner { + constructor() {} + onPrepare​() {} + onRun​() {} +} + +export default TestRunner diff --git a/interfaces/kits/napi/aafwk/app/test_runner/test_runner_module.cpp b/interfaces/kits/napi/aafwk/app/test_runner/test_runner_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecdb6e0586efdd30b1f618e5eeea7a119a482532 --- /dev/null +++ b/interfaces/kits/napi/aafwk/app/test_runner/test_runner_module.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_test_runner_js_start[]; +extern const char _binary_test_runner_js_end[]; +extern const char _binary_test_runner_abc_start[]; +extern const char _binary_test_runner_abc_end[]; + +extern "C" __attribute__((constructor)) void NAPI_application_testRunner_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.testRunner", + .fileName = "application/libtestrunner_napi.so/test_runner.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) void NAPI_application_testRunner_GetJSCode( + const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_test_runner_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_test_runner_js_end - _binary_test_runner_js_start; + } +} + +// testRunner JS register +extern "C" __attribute__((visibility("default"))) void NAPI_application_testRunner_GetABCCode( + const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_test_runner_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_test_runner_abc_end - _binary_test_runner_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/callee/BUILD.gn b/interfaces/kits/napi/aafwk/callee/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..aaf427cd1889eb0dbb3055ec847b01c78b1560e7 --- /dev/null +++ b/interfaces/kits/napi/aafwk/callee/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_callee_abc") { + src_js = rebase_path("callee.js") + dst_file = rebase_path(target_out_dir + "/callee.abc") + in_puts = [ "callee.js" ] + out_puts = [ target_out_dir + "/callee.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("callee_js") { + input = "callee.js" + output = target_out_dir + "/callee.o" +} + +gen_js_obj("callee_abc") { + input = get_label_info(":gen_callee_abc", "target_out_dir") + "/callee.abc" + output = target_out_dir + "/callee_abc.o" + dep = ":gen_callee_abc" +} + +ohos_shared_library("callee_napi") { + sources = [ "callee_module.cpp" ] + + deps = [ + ":callee_abc", + ":callee_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/callee/callee.js b/interfaces/kits/napi/aafwk/callee/callee.js new file mode 100644 index 0000000000000000000000000000000000000000..ee669d8e08bd08ef39d3badbd5121a4265bd2094 --- /dev/null +++ b/interfaces/kits/napi/aafwk/callee/callee.js @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ +var rpc = requireNapi("rpc") + +const EVENT_CALL_NOTIFY = 1; +const REQUEST_SUCCESS = 0; +const REQUEST_FAILED = 1; + +class Callee extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + this.callList = new Map(); + console.log("Callee constructor is OK " + typeof des); + } else { + console.log("Callee constructor error, des is " + typeof des); + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + console.log("Callee onRemoteRequest code [" + typeof code + " " + code + "]"); + if (typeof code !== 'number' || typeof data !== 'object' || + typeof reply !== 'object' || typeof option !== 'object') { + console.log("Callee onRemoteRequest error, code is [" + + typeof code + "], data is [" + typeof data + "], reply is [" + + typeof reply + "], option is [" + typeof option + "]"); + return false; + } + + console.log("Callee onRemoteRequest code proc"); + if (code == EVENT_CALL_NOTIFY) { + if (this.callList == null) { + console.log("Callee onRemoteRequest error, this.callList is nullptr"); + return false; + } + + let method = data.readString(); + console.log("Callee onRemoteRequest method [" + method + "]"); + let func = this.callList.get(method); + if (typeof func !== 'function') { + console.log("Callee onRemoteRequest error, get func is " + typeof func); + return false; + } + + let result = func(data); + if (typeof result === 'object' && result != null) { + reply.writeInt(REQUEST_SUCCESS); + reply.writeString(typeof result); + reply.writeSequenceable(result); + console.log("Callee onRemoteRequest code proc Packed data"); + } else { + reply.writeInt(REQUEST_FAILED); + reply.writeString(typeof result); + console.log("Callee onRemoteRequest error, retval is " + REQUEST_FAILED + ", type is " + typeof result); + } + + } else { + console.log("Callee onRemoteRequest error, code is " + code); + return false; + } + + console.log("Callee onRemoteRequest code proc success"); + return true; + } + + on(method, callback) { + if (typeof method !== 'string' || method == "" || typeof callback !== 'function') { + console.log("Callee on error, method is [" + typeof method + "], typeof callback [" + typeof callback + "]"); + throw new Error("function input parameter error"); + return; + } + + if (this.callList == null) { + console.log("Callee on error, this.callList is nullptr"); + throw new Error("Function inner container error"); + return; + } + + if (this.callList.has(method)) { + console.log("Callee on error, this.callList not found " + method); + throw new Error("function is registered"); + return; + } + + this.callList.set(method, callback); + console.log("Callee on method [" + method + "]"); + } + + off(method) { + if (typeof method !== 'string' || method == "") { + console.log("Callee off error, method is [" + typeof method + "]"); + throw new Error("function input parameter error"); + return; + } + + if (this.callList == null) { + console.log("Callee off error, this.callList is null"); + throw new Error("Function inner container error"); + return; + } + + if (!this.callList.has(method)) { + console.log("Callee off error, this.callList not found " + method); + throw new Error("function not registered"); + return; + } + + this.callList.delete(method); + console.log("Callee off method [" + method + "]"); + } +} + +export default Callee \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/callee/callee_module.cpp b/interfaces/kits/napi/aafwk/callee/callee_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..326e7ddff9b5bd02c1cc30a0da41102d14dd85af --- /dev/null +++ b/interfaces/kits/napi/aafwk/callee/callee_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_callee_js_start[]; +extern const char _binary_callee_js_end[]; +extern const char _binary_callee_abc_start[]; +extern const char _binary_callee_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_Callee_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.Callee", + .fileName = "application/libcallee_napi.so/callee.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Callee_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_callee_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_callee_js_end - _binary_callee_js_start; + } +} + +// callee JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Callee_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_callee_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_callee_abc_end - _binary_callee_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/caller/BUILD.gn b/interfaces/kits/napi/aafwk/caller/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2ca15407c3f47b14aa3450f915c2a28811ffd88d --- /dev/null +++ b/interfaces/kits/napi/aafwk/caller/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_caller_abc") { + src_js = rebase_path("caller.js") + dst_file = rebase_path(target_out_dir + "/caller.abc") + in_puts = [ "caller.js" ] + out_puts = [ target_out_dir + "/caller.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("caller_js") { + input = "caller.js" + output = target_out_dir + "/caller.o" +} + +gen_js_obj("caller_abc") { + input = get_label_info(":gen_caller_abc", "target_out_dir") + "/caller.abc" + output = target_out_dir + "/caller_abc.o" + dep = ":gen_caller_abc" +} + +ohos_shared_library("caller_napi") { + sources = [ "caller_module.cpp" ] + + deps = [ + ":caller_abc", + ":caller_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/caller/caller.js b/interfaces/kits/napi/aafwk/caller/caller.js new file mode 100644 index 0000000000000000000000000000000000000000..1cf63fb8ceb2d8d7f2b4d3ec6d7de5b4e1ddb625 --- /dev/null +++ b/interfaces/kits/napi/aafwk/caller/caller.js @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ +var rpc = requireNapi("rpc") + +const EVENT_CALL_NOTIFY = 1; +const REQUEST_SUCCESS = 0; +const REQUEST_FAILED = 1; + +class Caller { + constructor(obj) { + console.log("Caller::constructor obj is " + typeof obj); + this.__call_obj__ = obj; + this.releaseCallback = null; + } + + async call(method, data) { + console.log("Caller call method [" + method + "]"); + if (typeof method !== 'string' || typeof data !== 'object') { + console.log("Caller call " + typeof method + " " + typeof data); + throw new Error("function input parameter error"); + return; + } + + if (this.__call_obj__.callee == null) { + console.log("Caller call this.callee is nullptr"); + throw new Error("Function inner object error"); + return; + } + + let msgData = rpc.MessageParcel.create(); + msgData.writeString(method); + let msgReply = rpc.MessageParcel.create(); + let option = rpc.MessageOption(); + msgData.writeSequenceable(data); + + let status = await this.__call_obj__.callee.sendRequest(EVENT_CALL_NOTIFY, msgData, msgReply, option); + if (!status) { + console.log("Caller call return data " + status); + throw new Error("Function execution exception"); + return ; + } + + let retval = msgReply.readInt(); + let str = msgReply.readString(); + if (retval === REQUEST_SUCCESS && str === 'object') { + console.log("Caller call return data " + str); + } else { + console.log("Caller call retval is [" + retval + "], str [" + str + "]"); + msgData.reclaim(); + msgReply.reclaim(); + throw new Error("Function execution result is abnormal"); + } + + console.log("Caller call msgData SendRequest end"); + return; + } + + async callWithResult(method, data) { + if (typeof method !== 'string' || typeof data !== 'object') { + console.log("Caller callWithResult " + typeof method + ", " + typeof data); + return undefined; + } + + if (this.__call_obj__.callee == null) { + console.log("Caller callWithResult this.callee is nullptr"); + return undefined; + } + + let msgData = rpc.MessageParcel.create(); + let msgReply = rpc.MessageParcel.create(); + let option = rpc.MessageOption(); + let reply = undefined; + msgData.writeString(method); + msgData.writeSequenceable(data); + let status = await this.__call_obj__.callee.sendRequest(EVENT_CALL_NOTIFY, msgData, msgReply, option); + if (!status) { + console.log("Caller callWithResult return data " + status); + return reply; + } + + let retval = msgReply.readInt(); + let str = msgReply.readString(); + if (retval === REQUEST_SUCCESS && str === 'object') { + reply = msgReply; + console.log("Caller callWithResult return data " + str); + } else { + console.log("Caller callWithResult retval is [" + retval + "], str [" + str + "]"); + msgData.reclaim(); + msgReply.reclaim(); + } + + console.log("Caller callWithResult sendMsg return"); + return reply; + } + + release() { + console.log("Caller release js called."); + this.__call_obj__.release(); + } + + onRelease(callback) { + console.log("Caller onRelease jscallback called."); + if (typeof callback !== 'function') { + console.log("Caller onRelease " + typeof callback); + throw new Error("function input parameter error"); + return; + } + + this.__call_obj__.onRelease(callback); + } +} + +export default Caller \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/caller/caller_module.cpp b/interfaces/kits/napi/aafwk/caller/caller_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..752e439edea2a8bcb6a077034151fc7e409185d0 --- /dev/null +++ b/interfaces/kits/napi/aafwk/caller/caller_module.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_caller_js_start[]; +extern const char _binary_caller_js_end[]; +extern const char _binary_caller_abc_start[]; +extern const char _binary_caller_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_Caller_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.Caller", + .fileName = "application/libcaller_napi.so/caller.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Caller_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_caller_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_caller_js_end - _binary_caller_js_start; + } +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Caller_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_caller_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_caller_abc_end - _binary_caller_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn index e7987859215f175375bddb540b222fab65784660..514a76bd990facda8c3ee9fcf817fa4c22e5ba9d 100644 --- a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn +++ b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn @@ -30,20 +30,21 @@ ohos_shared_library("datauriutils") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:ability_manager", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -51,5 +52,5 @@ ohos_shared_library("datauriutils") { relative_install_dir = "module/ability" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.h b/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.h index d7c85294e7f1b0ee654a5e693ebe8d23c71fd661..1147a41bbb7135a4b9b8b83a18777b21fe92a5f4 100644 --- a/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.h +++ b/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.h @@ -15,6 +15,7 @@ #ifndef OHOS_APPEXECFWK_NAPI_DATA_URI_UTILS_H #define OHOS_APPEXECFWK_NAPI_DATA_URI_UTILS_H +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" diff --git a/interfaces/kits/napi/aafwk/extensioncontext/BUILD.gn b/interfaces/kits/napi/aafwk/extensioncontext/BUILD.gn index 4f2aabb165b0b14c9381e9e41e2470b64eb01412..17e3820b0c110cfeb4cd92e339106558b0c6c387 100644 --- a/interfaces/kits/napi/aafwk/extensioncontext/BUILD.gn +++ b/interfaces/kits/napi/aafwk/extensioncontext/BUILD.gn @@ -46,5 +46,5 @@ ohos_shared_library("extensioncontext_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn index b3dc9c51e9ff8bf3e418a983bd41034e12c0351a..9c89997fc34495f54a619db5469ce74116e9cbaa 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn +++ b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn @@ -21,17 +21,18 @@ ohos_shared_library("featureability") { "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_dataability", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_rdb/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/include", ] sources = [ - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/js_utils.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/src/js_utils.cpp", - #"//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb/napi_rdb_predicates.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_dataability/napi_data_ability_predicates.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb/napi_result_set.cpp", + #"//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_rdb/napi_rdb_predicates.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/src/napi_data_ability_predicates.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/src/napi_result_set.cpp", "feature_ability.cpp", "feature_ability_constant.cpp", "napi_context.cpp", @@ -42,22 +43,23 @@ ohos_shared_library("featureability") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager:dataobs_manager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/libuv:uv_static", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:ability_manager", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", @@ -70,5 +72,5 @@ ohos_shared_library("featureability") { relative_install_dir = "module/ability" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.h b/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.h index a2eb59c82b3210a70ba0f431a8af684cd1768b11..32a8414ebef532572cc9e72d78e36a3cd9a06cb7 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.h +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.h @@ -15,6 +15,7 @@ #ifndef OHOS_APPEXECFWK_FEATURE_ABILITY_CONSTANT_H #define OHOS_APPEXECFWK_FEATURE_ABILITY_CONSTANT_H +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp index b32246015c5eecf1f5d498e728dad9690d5eaaa7..6f73e78312c4d3aa3e1fb25c3a3cfd211b9aa6e6 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp @@ -40,6 +40,15 @@ napi_value ContextConstructor(napi_env env, napi_callback_info info) { napi_value jsthis = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &jsthis, nullptr)); + + napi_value value = nullptr; + NAPI_CALL(env, napi_get_boolean(env, false, &value)); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("stageMode", value), + }; + NAPI_CALL(env, napi_define_properties(env, jsthis, sizeof(desc) / sizeof(desc[0]), desc)); + return jsthis; } diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h index 01fb8b30a23c3bc994a3ed223d682326f39a9008..f3f6ba6c202d7795c2b89a83d21cfc019bab0af6 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h @@ -17,6 +17,7 @@ #define OHOS_APPEXECFWK_NAPI_CONTEXT_H #include "../inner/napi_common/napi_common.h" #include "ability.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp index 686d0b826ba222cd13e89f2d8c8e4c2ae28af155..9de7d8016eb84eba9c6484bdc6394e2428d999df 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp @@ -87,6 +87,7 @@ napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) size_t argc = 1; napi_value argv[1] = {nullptr}; napi_value thisVar = nullptr; + auto& dataAbilityHelperStatus = GetDataAbilityHelperStatus(); NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); std::string strUri = NapiValueToStringUtf8(env, argv[0]); @@ -106,6 +107,7 @@ napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) DataAbilityHelper::Creator(ability->GetContext(), std::make_shared(strUri)); if (dataAbilityHelper == nullptr) { HILOG_INFO("%{public}s, dataAbilityHelper is nullptr", __func__); + dataAbilityHelperStatus = false; return nullptr; } HILOG_INFO("dataAbilityHelper = %{public}p", dataAbilityHelper.get()); @@ -139,6 +141,7 @@ napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) nullptr, nullptr); + dataAbilityHelperStatus = true; HILOG_INFO("%{public}s,called end", __func__); return thisVar; } @@ -208,7 +211,6 @@ napi_value InsertWrap(napi_env env, napi_callback_info info, DAHelperInsertCB *i HILOG_INFO("%{public}s,uri=%{public}s", __func__, insertCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; } insertCB->valueBucket.Clear(); @@ -347,8 +349,12 @@ void InsertExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_Insert, worker pool thread execute."); DAHelperInsertCB *insertCB = static_cast(data); if (insertCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(insertCB->uri); - insertCB->result = insertCB->dataAbilityHelper->Insert(uri, insertCB->valueBucket); + insertCB->execResult = INVALID_PARAMETER; + if (!insertCB->uri.empty()) { + OHOS::Uri uri(insertCB->uri); + insertCB->result = insertCB->dataAbilityHelper->Insert(uri, insertCB->valueBucket); + insertCB->execResult = NO_ERROR; + } } else { HILOG_ERROR("NAPI_Insert, dataAbilityHelper == nullptr."); } @@ -366,7 +372,7 @@ void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, insertCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, insertCB->execResult); napi_create_int32(env, insertCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -470,7 +476,6 @@ napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info) */ napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DAHelperNotifyChangeCB *notifyChangeCB) { - HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_TWO; const size_t argcPromise = ARGS_ONE; @@ -492,7 +497,6 @@ napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DAHelperNotif HILOG_INFO("%{public}s,uri=%{public}s", __func__, notifyChangeCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; } DataAbilityHelper *objectInfo = nullptr; @@ -570,8 +574,14 @@ void NotifyChangeExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_NotifyChange, worker pool thread execute."); DAHelperNotifyChangeCB *notifyChangeCB = static_cast(data); if (notifyChangeCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(notifyChangeCB->uri); - notifyChangeCB->dataAbilityHelper->NotifyChange(uri); + notifyChangeCB->execResult = INVALID_PARAMETER; + if (!notifyChangeCB->uri.empty()) { + OHOS::Uri uri(notifyChangeCB->uri); + notifyChangeCB->dataAbilityHelper->NotifyChange(uri); + notifyChangeCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("%{public}s, notifyChangeCB uri is empty.", __func__); + } } } @@ -593,7 +603,7 @@ void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data) return; } - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, notifyChangeCB->execResult); result[PARAM1] = WrapVoidToJS(env); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -675,17 +685,20 @@ napi_value RegisterWrap(napi_env env, napi_callback_info info, DAHelperOnOffCB * return nullptr; } + onCB->result = NO_ERROR; napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { std::string type = NapiValueToStringUtf8(env, args[PARAM0]); - if (type != "dataChange") { - HILOG_ERROR("%{public}s, Wrong type=%{public}s", __func__, type.c_str()); - return nullptr; + if (type == "dataChange") { + HILOG_INFO("%{public}s, Wrong type=%{public}s", __func__, type.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type is %{public}s.", __func__, type.c_str()); + onCB->result = INVALID_PARAMETER; } } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; + onCB->result = INVALID_PARAMETER; } NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); @@ -694,7 +707,7 @@ napi_value RegisterWrap(napi_env env, napi_callback_info info, DAHelperOnOffCB * HILOG_INFO("%{public}s,uri=%{public}s", __func__, onCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; + onCB->result = INVALID_PARAMETER; } DataAbilityHelper *objectInfo = nullptr; @@ -724,6 +737,7 @@ napi_value RegisterAsync( NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &onCB->cbBase.cbInfo.callback)); } else { HILOG_INFO("not valuetype isn't napi_function"); + onCB->result = INVALID_PARAMETER; } sptr observer(new (std::nothrow) NAPIDataAbilityObserver()); @@ -731,7 +745,9 @@ napi_value RegisterAsync( observer->SetCallbackRef(onCB->cbBase.cbInfo.callback); onCB->observer = observer; - registerInstances_.emplace_back(onCB); + if (onCB->result == NO_ERROR) { + registerInstances_.emplace_back(onCB); + } NAPI_CALL(env, napi_create_async_work( @@ -739,9 +755,7 @@ napi_value RegisterAsync( nullptr, resourceName, RegisterExecuteCB, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_Register, main event thread complete."); - }, + RegisterCompleteCB, (void *)onCB, &onCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, onCB->cbBase.asyncWork)); @@ -755,9 +769,31 @@ void RegisterExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_Register, worker pool thread execute."); DAHelperOnOffCB *onCB = static_cast(data); if (onCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(onCB->uri); - onCB->dataAbilityHelper->RegisterObserver(uri, onCB->observer); + if (onCB->result != INVALID_PARAMETER && !onCB->uri.empty() && onCB->cbBase.cbInfo.callback != nullptr) { + OHOS::Uri uri(onCB->uri); + onCB->dataAbilityHelper->RegisterObserver(uri, onCB->observer); + } else { + HILOG_ERROR("%{public}s, dataAbilityHelper uri is empty or callback is nullptr.", __func__); + } + } +} + +void RegisterCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Register, main event thread complete."); + DAHelperOnOffCB *onCB = static_cast(data); + if (onCB == nullptr) { + HILOG_ERROR("%{public}s, input params onCB is nullptr.", __func__); + return; } + if (onCB->result == NO_ERROR) { + return; + } + HILOG_INFO("NAPI_Register, input params onCB is invalid params, will be release"); + onCB->observer->ReleaseJSCallback(); + delete onCB; + onCB = nullptr; + HILOG_INFO("NAPI_Register, main event thread complete over an release invalid onCB."); } /** @@ -818,17 +854,20 @@ napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DAHelperOnOffCB return nullptr; } + offCB->result = NO_ERROR; napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { std::string type = NapiValueToStringUtf8(env, args[PARAM0]); - if (type != "dataChange") { - HILOG_ERROR("%{public}s, Wrong type=%{public}s", __func__, type.c_str()); - return nullptr; + if (type == "dataChange") { + HILOG_INFO("%{public}s, Wrong type=%{public}s", __func__, type.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type %{public}s.", __func__, type.c_str()); + offCB->result = INVALID_PARAMETER; } } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; + offCB->result = INVALID_PARAMETER; } offCB->uri = ""; @@ -840,11 +879,14 @@ napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DAHelperOnOffCB HILOG_INFO("%{public}s,uri=%{public}s", __func__, offCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; + offCB->result = INVALID_PARAMETER; } NAPI_CALL(env, napi_typeof(env, args[PARAM2], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[PARAM2], 1, &offCB->cbBase.cbInfo.callback)); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + offCB->result = INVALID_PARAMETER; } } else { // parse uri or callback @@ -856,7 +898,7 @@ napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DAHelperOnOffCB NAPI_CALL(env, napi_create_reference(env, args[PARAM1], 1, &offCB->cbBase.cbInfo.callback)); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; + offCB->result = INVALID_PARAMETER; } } @@ -880,7 +922,9 @@ napi_value UnRegisterAsync( napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - FindRegisterObs(env, offCB); + if (offCB->result == NO_ERROR) { + FindRegisterObs(env, offCB); + } NAPI_CALL(env, napi_create_async_work( @@ -1178,9 +1222,11 @@ static void OnChangeJSThreadWorker(uv_work_t *work, int status) void NAPIDataAbilityObserver::OnChange() { - HILOG_INFO("%{public}s, called.", __func__); + if (ref_ == nullptr) { + HILOG_ERROR("%{public}s, OnChange ref is nullptr.", __func__); + return; + } ChangeWorkPre(); - uv_loop_s *loop = nullptr; napi_get_uv_event_loop(env_, &loop); if (loop == nullptr) { @@ -1188,14 +1234,12 @@ void NAPIDataAbilityObserver::OnChange() ChangeWorkPreDone(); return; } - uv_work_t *work = new uv_work_t; if (work == nullptr) { HILOG_ERROR("%{public}s, work==nullptr.", __func__); ChangeWorkPreDone(); return; } - DAHelperOnOffCB *onCB = new (std::nothrow) DAHelperOnOffCB; if (onCB == nullptr) { HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); @@ -1210,7 +1254,6 @@ void NAPIDataAbilityObserver::OnChange() onCB->cbBase.cbInfo.callback = ref_; onCB->observer = this; work->data = (void *)onCB; - int rev = uv_queue_work( loop, work, @@ -1278,7 +1321,6 @@ napi_value GetTypeWrap(napi_env env, napi_callback_info info, DAHelperGetTypeCB HILOG_INFO("%{public}s,uri=%{public}s", __func__, gettypeCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; } DataAbilityHelper *objectInfo = nullptr; @@ -1358,8 +1400,14 @@ void GetTypeExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_GetType, worker pool thread execute."); DAHelperGetTypeCB *gettypeCB = static_cast(data); if (gettypeCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(gettypeCB->uri); - gettypeCB->result = gettypeCB->dataAbilityHelper->GetType(uri); + gettypeCB->execResult = INVALID_PARAMETER; + if (!gettypeCB->uri.empty()) { + OHOS::Uri uri(gettypeCB->uri); + gettypeCB->result = gettypeCB->dataAbilityHelper->GetType(uri); + gettypeCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_GetType, dataAbilityHelper uri is empty."); + } } else { HILOG_ERROR("NAPI_GetType, dataAbilityHelper == nullptr."); } @@ -1377,7 +1425,7 @@ void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, gettypeCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, gettypeCB->execResult); napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -1536,10 +1584,18 @@ void GetFileTypesExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute."); DAHelperGetFileTypesCB *getfiletypesCB = static_cast(data); if (getfiletypesCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(getfiletypesCB->uri); - HILOG_INFO("NAPI_GetFileTypes, uri:%{public}s", uri.ToString().c_str()); - HILOG_INFO("NAPI_GetFileTypes, mimeTypeFilter:%{public}s", getfiletypesCB->mimeTypeFilter.c_str()); - getfiletypesCB->result = getfiletypesCB->dataAbilityHelper->GetFileTypes(uri, getfiletypesCB->mimeTypeFilter); + getfiletypesCB->execResult = INVALID_PARAMETER; + if (!getfiletypesCB->uri.empty()) { + OHOS::Uri uri(getfiletypesCB->uri); + HILOG_INFO("NAPI_GetFileTypes, uri:%{public}s", uri.ToString().c_str()); + HILOG_INFO("NAPI_GetFileTypes, mimeTypeFilter:%{public}s", getfiletypesCB->mimeTypeFilter.c_str()); + getfiletypesCB->result = getfiletypesCB->dataAbilityHelper->GetFileTypes( + uri, + getfiletypesCB->mimeTypeFilter); + getfiletypesCB->execResult = NO_ERROR; + } else { + HILOG_INFO("NAPI_GetFileTypes, dataAbilityHelper uri is empty."); + } } else { HILOG_INFO("NAPI_GetFileTypes, dataAbilityHelper == nullptr."); } @@ -1558,7 +1614,7 @@ void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, getfiletypesCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, getfiletypesCB->execResult); result[PARAM1] = WrapGetFileTypesCB(env, *getfiletypesCB); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -1733,9 +1789,13 @@ void NormalizeUriExecuteCB(napi_env env, void *data) DAHelperNormalizeUriCB *normalizeuriCB = static_cast(data); Uri uriValue(normalizeuriCB->uri); if (normalizeuriCB->dataAbilityHelper != nullptr) { + normalizeuriCB->execResult = INVALID_PARAMETER; + if (!normalizeuriCB->uri.empty()) { OHOS::Uri uri(normalizeuriCB->uri); - uriValue = normalizeuriCB->dataAbilityHelper->NormalizeUri(uri); - normalizeuriCB->result = uriValue.ToString(); + uriValue = normalizeuriCB->dataAbilityHelper->NormalizeUri(uri); + normalizeuriCB->result = uriValue.ToString(); + normalizeuriCB->execResult = NO_ERROR; + } } else { HILOG_INFO("NAPI_NormalizeUri, dataAbilityHelper == nullptr"); } @@ -1753,7 +1813,7 @@ void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, normalizeuriCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, normalizeuriCB->execResult); NAPI_CALL_RETURN_VOID( env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); @@ -1908,9 +1968,15 @@ void DenormalizeUriExecuteCB(napi_env env, void *data) DAHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); Uri uriValue(denormalizeuriCB->uri); if (denormalizeuriCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(denormalizeuriCB->uri); - uriValue = denormalizeuriCB->dataAbilityHelper->DenormalizeUri(uri); - denormalizeuriCB->result = uriValue.ToString(); + denormalizeuriCB->execResult = INVALID_PARAMETER; + if (!denormalizeuriCB->uri.empty()) { + OHOS::Uri uri(denormalizeuriCB->uri); + uriValue = denormalizeuriCB->dataAbilityHelper->DenormalizeUri(uri); + denormalizeuriCB->result = uriValue.ToString(); + denormalizeuriCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_DenormalizeUri, dataAbilityHelper uri is empty"); + } } else { HILOG_ERROR("NAPI_DenormalizeUri, dataAbilityHelper == nullptr"); } @@ -1928,7 +1994,7 @@ void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, denormalizeuriCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, denormalizeuriCB->execResult); NAPI_CALL_RETURN_VOID( env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); @@ -2110,8 +2176,14 @@ void DeleteExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_Delete, worker pool thread execute."); DAHelperDeleteCB *deleteCB = static_cast(data); if (deleteCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(deleteCB->uri); - deleteCB->result = deleteCB->dataAbilityHelper->Delete(uri, deleteCB->predicates); + deleteCB->execResult = INVALID_PARAMETER; + if (!deleteCB->uri.empty()) { + OHOS::Uri uri(deleteCB->uri); + deleteCB->result = deleteCB->dataAbilityHelper->Delete(uri, deleteCB->predicates); + deleteCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_Delete, dataAbilityHelper uri is empty"); + } } else { HILOG_ERROR("NAPI_Delete, dataAbilityHelper == nullptr"); } @@ -2129,7 +2201,7 @@ void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, DeleteCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, DeleteCB->execResult); napi_create_int32(env, DeleteCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -2300,8 +2372,14 @@ void UpdateExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_Update, worker pool thread execute."); DAHelperUpdateCB *updateCB = static_cast(data); if (updateCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(updateCB->uri); - updateCB->result = updateCB->dataAbilityHelper->Update(uri, updateCB->valueBucket, updateCB->predicates); + updateCB->execResult = INVALID_PARAMETER; + if (!updateCB->uri.empty()) { + OHOS::Uri uri(updateCB->uri); + updateCB->result = updateCB->dataAbilityHelper->Update(uri, updateCB->valueBucket, updateCB->predicates); + updateCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_Update, dataAbilityHelper uri is empty"); + } } else { HILOG_ERROR("NAPI_Update, dataAbilityHelper == nullptr"); } @@ -2319,7 +2397,7 @@ void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, updateCB->execResult); napi_create_int32(env, updateCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -2493,8 +2571,14 @@ void OpenFileExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_OpenFile, worker pool thread execute."); DAHelperOpenFileCB *OpenFileCB = static_cast(data); if (OpenFileCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(OpenFileCB->uri); - OpenFileCB->result = OpenFileCB->dataAbilityHelper->OpenFile(uri, OpenFileCB->mode); + OpenFileCB->execResult = INVALID_PARAMETER; + if (!OpenFileCB->uri.empty()) { + OHOS::Uri uri(OpenFileCB->uri); + OpenFileCB->result = OpenFileCB->dataAbilityHelper->OpenFile(uri, OpenFileCB->mode); + OpenFileCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_OpenFile, dataAbilityHelper uri is empty"); + } } else { HILOG_ERROR("NAPI_OpenFile, dataAbilityHelper == nullptr"); } @@ -2512,7 +2596,7 @@ void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, OpenFileCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, OpenFileCB->execResult); napi_create_int32(env, OpenFileCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -2721,8 +2805,14 @@ void BatchInsertExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_BatchInsert, worker pool thread execute."); DAHelperBatchInsertCB *batchInsertCB = static_cast(data); if (batchInsertCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(batchInsertCB->uri); - batchInsertCB->result = batchInsertCB->dataAbilityHelper->BatchInsert(uri, batchInsertCB->values); + batchInsertCB->execResult = INVALID_PARAMETER; + if (!batchInsertCB->uri.empty()) { + OHOS::Uri uri(batchInsertCB->uri); + batchInsertCB->result = batchInsertCB->dataAbilityHelper->BatchInsert(uri, batchInsertCB->values); + batchInsertCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_BatchInsert, dataAbilityHelper uri is empyt"); + } } else { HILOG_ERROR("NAPI_BatchInsert, dataAbilityHelper == nullptr"); } @@ -2740,7 +2830,7 @@ void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, BatchInsertCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, BatchInsertCB->execResult); napi_create_int32(env, BatchInsertCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -2836,7 +2926,6 @@ napi_value QueryWrap(napi_env env, napi_callback_info info, DAHelperQueryCB *que arrayStringbool = NapiValueToArrayStringUtf8(env, args[PARAM1], result); if (arrayStringbool == false) { HILOG_ERROR("%{public}s, The return value of arraystringbool is false", __func__); - return nullptr; } queryCB->columns = result; for (size_t i = 0; i < queryCB->columns.size(); i++) { @@ -2934,12 +3023,18 @@ void QueryExecuteCB(napi_env env, void *data) HILOG_INFO("NAPI_Query, worker pool thread execute."); DAHelperQueryCB *queryCB = static_cast(data); if (queryCB->dataAbilityHelper != nullptr) { - OHOS::Uri uri(queryCB->uri); - auto resultset = queryCB->dataAbilityHelper->Query(uri, queryCB->columns, queryCB->predicates); - if (resultset != nullptr) { - queryCB->result = resultset; + queryCB->execResult = INVALID_PARAMETER; + if (!queryCB->uri.empty()) { + OHOS::Uri uri(queryCB->uri); + auto resultset = queryCB->dataAbilityHelper->Query(uri, queryCB->columns, queryCB->predicates); + if (resultset != nullptr) { + queryCB->result = resultset; + queryCB->execResult = NO_ERROR; + } else { + HILOG_INFO("NAPI_Query, resultset == nullptr."); + } } else { - HILOG_INFO("NAPI_Query, resultset == nullptr."); + HILOG_ERROR("NAPI_Query, dataAbilityHelper uri is empty"); } } else { HILOG_ERROR("NAPI_Query, dataAbilityHelper == nullptr"); @@ -2958,7 +3053,7 @@ void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(env, queryCB->execResult); result[PARAM1] = WrapResultSet(env, queryCB->result); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); @@ -3011,8 +3106,8 @@ napi_value NAPI_Release(napi_env env, napi_callback_info info) napi_value ReleaseWrap(napi_env env, napi_callback_info info, DAHelperReleaseCB *releaseCB) { HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; + size_t argcAsync = ARGS_ONE; + const size_t argcPromise = ARGS_ZERO; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = nullptr; @@ -3030,7 +3125,7 @@ napi_value ReleaseWrap(napi_env env, napi_callback_info info, DAHelperReleaseCB releaseCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { - ret = ReleaseAsync(env, args, ARGS_ONE, releaseCB); + ret = ReleaseAsync(env, args, PARAM0, releaseCB); } else { ret = ReleasePromise(env, releaseCB); } @@ -3222,7 +3317,6 @@ napi_value ExecuteBatchWrap(napi_env env, napi_callback_info info, DAHelperExecu HILOG_INFO("%{public}s,uri=%{public}s", __func__, executeBatchCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - return nullptr; } std::vector> operations; @@ -3382,6 +3476,5 @@ void GetDataAbilityResultForResult( } HILOG_INFO("%{public}s, NAPI_ExecuteBatch, getDataAbilityResultForResult end.", __func__); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h index b6d469cae42bf2889a21e6a63a162c04fb6bc795..f759e1126c3b278e4b45d0fa5373984aa018f195 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h @@ -233,6 +233,7 @@ napi_value RegisterAsync( * @param data Point to asynchronous processing of data. */ void RegisterExecuteCB(napi_env env, void *data); +void RegisterCompleteCB(napi_env env, napi_status status, void *data); /** * @brief DataAbilityHelper NAPI method : off. diff --git a/interfaces/kits/napi/aafwk/formManager/BUILD.gn b/interfaces/kits/napi/aafwk/formManager/BUILD.gn index b8e50a0567c5ff96f55e7fdff6dbd1dd2c1d888d..49a09746b3dd5fbe0285f4f13ca836cfb19e58e7 100644 --- a/interfaces/kits/napi/aafwk/formManager/BUILD.gn +++ b/interfaces/kits/napi/aafwk/formManager/BUILD.gn @@ -28,20 +28,21 @@ ohos_shared_library("formmanager") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/kits:appkit_native", ] external_deps = [ - "aafwk_standard:ability_manager", - "aafwk_standard:want", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "ability_runtime:want", "hiviewdfx_hilog_native:libhilog", ] relative_install_dir = "module/ability" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "form_runtime" } diff --git a/interfaces/kits/napi/aafwk/formManager/napi_form_manager.cpp b/interfaces/kits/napi/aafwk/formManager/napi_form_manager.cpp index edd1f274150355c4f9b7faed362b719eb1e85ff9..9fbbf7a5cc4ea38bee6a51600e6062d5a3eaefca 100644 --- a/interfaces/kits/napi/aafwk/formManager/napi_form_manager.cpp +++ b/interfaces/kits/napi/aafwk/formManager/napi_form_manager.cpp @@ -22,6 +22,7 @@ #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "runtime.h" using namespace OHOS; using namespace OHOS::AAFwk; @@ -38,6 +39,7 @@ namespace { constexpr int DECIMAL_VALUE = 10; constexpr int BASE_NUMBER = 9; constexpr int REF_COUNT = 1; + OHOS::AppExecFwk::Ability* g_ability = nullptr; } /** @@ -66,7 +68,7 @@ OHOS::AppExecFwk::Ability* GetGlobalAbility(napi_env env) // get global value napi_value global = nullptr; napi_get_global(env, &global); - + // get ability napi_value abilityObj = nullptr; napi_get_named_property(env, global, "ability", &abilityObj); @@ -75,7 +77,14 @@ OHOS::AppExecFwk::Ability* GetGlobalAbility(napi_env env) OHOS::AppExecFwk::Ability* ability = nullptr; napi_get_value_external(env, abilityObj, (void**)&ability); HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); - + if (ability == nullptr) { + if (g_ability == nullptr) { + std::unique_ptr runtime; + g_ability = OHOS::AppExecFwk::Ability::Create(runtime); + } + ability = g_ability; + HILOG_INFO("%{public}s, Use Local tmp Ability for Stage Module", __func__); + } return ability; } @@ -264,8 +273,8 @@ static void ParseFormInfoIntoNapi(napi_env env, const FormInfo &formInfo, napi_v // scheduledUpdateTime napi_value scheduledUpdateTime; - napi_create_string_utf8(env, formInfo.scheduledUpateTime.c_str(), NAPI_AUTO_LENGTH, &scheduledUpdateTime); - HILOG_DEBUG("%{public}s, scheduledUpdateTime=%{public}s.", __func__, formInfo.scheduledUpateTime.c_str()); + napi_create_string_utf8(env, formInfo.scheduledUpdateTime.c_str(), NAPI_AUTO_LENGTH, &scheduledUpdateTime); + HILOG_DEBUG("%{public}s, scheduledUpdateTime=%{public}s.", __func__, formInfo.scheduledUpdateTime.c_str()); napi_set_named_property(env, result, "scheduledUpdateTime", scheduledUpdateTime); // defaultDimension diff --git a/interfaces/kits/napi/aafwk/formManager/napi_form_manager.h b/interfaces/kits/napi/aafwk/formManager/napi_form_manager.h index e89c2aadbec568b44257cf8292526d6e36857a7a..8f301b44b56769005704c13eab9e9801f46d573c 100644 --- a/interfaces/kits/napi/aafwk/formManager/napi_form_manager.h +++ b/interfaces/kits/napi/aafwk/formManager/napi_form_manager.h @@ -21,6 +21,7 @@ #include "form_js_info.h" #include "form_provider_info.h" #include "hilog_wrapper.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" #include "nlohmann/json.hpp" diff --git a/interfaces/kits/napi/aafwk/form_binding_data/BUILD.gn b/interfaces/kits/napi/aafwk/form_binding_data/BUILD.gn index d8194aee92e81083b27315160d7f3823e21f6d84..8105005e1fbbdea1e85259a50c4e6a82c494126b 100644 --- a/interfaces/kits/napi/aafwk/form_binding_data/BUILD.gn +++ b/interfaces/kits/napi/aafwk/form_binding_data/BUILD.gn @@ -29,8 +29,9 @@ ohos_shared_library("formbindingdata_napi") { ] external_deps = [ - "aafwk_standard:runtime", - "appexecfwk_standard:appexecfwk_base", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "form_runtime:form_manager", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", @@ -39,5 +40,5 @@ ohos_shared_library("formbindingdata_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "form_runtime" } diff --git a/interfaces/kits/napi/aafwk/form_extension/BUILD.gn b/interfaces/kits/napi/aafwk/form_extension/BUILD.gn index e5302515989cd488e5cd9e0b2abe8b842fa3aa98..b1739d2a8064825d05f5fc85f6099a1b775d0d13 100644 --- a/interfaces/kits/napi/aafwk/form_extension/BUILD.gn +++ b/interfaces/kits/napi/aafwk/form_extension/BUILD.gn @@ -46,5 +46,5 @@ ohos_shared_library("formextension_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "form_runtime" } diff --git a/interfaces/kits/napi/aafwk/form_extension_context/BUILD.gn b/interfaces/kits/napi/aafwk/form_extension_context/BUILD.gn index 044c4625eff6bf3cee7ea6395a5a08e3edfe63e4..69f6e26b08b5c1058ae797aabed8702a3caa7906 100644 --- a/interfaces/kits/napi/aafwk/form_extension_context/BUILD.gn +++ b/interfaces/kits/napi/aafwk/form_extension_context/BUILD.gn @@ -46,5 +46,5 @@ ohos_shared_library("formextensioncontext_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "form_runtime" } diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn index e903bf10d4934febabf054775c5ce27bb9aafe4e..0cc0228b1c8c9e3376c3500a08a90663bd69a157 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn +++ b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn @@ -23,6 +23,7 @@ ohos_shared_library("napi_common") { sources = [ "napi_common_ability.cpp", + "napi_common_configuration.cpp", "napi_common_start_options.cpp", "napi_common_util.cpp", "napi_common_want.cpp", @@ -30,19 +31,21 @@ ohos_shared_library("napi_common") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/kits:appkit_native", "//third_party/libuv:uv_static", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:ability_manager", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:napi_base_context", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "ipc_js:rpc", @@ -54,5 +57,5 @@ ohos_shared_library("napi_common") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h index 490ed709a47af24ae34719806a9f1d78346e08af..5441466206d55018796e8ed033023cf83520c0a8 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h @@ -18,6 +18,7 @@ #include "ability.h" #include "abs_shared_result_set.h" #include "data_ability_predicates.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" #include "napi_common.h" @@ -219,6 +220,7 @@ struct DAHelperInsertCB { std::string uri; NativeRdb::ValuesBucket valueBucket; int result = 0; + int execResult; }; class NAPIAbilityConnection; @@ -243,6 +245,7 @@ struct DAHelperNotifyChangeCB { CBBase cbBase; DataAbilityHelper *dataAbilityHelper = nullptr; std::string uri; + int execResult; }; class NAPIDataAbilityObserver; @@ -277,6 +280,7 @@ struct DAHelperGetTypeCB { DataAbilityHelper *dataAbilityHelper = nullptr; std::string uri; std::string result = ""; + int execResult; }; struct DAHelperGetFileTypesCB { @@ -285,6 +289,7 @@ struct DAHelperGetFileTypesCB { std::string uri; std::string mimeTypeFilter; std::vector result; + int execResult; }; struct DAHelperNormalizeUriCB { @@ -292,12 +297,14 @@ struct DAHelperNormalizeUriCB { DataAbilityHelper *dataAbilityHelper = nullptr; std::string uri; std::string result = ""; + int execResult; }; struct DAHelperDenormalizeUriCB { CBBase cbBase; DataAbilityHelper *dataAbilityHelper = nullptr; std::string uri; std::string result = ""; + int execResult; }; struct DAHelperDeleteCB { @@ -306,6 +313,7 @@ struct DAHelperDeleteCB { std::string uri; NativeRdb::DataAbilityPredicates predicates; int result = 0; + int execResult; }; struct DAHelperQueryCB { @@ -315,6 +323,7 @@ struct DAHelperQueryCB { std::vector columns; NativeRdb::DataAbilityPredicates predicates; std::shared_ptr result; + int execResult; }; struct DAHelperUpdateCB { @@ -324,6 +333,7 @@ struct DAHelperUpdateCB { NativeRdb::ValuesBucket valueBucket; NativeRdb::DataAbilityPredicates predicates; int result = 0; + int execResult; }; struct DAHelperBatchInsertCB { CBBase cbBase; @@ -331,6 +341,7 @@ struct DAHelperBatchInsertCB { std::string uri; std::vector values; int result = 0; + int execResult; }; struct DAHelperOpenFileCB { CBBase cbBase; @@ -338,6 +349,7 @@ struct DAHelperOpenFileCB { std::string uri; std::string mode; int result = 0; + int execResult; }; struct DAHelperReleaseCB { diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common.h index c33bf6311b5df63722bf3be41149236e4d1d3172..6ee0e9b394e2a64e75490d51c6d650e7012f97df 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common.h @@ -16,6 +16,7 @@ #ifndef OHOS_APPEXECFWK_NAPI_COMMON_H #define OHOS_APPEXECFWK_NAPI_COMMON_H +#include "napi_common_configuration.h" #include "napi_common_data.h" #include "napi_common_error.h" #include "napi_common_util.h" diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp index 44db7fee4cfaabb58ac621830c41d97fca571196..13da15752555ca0e4e9a484864219297266a38c7 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp @@ -20,19 +20,20 @@ #include "hilog_wrapper.h" #include "napi_common_util.h" +#include "napi_base_context.h" #include "napi_remote_object.h" #include "securec.h" namespace OHOS { namespace AppExecFwk { -napi_value thread_local g_classContext; napi_value thread_local g_dataAbilityHelper; +bool thread_local g_dataAbilityHelperStatus = false; using NAPICreateJsRemoteObject = napi_value (*)(napi_env env, const sptr target); napi_value *GetGlobalClassContext(void) { - return &g_classContext; + return AbilityRuntime::GetFAModeContextClassObject(); } napi_value *GetGlobalDataAbilityHelper(void) @@ -40,6 +41,11 @@ napi_value *GetGlobalDataAbilityHelper(void) return &g_dataAbilityHelper; } +bool& GetDataAbilityHelperStatus() +{ + return g_dataAbilityHelperStatus; +} + bool CheckAbilityType(AbilityType typeInAbility, AbilityType typeWant) { HILOG_INFO("%{public}s called.", __func__); @@ -1575,7 +1581,7 @@ napi_value GetContextAsync( napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { - napi_new_instance(env, g_classContext, 0, nullptr, &result[PARAM1]); + napi_new_instance(env, *GetGlobalClassContext(), 0, nullptr, &result[PARAM1]); } else { result[PARAM1] = WrapUndefinedToJS(env); } @@ -1623,7 +1629,7 @@ napi_value GetContextPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); napi_value result = nullptr; if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { - napi_new_instance(env, g_classContext, 0, nullptr, &result); + napi_new_instance(env, *GetGlobalClassContext(), 0, nullptr, &result); napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); } else { result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); @@ -1666,7 +1672,7 @@ napi_value GetContextWrap(napi_env env, napi_callback_info info, AsyncCallbackIn } napi_value result = nullptr; - napi_new_instance(env, g_classContext, 0, nullptr, &result); + napi_new_instance(env, *GetGlobalClassContext(), 0, nullptr, &result); HILOG_INFO("%{public}s, end.", __func__); return result; } @@ -2309,27 +2315,34 @@ void StartAbilityExecuteCB(napi_env env, void *data) HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); return; } - asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + if (asyncCallbackInfo->errCode != NAPI_ERR_NO_ERROR) { + HILOG_ERROR("%{public}s errCode:%{public}d", __func__, asyncCallbackInfo->errCode); + return; + } if (asyncCallbackInfo->ability == nullptr) { asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; HILOG_ERROR("%{public}s ability == nullptr", __func__); return; } - if (!CheckAbilityType(asyncCallbackInfo)) { HILOG_ERROR("%{public}s wrong ability type", __func__); asyncCallbackInfo->errCode = NAPI_ERR_ABILITY_TYPE_INVALID; return; } + ErrCode ret = ERR_OK; if (asyncCallbackInfo->param.setting == nullptr) { HILOG_INFO("%{public}s param.setting == nullptr call StartAbility.", __func__); - asyncCallbackInfo->ability->StartAbility(asyncCallbackInfo->param.want); + ret = asyncCallbackInfo->ability->StartAbility(asyncCallbackInfo->param.want); } else { HILOG_INFO("%{public}s param.setting != nullptr call StartAbility.", __func__); - asyncCallbackInfo->ability->StartAbility(asyncCallbackInfo->param.want, *(asyncCallbackInfo->param.setting)); + ret = asyncCallbackInfo->ability->StartAbility(asyncCallbackInfo->param.want, + *(asyncCallbackInfo->param.setting)); } - HILOG_INFO("%{public}s end.", __func__); + if (ret != ERR_OK) { + asyncCallbackInfo->errCode = ret; + } + HILOG_INFO("%{public}s end. ret:%{public}d", __func__, ret); } void StartAbilityCallbackCompletedCB(napi_env env, napi_status status, void *data) @@ -2381,7 +2394,7 @@ void StartAbilityPromiseCompletedCB(napi_env env, napi_status status, void *data napi_value StartAbilityAsync( napi_env env, napi_value *args, const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) { - HILOG_INFO("%{public}s asyncCallback.", __func__); + HILOG_INFO("%{public}s async call.", __func__); if (args == nullptr || asyncCallbackInfo == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; @@ -2405,13 +2418,13 @@ napi_value StartAbilityAsync( &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - HILOG_INFO("%{public}s asyncCallback end.", __func__); + HILOG_INFO("%{public}s async end.", __func__); return WrapVoidToJS(env); } napi_value StartAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) { - HILOG_INFO("%{public}s, promise.", __func__); + HILOG_INFO("%{public}s promise call.", __func__); if (asyncCallbackInfo == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; @@ -2432,7 +2445,7 @@ napi_value StartAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInf (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - HILOG_INFO("%{public}s, end.", __func__); + HILOG_INFO("%{public}s promise end.", __func__); return promise; } @@ -2452,20 +2465,20 @@ napi_value StartAbilityWrap(napi_env env, napi_callback_info info, AsyncCallback const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; - + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - CallAbilityParam param; - if (UnwrapParamForWant(env, args[PARAM0], asyncCallbackInfo->abilityType, param) == false) { - HILOG_ERROR("%{public}s, call UnwrapParamForWant failed.", __func__); - return nullptr; + asyncCallbackInfo->errCode = NAPI_ERR_PARAM_INVALID; + } else { + CallAbilityParam param; + if (UnwrapParamForWant(env, args[PARAM0], asyncCallbackInfo->abilityType, param)) { + asyncCallbackInfo->param = param; + } else { + HILOG_ERROR("%{public}s, call UnwrapParamForWant failed.", __func__); + asyncCallbackInfo->errCode = NAPI_ERR_PARAM_INVALID; + } } - - asyncCallbackInfo->param = param; if (argcAsync > argcPromise) { ret = StartAbilityAsync(env, args, 1, asyncCallbackInfo); } else { @@ -3444,7 +3457,22 @@ napi_value AcquireDataAbilityHelperWrap(napi_env env, napi_callback_info info, D NAPI_CALL(env, napi_new_instance(env, *(GetGlobalDataAbilityHelper()), 1, &args[PARAM0], &result)); if (!IsTypeForNapiValue(env, result, napi_object)) { - HILOG_ERROR("%{public}s, IsTypeForNapiValue retval is false", __func__); + HILOG_ERROR("%{public}s, IsTypeForNapiValue isn`t object", __func__); + return nullptr; + } + + if (IsTypeForNapiValue(env, result, napi_null)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue is null", __func__); + return nullptr; + } + + if (IsTypeForNapiValue(env, result, napi_undefined)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue is undefined", __func__); + return nullptr; + } + + if (!GetDataAbilityHelperStatus()) { + HILOG_ERROR("%{public}s, GetDataAbilityHelperStatus is false", __func__); return nullptr; } diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h index e3e724c632197cf8d3ea3c2591029eafb4854427..963241e98ad7911f462aa19cb9ed7c881eb94dbb 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h @@ -26,6 +26,7 @@ const std::int32_t STR_MAX_SIZE = 128; napi_value *GetGlobalClassContext(void); napi_value *GetGlobalDataAbilityHelper(void); +bool& GetDataAbilityHelperStatus(); void SaveAppInfo(AppInfo_ &appInfo, const ApplicationInfo &appInfoOrg); napi_value WrapAppInfo(napi_env env, const AppInfo_ &appInfo); diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp new file mode 100644 index 0000000000000000000000000000000000000000..993e230ee528e7c1b59fc0e11ed5d2b621ab4b79 --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "napi_common_configuration.h" +#include "hilog_wrapper.h" +#include "napi_common_util.h" + +namespace OHOS { +namespace AppExecFwk { +EXTERN_C_START + +bool InnerWrapConfigurationString( + napi_env env, napi_value jsObject, const std::string &key, const std::string &value) +{ + if (!value.empty()) { + HILOG_INFO("%{public}s called. key=%{public}s, value=%{public}s", __func__, key.c_str(), value.c_str()); + napi_value jsValue = WrapStringToJS(env, value); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +napi_value WrapConfiguration(napi_env env, const AppExecFwk::Configuration &configuration) +{ + HILOG_INFO("%{public}s called, config size %{public}d", __func__, static_cast(configuration.GetItemSize())); + napi_value jsObject = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsObject)); + + std::vector keys = OHOS::AppExecFwk::ConfigurationInner::SystemConfigurationKeyStore; + for (auto const &key : keys) { + std::string value = configuration.GetItem(key); + if (value.empty()) { + HILOG_INFO("value is empty"); + continue; + } + + std::size_t pos = key.rfind(DOT_STRING); + if (pos != std::string::npos) { + InnerWrapConfigurationString(env, jsObject, key.substr(pos+1), value); + } else { + InnerWrapConfigurationString(env, jsObject, key, value); + } + } + return jsObject; +} + +bool UnwrapConfiguration(napi_env env, napi_value param, Configuration &config) +{ + HILOG_INFO("%{public}s called.", __func__); + + if (!IsTypeForNapiValue(env, param, napi_object)) { + HILOG_INFO("%{public}s called. Params is invalid.", __func__); + return false; + } + + std::string language {""}; + if (UnwrapStringByPropertyName(env, param, "language", language)) { + HILOG_DEBUG("The parsed language part %{public}s", language.c_str()); + if (!config.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, language)) { + HILOG_ERROR("language Parsing failed"); + return false; + } + } + + return true; +} +EXTERN_C_END +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.h new file mode 100644 index 0000000000000000000000000000000000000000..d86f71e995d34e6ea22045c84a83d2993ec8f1a4 --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_NAPI_COMMON_CONFIGURATION_H +#define OHOS_APPEXECFWK_NAPI_COMMON_CONFIGURATION_H + +#include "napi_common_data.h" +#include "configuration.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string DOT_STRING {"."}; +EXTERN_C_START + +napi_value WrapConfiguration(napi_env env, const AppExecFwk::Configuration &configuration); +bool UnwrapConfiguration(napi_env env, napi_value param, Configuration &config); + +EXTERN_C_END +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_NAPI_COMMON_CONFIGURATION_H diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h index 8ef50d7d2c88bec472bff0a082eb8a69c3364cbc..859c51388c134ebf7d8a1a6a457cb672b36682da 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h @@ -21,6 +21,7 @@ #include #include "ability.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" #include "pac_map.h" @@ -33,6 +34,7 @@ namespace AppExecFwk { #define ARGS_MAX_COUNT 10 #define ARGS_ASYNC_COUNT 1 +#define ARGS_ZERO 0 #define ARGS_ONE 1 #define ARGS_TWO 2 #define ARGS_THREE 3 diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_start_options.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_start_options.cpp index f2961d49680fcb3cf4fe404b6d9d44758c9750d5..1289113e26f29d9fb2fa90beab26a6ce357f8b5b 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_start_options.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_start_options.cpp @@ -37,6 +37,12 @@ bool UnwrapStartOptions(napi_env env, napi_value param, AAFwk::StartOptions &sta startOptions.SetWindowMode(windowMode); } + int32_t displayId = 0; + if (UnwrapInt32ByPropertyName(env, param, "displayId", displayId)) { + HILOG_INFO("get display id ok displayId %{public}d", displayId); + startOptions.SetDisplayID(displayId); + } + return true; } EXTERN_C_END diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h index 3844f23d4e3f935f8f96f4be2b7181c597fdda94..249ce4505fc3f8451cb8883bdc8f1028a584247f 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h @@ -16,6 +16,7 @@ #ifndef OHOS_APPEXECFWK_NAPI_COMMON_UTIL_H #define OHOS_APPEXECFWK_NAPI_COMMON_UTIL_H +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" #include "napi_common_data.h" diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp index 5829d942c022f8cd1afa881cfe350ee6132e8470..9dff21cbd37d74ba198927c30e7e09cfda5094cb 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp @@ -708,6 +708,10 @@ bool UnwrapWantParams(napi_env env, napi_value param, AAFwk::WantParams &wantPar NAPI_CALL_BASE(env, napi_get_element(env, jsProNameList, index, &jsProName), false); std::string strProName = UnwrapStringFromJS(env, jsProName); + /* skip reserved param */ + if (strProName == Want::PARAM_RESV_WINDOW_MODE) { + continue; + } HILOG_INFO("%{public}s called. Property name=%{public}s.", __func__, strProName.c_str()); NAPI_CALL_BASE(env, napi_get_named_property(env, param, strProName.c_str(), &jsProValue), false); NAPI_CALL_BASE(env, napi_typeof(env, jsProValue, &jsValueType), false); diff --git a/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn b/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn index 000028cc9b249751c6108a08f0b96885435e7d3b..511654f5cdc1c0a6e1a1941e0d7924b0bda54833 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn +++ b/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn @@ -25,13 +25,20 @@ ohos_shared_library("missionmanager_napi") { configs = [ "//foundation/aafwk/standard/services/common:common_config" ] - include_dirs = - [ "//foundation/multimedia/image_standard/interfaces/innerkits/include" ] + include_dirs = [ + "//foundation/multimedia/image_standard/interfaces/innerkits/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + "//base/global/resmgr_standard/interfaces/innerkits/include", + "//third_party/icu/icu4c/source/common", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/kits", + "//foundation/communication/ipc/ipc/native/src/napi/include", + ] deps = [ - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", @@ -41,20 +48,23 @@ ohos_shared_library("missionmanager_napi") { ] external_deps = [ - "aafwk_standard:runtime", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "ipc_js:rpc", + "multimedia_image_standard:image", ] relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } -ohos_shared_library("missionregistration_napi") { +ohos_shared_library("distributedmissionmanager") { include_dirs = [ "//third_party/libuv/include", "//third_party/node/src", @@ -71,8 +81,8 @@ ohos_shared_library("missionregistration_napi") { ] sources = [ + "distributed_mission_manager.cpp", "mission_continue_stub.cpp", - "napi_mission_registration.cpp", ] deps = [ @@ -89,6 +99,7 @@ ohos_shared_library("missionregistration_napi") { ] external_deps = [ + "ability_runtime:app_manager", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "ipc_js:rpc", @@ -97,5 +108,5 @@ ohos_shared_library("missionregistration_napi") { relative_install_dir = "module" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/mission_manager/napi_mission_registration.cpp b/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.cpp similarity index 95% rename from interfaces/kits/napi/aafwk/mission_manager/napi_mission_registration.cpp rename to interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.cpp index c4e1e70c117635e61a7600a3b3a2448d8b3da843..4b63e20877fb2eee5d3645839bd28c60004959bb 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/napi_mission_registration.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.cpp @@ -15,7 +15,7 @@ #include -#include "napi_mission_registration.h" +#include "distributed_mission_manager.h" #include "ability_manager_client.h" #include "hilog_wrapper.h" @@ -25,6 +25,8 @@ #include "napi_common_want.h" #include "napi_remote_object.h" +using namespace OHOS::AppExecFwk; + namespace OHOS { namespace AAFwk { using AbilityManagerClient = AAFwk::AbilityManagerClient; @@ -102,7 +104,16 @@ bool SetSyncRemoteMissionsContext(const napi_env &env, const napi_value &value, HILOG_ERROR("%{public}s, deviceId error type.", __func__); return false; } - napi_get_value_string_utf16(env, deviceIdValue, context->deviceId, VALUE_BUFFER_SIZE, &context->valueLen); + + char deviceId[VALUE_BUFFER_SIZE + 1] = {0}; + napi_get_value_string_utf8(env, deviceIdValue, deviceId, VALUE_BUFFER_SIZE + 1, &context->valueLen); + if (context->valueLen > VALUE_BUFFER_SIZE) { + HILOG_ERROR("%{public}s, deviceId length not correct", __func__); + return false; + } + context->deviceId = deviceId; + HILOG_INFO("%{public}s deviceId:%{public}s", __func__, context->deviceId.c_str()); + if (isStart) { if (!SetStartSyncMissionsContext (env, value, context)) { HILOG_ERROR("%{public}s, Wrong argument for start sync.", __func__); @@ -150,7 +161,7 @@ void StartSyncRemoteMissionsAsyncWork(napi_env env, const napi_value resourceNam [](napi_env env, void* data) { SyncRemoteMissionsContext* syncContext = (SyncRemoteMissionsContext*)data; syncContext->result = AbilityManagerClient::GetInstance()-> - StartSyncRemoteMissions(Str16ToStr8(syncContext->deviceId), + StartSyncRemoteMissions(syncContext->deviceId, syncContext->fixConflict, syncContext->tag); }, [](napi_env env, napi_status status, void* data) { @@ -192,7 +203,7 @@ void StartSyncRemoteMissionsAsyncWork(napi_env env, const napi_value resourceNam napi_value NAPI_StartSyncRemoteMissions(napi_env env, napi_callback_info info) { - HILOG_INFO("%{public}s, called.", __func__); + HILOG_INFO("%{public}s, test1 called.", __func__); auto syncContext = new SyncRemoteMissionsContext(); if (syncContext == nullptr) { HILOG_ERROR("%{public}s, syncContext is nullptr.", __func__); @@ -227,7 +238,7 @@ void StopSyncRemoteMissionsAsyncWork(napi_env env, napi_value resourceName, [](napi_env env, void* data) { SyncRemoteMissionsContext* syncContext = (SyncRemoteMissionsContext*)data; syncContext->result = AbilityManagerClient::GetInstance()-> - StopSyncRemoteMissions(Str16ToStr8(syncContext->deviceId)); + StopSyncRemoteMissions(syncContext->deviceId); }, [](napi_env env, napi_status status, void* data) { SyncRemoteMissionsContext* syncContext = (SyncRemoteMissionsContext*)data; @@ -344,7 +355,7 @@ void RegisterMissonExecuteCB(napi_env env, void *data) registerMissonCB->result = AbilityManagerClient::GetInstance()-> - RegisterMissionListener(Str16ToStr8(registerMissonCB->deviceId), + RegisterMissionListener(registerMissonCB->deviceId, registerMissonCB->missionRegistration); if (registerMissonCB->result == NO_ERROR) { HILOG_INFO("add registration."); @@ -517,16 +528,20 @@ napi_value RegisterMissonWrap(napi_env env, napi_callback_info info, RegisterMis return nullptr; } - char16_t deviceIdList[128] = {0}; - size_t valueLen = 0; napi_typeof(env, firstNApi, &valueType); if (valueType != napi_string) { HILOG_ERROR("%{public}s, deviceId error type.", __func__); return nullptr; } - napi_get_value_string_utf16(env, firstNApi, deviceIdList, VALUE_BUFFER_SIZE, &valueLen); - registerMissonCB->deviceId = deviceIdList; - HILOG_INFO("%{public}s deviceId:%{public}s", __func__, Str16ToStr8(registerMissonCB->deviceId).c_str()); + char deviceId[VALUE_BUFFER_SIZE + 1] = {0}; + size_t valueLen = 0; + napi_get_value_string_utf8(env, firstNApi, deviceId, VALUE_BUFFER_SIZE + 1, &valueLen); + if (valueLen > VALUE_BUFFER_SIZE) { + HILOG_ERROR("%{public}s, deviceId length not correct", __func__); + return nullptr; + } + registerMissonCB->deviceId = deviceId; + HILOG_INFO("%{public}s deviceId:%{public}s", __func__, registerMissonCB->deviceId.c_str()); if (argcAsync > 1 && !CreateCallbackReference(env, args[1], registerMissonCB)) { HILOG_ERROR("%{public}s, Wrong arguments.", __func__); @@ -606,9 +621,9 @@ void UvWorkNotifyMissionChanged(uv_work_t *work, int status) return; } napi_value result = nullptr; - HILOG_INFO("UvWorkNotifyMissionChanged, deviceId = %{public}s", Str16ToStr8(registerMissonCB->deviceId).c_str()); + HILOG_INFO("UvWorkNotifyMissionChanged, deviceId = %{public}s", registerMissonCB->deviceId.c_str()); result = - WrapString(registerMissonCB->cbBase.cbInfo.env, Str16ToStr8(registerMissonCB->deviceId).c_str(), "deviceId"); + WrapString(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->deviceId.c_str(), "deviceId"); napi_value callback = nullptr; napi_value undefined = nullptr; @@ -617,9 +632,6 @@ void UvWorkNotifyMissionChanged(uv_work_t *work, int status) napi_get_reference_value(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->cbBase.cbInfo.callback, &callback); napi_call_function(registerMissonCB->cbBase.cbInfo.env, undefined, callback, 1, &result, &callResult); - if (registerMissonCB->cbBase.cbInfo.callback != nullptr) { - napi_delete_reference(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->cbBase.cbInfo.callback); - } delete registerMissonCB; registerMissonCB = nullptr; delete work; @@ -651,7 +663,7 @@ void NAPIRemoteMissionListener::NotifyMissionsChanged(const std::string& deviceI } registerMissonCB->cbBase.cbInfo.env = env_; registerMissonCB->cbBase.cbInfo.callback = notifyMissionsChangedRef_; - registerMissonCB->deviceId = Str8ToStr16(deviceId); + registerMissonCB->deviceId = deviceId; work->data = (void *)registerMissonCB; int rev = uv_queue_work( @@ -678,9 +690,9 @@ void UvWorkNotifySnapshot(uv_work_t *work, int status) return; } napi_value result[2] = {0}; - HILOG_INFO("UvWorkNotifySnapshot, deviceId = %{public}s", Str16ToStr8(registerMissonCB->deviceId).c_str()); + HILOG_INFO("UvWorkNotifySnapshot, deviceId = %{public}s", registerMissonCB->deviceId.c_str()); result[0] = - WrapString(registerMissonCB->cbBase.cbInfo.env, Str16ToStr8(registerMissonCB->deviceId).c_str(), "deviceId"); + WrapString(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->deviceId.c_str(), "deviceId"); HILOG_INFO("UvWorkNotifySnapshot, missionId = %{public}d", registerMissonCB->missionId); result[1] = WrapInt32(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->missionId, "missionId"); @@ -692,9 +704,6 @@ void UvWorkNotifySnapshot(uv_work_t *work, int status) napi_get_reference_value(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->cbBase.cbInfo.callback, &callback); napi_call_function(registerMissonCB->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[0], &callResult); - if (registerMissonCB->cbBase.cbInfo.callback != nullptr) { - napi_delete_reference(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->cbBase.cbInfo.callback); - } delete registerMissonCB; registerMissonCB = nullptr; delete work; @@ -726,7 +735,7 @@ void NAPIRemoteMissionListener::NotifySnapshot(const std::string& deviceId, int3 } registerMissonCB->cbBase.cbInfo.env = env_; registerMissonCB->cbBase.cbInfo.callback = notifySnapshotRef_; - registerMissonCB->deviceId = Str8ToStr16(deviceId); + registerMissonCB->deviceId = deviceId; registerMissonCB->missionId = missionId; work->data = (void *)registerMissonCB; @@ -754,9 +763,9 @@ void UvWorkNotifyNetDisconnect(uv_work_t *work, int status) return; } napi_value result[2] = {0}; - HILOG_INFO("UvWorkNotifyNetDisconnect, deviceId = %{public}s", Str16ToStr8(registerMissonCB->deviceId).c_str()); + HILOG_INFO("UvWorkNotifyNetDisconnect, deviceId = %{public}s", registerMissonCB->deviceId.c_str()); result[0] = - WrapString(registerMissonCB->cbBase.cbInfo.env, Str16ToStr8(registerMissonCB->deviceId).c_str(), "deviceId"); + WrapString(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->deviceId.c_str(), "deviceId"); HILOG_INFO("UvWorkNotifyNetDisconnect, state = %{public}d", registerMissonCB->state); result[1] = WrapInt32(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->state, "state"); @@ -768,9 +777,6 @@ void UvWorkNotifyNetDisconnect(uv_work_t *work, int status) napi_get_reference_value(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->cbBase.cbInfo.callback, &callback); napi_call_function(registerMissonCB->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[0], &callResult); - if (registerMissonCB->cbBase.cbInfo.callback != nullptr) { - napi_delete_reference(registerMissonCB->cbBase.cbInfo.env, registerMissonCB->cbBase.cbInfo.callback); - } delete registerMissonCB; registerMissonCB = nullptr; delete work; @@ -803,7 +809,7 @@ void NAPIRemoteMissionListener::NotifyNetDisconnect(const std::string& deviceId, } registerMissonCB->cbBase.cbInfo.env = env_; registerMissonCB->cbBase.cbInfo.callback = notifyNetDisconnectRef_; - registerMissonCB->deviceId = Str8ToStr16(deviceId); + registerMissonCB->deviceId = deviceId; registerMissonCB->state = state; work->data = (void *)registerMissonCB; @@ -837,7 +843,7 @@ void UnRegisterMissonExecuteCB(napi_env env, void *data) registerMissonCB->result = AbilityManagerClient::GetInstance()-> - UnRegisterMissionListener(Str16ToStr8(registerMissonCB->deviceId), + UnRegisterMissionListener(registerMissonCB->deviceId, registerMissonCB->missionRegistration); if (registerMissonCB->result == NO_ERROR) { HILOG_INFO("remove registration."); @@ -929,16 +935,20 @@ bool GetUnRegisterMissonDeviceId(napi_env env, const napi_value& value, Register return false; } - char16_t deviceIdList[VALUE_BUFFER_SIZE] = {0}; size_t valueLen = 0; napi_typeof(env, firstNApi, &valueType); if (valueType != napi_string) { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); return false; } - napi_get_value_string_utf16(env, firstNApi, deviceIdList, VALUE_BUFFER_SIZE, &valueLen); - registerMissonCB->deviceId = deviceIdList; - HILOG_INFO("%{public}s deviceId:%{public}s", __func__, Str16ToStr8(registerMissonCB->deviceId).c_str()); + char deviceId[VALUE_BUFFER_SIZE + 1] = {0}; + napi_get_value_string_utf8(env, firstNApi, deviceId, VALUE_BUFFER_SIZE + 1, &valueLen); + if (valueLen > VALUE_BUFFER_SIZE) { + HILOG_ERROR("%{public}s, deviceId length not correct", __func__); + return false; + } + registerMissonCB->deviceId = deviceId; + HILOG_INFO("%{public}s deviceId:%{public}s", __func__, registerMissonCB->deviceId.c_str()); HILOG_INFO("%{public}s called end.", __func__); return true; } @@ -1395,7 +1405,7 @@ static napi_module missionModule = { .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = DistributedMissionManagerExport, - .nm_modname = "missionRegistration", + .nm_modname = "distributedMissionManager", .nm_priv = ((void*)0), .reserved = {0} }; diff --git a/interfaces/kits/napi/aafwk/mission_manager/napi_mission_registration.h b/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.h similarity index 96% rename from interfaces/kits/napi/aafwk/mission_manager/napi_mission_registration.h rename to interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.h index 4e7ad52734e5f86153f6e9e15a6169f958b66765..a5c89d66fca466b49aceacb523923596abcbb535 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/napi_mission_registration.h +++ b/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.h @@ -18,7 +18,6 @@ #include -#include "distributed_sched_interface.h" #include "mission_continue_interface.h" #include "mission_continue_stub.h" #include "napi/native_api.h" @@ -90,7 +89,7 @@ struct MissionRegistrationCB { struct RegisterMissonCB { CBBase cbBase; - std::u16string deviceId; + std::string deviceId; sptr missionRegistration; MissionRegistrationCB missionRegistrationCB; int result = 0; @@ -121,7 +120,7 @@ struct SyncRemoteMissionsContext { napi_env env; napi_async_work work; - char16_t deviceId[128] = {0}; + std::string deviceId; size_t valueLen = 0; bool fixConflict = false; int64_t tag = -1; @@ -136,7 +135,7 @@ bool SetSyncRemoteMissionsContext( bool ProcessSyncInput(napi_env env, napi_callback_info info, bool isStart, SyncRemoteMissionsContext* syncContext); mutex registrationLock_; -map> registration_; +map> registration_; enum ErrorCode { NO_ERROR = 0, diff --git a/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.cpp b/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.cpp index 5b20d9c5eb75c964da31eb6b1859bd04b6c3af1f..7fa45008eff1766f76b8e8f6826a9f1e1805ab8e 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.cpp @@ -16,6 +16,8 @@ #include "js_mission_info_utils.h" #include "hilog_wrapper.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" #include "ohos/aafwk/base/array_wrapper.h" #include "ohos/aafwk/base/bool_wrapper.h" #include "ohos/aafwk/base/byte_wrapper.h" @@ -37,6 +39,7 @@ NativeValue* CreateJsMissionInfo(NativeEngine &engine, const AAFwk::MissionInfo object->SetProperty("missionId", CreateJsValue(engine, missionInfo.id)); object->SetProperty("runningState", CreateJsValue(engine, missionInfo.runningState)); object->SetProperty("lockedState", CreateJsValue(engine, missionInfo.lockedState)); + object->SetProperty("continuable", CreateJsValue(engine, missionInfo.continuable)); object->SetProperty("timestamp", CreateJsValue(engine, missionInfo.time)); object->SetProperty("want", CreateJsWant(engine, missionInfo.want)); object->SetProperty("label", CreateJsValue(engine, missionInfo.label)); diff --git a/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h b/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h index 1b66f6744282f610bb9a674d0ed5889b0780a507..00c01039dd7e76e0d9fe8a797c2dad2883f97522 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h +++ b/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h @@ -16,6 +16,9 @@ #include "js_runtime_utils.h" #include "mission_info.h" #include "mission_snapshot.h" +#include "ability_running_info.h" +#include "extension_running_info.h" +#include "running_process_info.h" #include "native_engine/native_engine.h" #include "ohos/aafwk/content/want_params_wrapper.h" #include "want.h" diff --git a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp index b15d50eaf49b1d2ff3fab105470d120d6a2e90b7..37271ce39da8bda84b2aa18ea27e1ddb88c9a3f5 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp @@ -22,34 +22,32 @@ namespace OHOS { namespace AbilityRuntime { void JsMissionListener::OnMissionCreated(int32_t missionId) { - PostMissionCallback("onMissionCreated", missionId); + CallJsMethod("onMissionCreated", missionId); } void JsMissionListener::OnMissionDestroyed(int32_t missionId) { - PostMissionCallback("onMissionDestroyed", missionId); + CallJsMethod("onMissionDestroyed", missionId); } void JsMissionListener::OnMissionSnapshotChanged(int32_t missionId) { - PostMissionCallback("onMissionSnapshotChanged", missionId); + CallJsMethod("onMissionSnapshotChanged", missionId); } void JsMissionListener::OnMissionMovedToFront(int32_t missionId) { - PostMissionCallback("onMissionMovedToFront", missionId); + CallJsMethod("onMissionMovedToFront", missionId); } void JsMissionListener::AddJsListenerObject(int32_t listenerId, NativeValue* jsListenerObject) { - std::lock_guard lock(listenerMutex_); jsListenerObjectMap_.emplace( listenerId, std::shared_ptr(engine_->CreateReference(jsListenerObject, 1))); } void JsMissionListener::RemoveJsListenerObject(int32_t listenerId) { - std::lock_guard lock(listenerMutex_); jsListenerObjectMap_.erase(listenerId); } @@ -58,37 +56,29 @@ bool JsMissionListener::IsEmpty() return jsListenerObjectMap_.empty(); } -void JsMissionListener::HandleMissionCallback(const char* methodName, int32_t missionId) +void JsMissionListener::CallJsMethod(const std::string &methodName, int32_t missionId) { - NativeValue* argv[] = { CreateJsValue(*engine_, missionId) }; - CallJsMethod(methodName, argv, 1); -} - -void JsMissionListener::PostMissionCallback(const std::string &methodName, int32_t missionId) -{ - if (!mainHandler_) { - HILOG_ERROR("mainHandler_ is nullptr"); + HILOG_INFO("methodName = %{public}s", methodName.c_str()); + if (engine_ == nullptr) { + HILOG_ERROR("engine_ nullptr"); return; } - wptr wpListener = this; - auto task = [wpListener, methodName, missionId]() { - auto listener = wpListener.promote(); - if (listener) { - listener->HandleMissionCallback(methodName.c_str(), missionId); - } - }; - mainHandler_->PostTask(task); + // js callback should run in js thread + std::unique_ptr complete = std::make_unique + ([jsMissionListener = this, methodName, missionId](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (jsMissionListener) { + jsMissionListener->CallJsMethodInner(methodName, missionId); + } + }); + NativeReference* callback = nullptr; + std::unique_ptr execute = nullptr; + AsyncTask::Schedule( + *engine_, std::make_unique(callback, std::move(execute), std::move(complete))); } -void JsMissionListener::CallJsMethod(const char* methodName, NativeValue* const* argv, size_t argc) +void JsMissionListener::CallJsMethodInner(const std::string &methodName, int32_t missionId) { - HILOG_INFO("methodName = %{public}s", methodName); - if (engine_ == nullptr) { - HILOG_ERROR("engine_ nullptr"); - return; - } - std::lock_guard lock(listenerMutex_); for (auto &item : jsListenerObjectMap_) { NativeValue* value = (item.second)->Get(); NativeObject* obj = ConvertNativeValueTo(value); @@ -96,12 +86,13 @@ void JsMissionListener::CallJsMethod(const char* methodName, NativeValue* const* HILOG_ERROR("Failed to get object"); continue; } - NativeValue* method = obj->GetProperty(methodName); - if (method == nullptr) { - HILOG_ERROR("Failed to get onMissionCreated from object"); + NativeValue* method = obj->GetProperty(methodName.c_str()); + if (method == nullptr || method->TypeOf() == NATIVE_UNDEFINED) { + HILOG_ERROR("Failed to get %{public}s from object", methodName.c_str()); continue; } - engine_->CallFunction(value, method, argv, argc); + NativeValue* argv[] = { CreateJsValue(*engine_, missionId) }; + engine_->CallFunction(value, method, argv, ArraySize(argv)); } } } // namespace AbilityRuntime diff --git a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h index f3921faf138094f239b4a2ad53d2c1a48b6ee383..9399adfe99156a3098c6b6123f0111330d2c4040 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h +++ b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h @@ -27,8 +27,7 @@ namespace OHOS { namespace AbilityRuntime { class JsMissionListener : public AAFwk::MissionListenerStub { public: - JsMissionListener(NativeEngine* engine, std::shared_ptr &handler) - : engine_(engine), mainHandler_(handler) {} + explicit JsMissionListener(NativeEngine* engine) : engine_(engine) {} virtual ~JsMissionListener() = default; void OnMissionCreated(int32_t missionId) override; @@ -38,14 +37,13 @@ public: void AddJsListenerObject(int32_t listenerId, NativeValue* jsListenerObject); void RemoveJsListenerObject(int32_t listenerId); bool IsEmpty(); - void HandleMissionCallback(const char* methodName, int32_t missionId); + private: - void PostMissionCallback(const std::string &methodName, int32_t missionId); - void CallJsMethod(const char* methodName, NativeValue* const* argv = nullptr, size_t argc = 0); + void CallJsMethod(const std::string &methodName, int32_t missionId); + void CallJsMethodInner(const std::string &methodName, int32_t missionId); NativeEngine* engine_ = nullptr; std::map> jsListenerObjectMap_; - std::mutex listenerMutex_; std::shared_ptr mainHandler_; }; } // namespace AbilityRuntime diff --git a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp index 1deb73c862f381caa2fdfbd863af6c68a6153262..88a4ee42f45d7c082638c8fa4fee2d9cb058913a 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp @@ -23,6 +23,7 @@ #include "js_mission_listener.h" #include "js_runtime_utils.h" #include "mission_snapshot.h" +#include "pixel_map_napi.h" #include @@ -30,6 +31,11 @@ namespace OHOS { namespace AbilityRuntime { using namespace OHOS::AppExecFwk; using AbilityManagerClient = AAFwk::AbilityManagerClient; +namespace { + constexpr int32_t ARG_COUNT_TWO = 2; + constexpr int32_t ARG_COUNT_THREE = 3; + constexpr int32_t ERR_NOT_OK = -1; +} class JsMissionManager { public: JsMissionManager() = default; @@ -116,14 +122,13 @@ private: return engine.CreateNumber(missionListenerId_); } - auto mainHandler = GetMainHandler(); - missionListener_ = new JsMissionListener(&engine, mainHandler); - auto errcode = AbilityManagerClient::GetInstance()->RegisterMissionListener(missionListener_); - if (errcode == 0) { + missionListener_ = new JsMissionListener(&engine); + auto ret = AbilityManagerClient::GetInstance()->RegisterMissionListener(missionListener_); + if (ret == 0) { missionListener_->AddJsListenerObject(missionListenerId_, info.argv[0]); return engine.CreateNumber(missionListenerId_); } else { - HILOG_ERROR("RegisterMissionListener failed, ret = %{public}d", errcode); + HILOG_ERROR("RegisterMissionListener failed, ret = %{public}d", ret); missionListener_ = nullptr; return engine.CreateUndefined(); } @@ -132,30 +137,39 @@ private: NativeValue* OnUnregisterMissionListener(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); + int32_t errCode = 0; if (info.argc < 1) { HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } - uint32_t missionListenerId = -1; - if (!ConvertFromJsValue(engine, info.argv[0], missionListenerId)) { + int32_t missionListenerId = -1; + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], missionListenerId)) { HILOG_ERROR("Parse missionListenerId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } AsyncTask::CompleteCallback complete = - [&missionListener = missionListener_, missionListenerId] + [&missionListener = missionListener_, missionListenerId, errCode] (NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } + if (!missionListener) { + task.Resolve(engine, engine.CreateUndefined()); + return; + } missionListener->RemoveJsListenerObject(missionListenerId); if (!missionListener->IsEmpty()) { task.Resolve(engine, engine.CreateUndefined()); return; } - auto errcode = AbilityManagerClient::GetInstance()->UnRegisterMissionListener(missionListener); - if (errcode == 0) { + auto ret = AbilityManagerClient::GetInstance()->UnRegisterMissionListener(missionListener); + if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); missionListener = nullptr; } else { - task.Reject(engine, CreateJsError(engine, errcode, "Unregister mission listener failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Unregister mission listener failed.")); } }; @@ -169,29 +183,34 @@ private: NativeValue* OnGetMissionInfos(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); + int32_t errCode = 0; if (info.argc < 2) { HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } std::string deviceId; - if (!ConvertFromJsValue(engine, info.argv[0], deviceId)) { + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], deviceId)) { HILOG_ERROR("Parse deviceId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } int numMax = -1; - if (!ConvertFromJsValue(engine, info.argv[1], numMax)) { + if (!errCode && !ConvertFromJsValue(engine, info.argv[1], numMax)) { HILOG_ERROR("Parse numMax failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } AsyncTask::CompleteCallback complete = - [deviceId, numMax](NativeEngine &engine, AsyncTask &task, int32_t status) { + [deviceId, numMax, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } std::vector missionInfos; - auto errcode = AbilityManagerClient::GetInstance()->GetMissionInfos(deviceId, numMax, missionInfos); - if (errcode == 0) { + auto ret = AbilityManagerClient::GetInstance()->GetMissionInfos(deviceId, numMax, missionInfos); + if (ret == 0) { task.Resolve(engine, CreateJsMissionInfoArray(engine, missionInfos)); } else { - task.Reject(engine, CreateJsError(engine, errcode, "Get mission infos failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Get mission infos failed.")); } }; @@ -205,29 +224,34 @@ private: NativeValue* OnGetMissionInfo(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); + int32_t errCode = 0; if (info.argc < 2) { HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } std::string deviceId; - if (!ConvertFromJsValue(engine, info.argv[0], deviceId)) { + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], deviceId)) { HILOG_ERROR("Parse deviceId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } - int missionId = -1; - if (!ConvertFromJsValue(engine, info.argv[1], missionId)) { + int32_t missionId = -1; + if (!errCode && !ConvertFromJsValue(engine, info.argv[1], missionId)) { HILOG_ERROR("Parse missionId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } AsyncTask::CompleteCallback complete = - [deviceId, missionId](NativeEngine &engine, AsyncTask &task, int32_t status) { + [deviceId, missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } AAFwk::MissionInfo missionInfo; - auto errcode = AbilityManagerClient::GetInstance()->GetMissionInfo(deviceId, missionId, missionInfo); - if (errcode == 0) { + auto ret = AbilityManagerClient::GetInstance()->GetMissionInfo(deviceId, missionId, missionInfo); + if (ret == 0) { task.Resolve(engine, CreateJsMissionInfo(engine, missionInfo)); } else { - task.Reject(engine, CreateJsError(engine, errcode, "Get mission info failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Get mission info failed.")); } }; @@ -241,29 +265,80 @@ private: NativeValue* OnGetMissionSnapShot(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); - return nullptr; + int32_t errCode = 0; + if (info.argc != ARG_COUNT_TWO && info.argc != ARG_COUNT_THREE) { + HILOG_ERROR("missionSnapshot: need two or three params"); + errCode = ERR_NOT_OK; + } + std::string deviceId; + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], deviceId)) { + HILOG_ERROR("missionSnapshot: Parse deviceId failed"); + errCode = ERR_NOT_OK; + } + int32_t missionId = -1; + if (!errCode && !ConvertFromJsValue(engine, info.argv[1], missionId)) { + HILOG_ERROR("missionSnapshot: Parse missionId failed"); + errCode = ERR_NOT_OK; + } + AsyncTask::CompleteCallback complete = + [deviceId, missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } + AAFwk::MissionSnapshot missionSnapshot; + auto ret = AbilityManagerClient::GetInstance()->GetMissionSnapshot( + deviceId, missionId, missionSnapshot); + if (ret == 0) { + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + NativeValue* abilityValue = engine.CreateObject(); + NativeObject* abilityObj = ConvertNativeValueTo(abilityValue); + abilityObj->SetProperty( + "bundleName", CreateJsValue(engine, missionSnapshot.topAbility.GetBundleName())); + abilityObj->SetProperty( + "abilityName", CreateJsValue(engine, missionSnapshot.topAbility.GetAbilityName())); + object->SetProperty("ability", abilityValue); + auto snapshotValue = reinterpret_cast(Media::PixelMapNapi::CreatePixelMap( + reinterpret_cast(&engine), missionSnapshot.snapshot)); + object->SetProperty("snapshot", snapshotValue); + task.Resolve(engine, objValue); + } else { + task.Reject(engine, CreateJsError(engine, ret, "Get mission snapshot failed.")); + } + }; + NativeValue* lastParam = (info.argc == ARG_COUNT_TWO) ? nullptr : info.argv[2]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; } NativeValue* OnLockMission(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); + int32_t errCode = 0; if (info.argc == 0) { HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } - int missionId = -1; - if (!ConvertFromJsValue(engine, info.argv[0], missionId)) { + int32_t missionId = -1; + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], missionId)) { HILOG_ERROR("Parse missionId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } AsyncTask::CompleteCallback complete = - [missionId](NativeEngine &engine, AsyncTask &task, int32_t status) { - auto errcode = AbilityManagerClient::GetInstance()->LockMissionForCleanup(missionId); - if (errcode == 0) { + [missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } + auto ret = AbilityManagerClient::GetInstance()->LockMissionForCleanup(missionId); + if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); } else { - task.Reject(engine, CreateJsError(engine, errcode, "Lock mission failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Lock mission failed.")); } }; @@ -277,23 +352,28 @@ private: NativeValue* OnUnlockMission(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); + int32_t errCode = 0; if (info.argc == 0) { HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } - int missionId = -1; - if (!ConvertFromJsValue(engine, info.argv[0], missionId)) { + int32_t missionId = -1; + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], missionId)) { HILOG_ERROR("Parse missionId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } AsyncTask::CompleteCallback complete = - [missionId](NativeEngine &engine, AsyncTask &task, int32_t status) { - auto errcode = AbilityManagerClient::GetInstance()->UnlockMissionForCleanup(missionId); - if (errcode == 0) { + [missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } + auto ret = AbilityManagerClient::GetInstance()->UnlockMissionForCleanup(missionId); + if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); } else { - task.Reject(engine, CreateJsError(engine, errcode, "Unlock mission failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Unlock mission failed.")); } }; @@ -307,23 +387,28 @@ private: NativeValue* OnClearMission(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); + int32_t errCode = 0; if (info.argc == 0) { HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } - int missionId = -1; - if (!ConvertFromJsValue(engine, info.argv[0], missionId)) { + int32_t missionId = -1; + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], missionId)) { HILOG_ERROR("Parse missionId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } AsyncTask::CompleteCallback complete = - [missionId](NativeEngine &engine, AsyncTask &task, int32_t status) { - auto errcode = AbilityManagerClient::GetInstance()->CleanMission(missionId); - if (errcode == 0) { + [missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } + auto ret = AbilityManagerClient::GetInstance()->CleanMission(missionId); + if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); } else { - task.Reject(engine, CreateJsError(engine, errcode, "Clear mission failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Clear mission failed.")); } }; @@ -339,11 +424,11 @@ private: HILOG_INFO("%{public}s is called", __FUNCTION__); AsyncTask::CompleteCallback complete = [](NativeEngine &engine, AsyncTask &task, int32_t status) { - auto errcode = AbilityManagerClient::GetInstance()->CleanAllMissions(); - if (errcode == 0) { + auto ret = AbilityManagerClient::GetInstance()->CleanAllMissions(); + if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); } else { - task.Reject(engine, CreateJsError(engine, errcode, "Clear all missions failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Clear all missions failed.")); } }; @@ -357,23 +442,28 @@ private: NativeValue* OnMoveMissionToFront(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); + int32_t errCode = 0; if (info.argc == 0) { HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } - int missionId = -1; - if (!ConvertFromJsValue(engine, info.argv[0], missionId)) { + int32_t missionId = -1; + if (!errCode && !ConvertFromJsValue(engine, info.argv[0], missionId)) { HILOG_ERROR("Parse missionId failed"); - return engine.CreateUndefined(); + errCode = ERR_NOT_OK; } AsyncTask::CompleteCallback complete = - [missionId](NativeEngine &engine, AsyncTask &task, int32_t status) { - auto errcode = AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId); - if (errcode == 0) { + [missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (errCode != 0) { + task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); + return; + } + auto ret = AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId); + if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); } else { - task.Reject(engine, CreateJsError(engine, errcode, "Move mission to front failed.")); + task.Reject(engine, CreateJsError(engine, ret, "Move mission to front failed.")); } }; @@ -384,17 +474,8 @@ private: return result; } - std::shared_ptr GetMainHandler() - { - if (!mainHandler_) { - mainHandler_ = std::make_shared(EventRunner::GetMainEventRunner()); - } - return mainHandler_; - } - sptr missionListener_ = nullptr; uint32_t missionListenerId_ = 0; - std::shared_ptr mainHandler_; }; NativeValue* JsMissionManagerInit(NativeEngine* engine, NativeValue* exportObj) @@ -424,6 +505,7 @@ NativeValue* JsMissionManagerInit(NativeEngine* engine, NativeValue* exportObj) BindNativeFunction(*engine, *object, "clearMission", JsMissionManager::ClearMission); BindNativeFunction(*engine, *object, "clearAllMissions", JsMissionManager::ClearAllMissions); BindNativeFunction(*engine, *object, "moveMissionToFront", JsMissionManager::MoveMissionToFront); + BindNativeFunction(*engine, *object, "moveMissionToFront", JsMissionManager::MoveMissionToFront); return engine->CreateUndefined(); } } // namespace AbilityRuntime diff --git a/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn index 58855e0158d26956d5a62c140b2704596a161583..f84c7f39300841b82ba3ce7952abe4846a19a675 100644 --- a/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn +++ b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn @@ -23,40 +23,42 @@ ohos_shared_library("particleability") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility", "//foundation/aafwk/standard/services/common/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_dataability", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_rdb/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/include", ] sources = [ "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_operation.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/js_utils.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_dataability/napi_data_ability_predicates.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/native_rdb/napi_result_set.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/src/js_utils.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/src/napi_data_ability_predicates.cpp", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/src/napi_result_set.cpp", "native_module.cpp", "particle_ability.cpp", ] deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager:dataobs_manager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/libuv:uv_static", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:ability_manager", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", @@ -67,5 +69,5 @@ ohos_shared_library("particleability") { relative_install_dir = "module/ability" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.h b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.h index 0ee568145ac0c25a59ce30694b660d9e3805a754..ad1c91c7b568c0a5bb65af1e2b902183e96ac806 100644 --- a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.h +++ b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.h @@ -16,6 +16,7 @@ #ifndef OHOS_APPEXECFWK_PARTICLE_ABILITY_H #define OHOS_APPEXECFWK_PARTICLE_ABILITY_H +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" diff --git a/interfaces/kits/napi/aafwk/service_extension_context/BUILD.gn b/interfaces/kits/napi/aafwk/service_extension_context/BUILD.gn index 87666e198a206c5a66bafc094f8c63e37cfeecd0..adb3c0de7987d035be59c3394ec81902fbb6d187 100644 --- a/interfaces/kits/napi/aafwk/service_extension_context/BUILD.gn +++ b/interfaces/kits/napi/aafwk/service_extension_context/BUILD.gn @@ -46,5 +46,5 @@ ohos_shared_library("serviceextensioncontext_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/service_extension_context/service_extension_context.js b/interfaces/kits/napi/aafwk/service_extension_context/service_extension_context.js index 1db55b065f53ac80a5038348aeda4bfc09d54c79..5821bb3953c76bf7ff7996ecb57754b2aacea7cd 100755 --- a/interfaces/kits/napi/aafwk/service_extension_context/service_extension_context.js +++ b/interfaces/kits/napi/aafwk/service_extension_context/service_extension_context.js @@ -18,6 +18,7 @@ var ExtensionContext = requireNapi("application.ExtensionContext") class ServiceExtensionContext extends ExtensionContext { constructor(obj) { super(obj); + this.extensionAbilityInfo = obj.extensionAbilityInfo } startAbility(want, options, callback) { @@ -30,6 +31,16 @@ class ServiceExtensionContext extends ExtensionContext { return this.__context_impl__.connectAbility(want, options); } + startAbilityWithAccount(want, accountId, options, callback) { + console.log("startAbilityWithAccount"); + return this.__context_impl__.startAbilityWithAccount(want, accountId, options, callback); + } + + connectAbilityWithAccount(want, accountId, options) { + console.log("connectAbilityWithAccount"); + return this.__context_impl__.connectAbilityWithAccount(want, accountId, options); + } + disconnectAbility(connection, callback) { console.log("disconnectAbility"); return this.__context_impl__.disconnectAbility(connection, callback); diff --git a/interfaces/kits/napi/aafwk/serviceextension/BUILD.gn b/interfaces/kits/napi/aafwk/serviceextension/BUILD.gn index fe08740b7fe209403cd5d95442acae7b14cd69c7..e72e10f4fd675f68bd22afe0b3011f27570162be 100644 --- a/interfaces/kits/napi/aafwk/serviceextension/BUILD.gn +++ b/interfaces/kits/napi/aafwk/serviceextension/BUILD.gn @@ -46,5 +46,5 @@ ohos_shared_library("serviceextension_napi") { relative_install_dir = "module/application" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/static_subscriber_extension/BUILD.gn b/interfaces/kits/napi/aafwk/static_subscriber_extension/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4e8307e2b20918ded54a6b382b20eac1da0dac11 --- /dev/null +++ b/interfaces/kits/napi/aafwk/static_subscriber_extension/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_static_subscriber_extension_abc") { + src_js = rebase_path("static_subscriber_extension.js") + dst_file = rebase_path(target_out_dir + "/static_subscriber_extension.abc") + in_puts = [ "static_subscriber_extension.js" ] + out_puts = [ target_out_dir + "/static_subscriber_extension.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("static_subscriber_extension_js") { + input = "static_subscriber_extension.js" + output = target_out_dir + "/static_subscriber_extension.o" +} + +gen_js_obj("static_subscriber_extension_abc") { + input = get_label_info(":gen_static_subscriber_extension_abc", + "target_out_dir") + "/static_subscriber_extension.abc" + output = target_out_dir + "/static_subscriber_extension_abc.o" + dep = ":gen_static_subscriber_extension_abc" +} + +ohos_shared_library("staticsubscriberextension_napi") { + sources = [ "static_subscriber_extension_module.cpp" ] + + deps = [ + ":static_subscriber_extension_abc", + ":static_subscriber_extension_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/static_subscriber_extension/static_subscriber_extension.js b/interfaces/kits/napi/aafwk/static_subscriber_extension/static_subscriber_extension.js new file mode 100644 index 0000000000000000000000000000000000000000..4e31c2ff63721acebcb1c9df1e26cee46f2470fe --- /dev/null +++ b/interfaces/kits/napi/aafwk/static_subscriber_extension/static_subscriber_extension.js @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +class StaticSubscriberExtension { + onCommonEventTriggered(event) { + console.log('onCommonEventTriggered, event:' + event.code); + } +} + +export default StaticSubscriberExtension \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/static_subscriber_extension/static_subscriber_extension_module.cpp b/interfaces/kits/napi/aafwk/static_subscriber_extension/static_subscriber_extension_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a0bd21ded14662b8a4b8a2dd3fb005da7ee66b2 --- /dev/null +++ b/interfaces/kits/napi/aafwk/static_subscriber_extension/static_subscriber_extension_module.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_static_subscriber_extension_js_start[]; +extern const char _binary_static_subscriber_extension_js_end[]; +extern const char _binary_static_subscriber_extension_abc_start[]; +extern const char _binary_static_subscriber_extension_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_StaticSubscriberExtension_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.StaticSubscriberExtension", + .fileName = "application/libstaticsubscriberextension_napi.so/StaticSubscriberExtension.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_StaticSubscriberExtension_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_static_subscriber_extension_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_static_subscriber_extension_js_end - + _binary_static_subscriber_extension_js_start; + } +} + +// StaticSubscriberExtension JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_StaticSubscriberExtension_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_static_subscriber_extension_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_static_subscriber_extension_abc_end - + _binary_static_subscriber_extension_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/static_subscriber_extension_context/BUILD.gn b/interfaces/kits/napi/aafwk/static_subscriber_extension_context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a22f840fda77f4f33420fda70c038e2cd24d7b96 --- /dev/null +++ b/interfaces/kits/napi/aafwk/static_subscriber_extension_context/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_static_subscriber_extension_context_abc") { + src_js = rebase_path("static_subscriber_extension_context.js") + dst_file = + rebase_path(target_out_dir + "/static_subscriber_extension_context.abc") + in_puts = [ "static_subscriber_extension_context.js" ] + out_puts = [ target_out_dir + "/static_subscriber_extension_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("static_subscriber_extension_context_js") { + input = "static_subscriber_extension_context.js" + output = target_out_dir + "/static_subscriber_extension_context.o" +} + +gen_js_obj("static_subscriber_extension_context_abc") { + input = get_label_info(":gen_static_subscriber_extension_context_abc", + "target_out_dir") + + "/static_subscriber_extension_context.abc" + output = target_out_dir + "/static_subscriber_extension_context_abc.o" + dep = ":gen_static_subscriber_extension_context_abc" +} + +ohos_shared_library("staticsubscriberextensioncontext_napi") { + sources = [ "static_subscriber_extension_context_module.cpp" ] + + deps = [ + ":static_subscriber_extension_context_abc", + ":static_subscriber_extension_context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/static_subscriber_extension_context/static_subscriber_extension_context.js b/interfaces/kits/napi/aafwk/static_subscriber_extension_context/static_subscriber_extension_context.js new file mode 100644 index 0000000000000000000000000000000000000000..7df95b9b7d33cce541291f8ff6e917005c083e1e --- /dev/null +++ b/interfaces/kits/napi/aafwk/static_subscriber_extension_context/static_subscriber_extension_context.js @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +var ExtensionContext = requireNapi("application.ExtensionContext") + +class StaticSubscriberExtensionContext extends ExtensionContext { + constructor(obj) { + super(obj); + } +} + +export default StaticSubscriberExtensionContext \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/static_subscriber_extension_context/static_subscriber_extension_context_module.cpp b/interfaces/kits/napi/aafwk/static_subscriber_extension_context/static_subscriber_extension_context_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3731cfe899604a01887634581cab6659f59ca6d8 --- /dev/null +++ b/interfaces/kits/napi/aafwk/static_subscriber_extension_context/static_subscriber_extension_context_module.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "native_engine/native_engine.h" + +extern const char _binary_static_subscriber_extension_context_js_start[]; +extern const char _binary_static_subscriber_extension_context_js_end[]; +extern const char _binary_static_subscriber_extension_context_abc_start[]; +extern const char _binary_static_subscriber_extension_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_StaticSubscriberExtensionContext_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.StaticSubscriberExtensionContext", + .fileName = "application/libstaticsubscriberextensioncontext_napi.so/StaticSubscriberExtensionContext.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_StaticSubscriberExtensionContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_static_subscriber_extension_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_static_subscriber_extension_context_js_end - + _binary_static_subscriber_extension_context_js_start; + } +} + +// StaticSubscriberExtensionContext JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_StaticSubscriberExtensionContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_static_subscriber_extension_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_static_subscriber_extension_context_abc_end - + _binary_static_subscriber_extension_context_abc_start; + } +} diff --git a/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn b/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn index c05883224b654afa913959eae21ea7d193bae8c1..91b36056afa2a2e9a19851a5384136942aab6009 100644 --- a/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn +++ b/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn @@ -29,24 +29,25 @@ ohos_shared_library("wantconstant") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/kits:appkit_native", "//third_party/libuv:uv_static", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:ability_manager", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", ] relative_install_dir = "module/ability" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/interfaces/kits/napi/aafwk/wantConstant/want_constant.h b/interfaces/kits/napi/aafwk/wantConstant/want_constant.h index 5a44ae771f36ebe524713b2e0f971bbe0ee42667..24bbb760f7a34abc80522a17881ce1193e55cc54 100644 --- a/interfaces/kits/napi/aafwk/wantConstant/want_constant.h +++ b/interfaces/kits/napi/aafwk/wantConstant/want_constant.h @@ -15,6 +15,7 @@ #ifndef OHOS_APPEXECFWK_WANT_CONSTANT_H #define OHOS_APPEXECFWK_WANT_CONSTANT_H +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" diff --git a/ohos.build b/ohos.build index cf7185cccbed613ae1b6395d0663dca8678643d1..c21ef63994e899d8bbc70ec2cd1e1b5878dced80 100755 --- a/ohos.build +++ b/ohos.build @@ -1,16 +1,18 @@ { "parts": { - "aafwk_standard": { + "ability_runtime": { "module_list": [ "//foundation/aafwk/standard/services:services_target", - "//foundation/aafwk/standard/tools:tools_target", "//foundation/aafwk/standard/interfaces/innerkits:innerkits_target", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:static_subscriber_ipc", + "//foundation/aafwk/standard/frameworks/kits/ability/native:service_extension_module", "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", "//foundation/aafwk/standard/interfaces/kits/napi:napi_packages", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", - "//foundation/aafwk/standard/zidl/test/native:zidl_client_test", - "//foundation/aafwk/standard/zidl/test/native:zidl_server_test" + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appexec", + "//foundation/aafwk/standard/test/resource/amssystemtestability/abilitySrc:ams_system_test_app" ], "inner_kits": [ { @@ -95,18 +97,138 @@ ] }, "name": "//foundation/aafwk/standard/interfaces/innerkits/runtime:runtime" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/napi_base_context/include", + "header_files": [ + "napi_base_context.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/napi_base_context:napi_base_context" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include", + "header_files": [ + "appmgr/app_mgr_client.h", + "appmgr/iapp_state_callback.h", + "appmgr/app_state_callback_host.h", + "appmgr/app_mgr_constants.h", + "appmgr/app_process_data.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/frameworks/kits/ability/native/include/", + "header_files": [ + "extension_base.h", + "extension_context.h", + "extension_module_loader.h", + "service_extension.h", + "service_extension_context.h" + ] + }, + "name": "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/common/task_dispatcher/include", + "header_files": [ + "dispatcher/parallel_task_dispatcher.h", + "dispatcher/task_dispatcher_context", + "threading/runnable.h", + "task/task.h" + ] + }, + "name": "//foundation/aafwk/standard/common:common_target" } ], "test_list": [ "//foundation/aafwk/standard/frameworks/kits/content/cpp/test:unittest", "//foundation/aafwk/standard/frameworks/kits/ability/native/test:unittest", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test:moduletest", "//foundation/aafwk/standard/frameworks/kits/test:moduletest", "//foundation/aafwk/standard/services/test:moduletest", "//foundation/aafwk/standard/services:unittest", + "//foundation/aafwk/standard/common/task_dispatcher/test:unittest", + "//foundation/aafwk/standard/common/test:moduletest", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/test:unittest", + "//foundation/aafwk/standard/frameworks/kits/appkit/test:moduletest", + "//foundation/aafwk/standard/services/appmgr/test:unittest" + ] + }, + "ability_tools": { + "module_list": [ + "//foundation/aafwk/standard/tools:tools_target" + ], + "inner_kits": [ + ], + "test_list": [ "//foundation/aafwk/standard/tools/test:systemtest", "//foundation/aafwk/standard/tools/test:moduletest", - "//foundation/aafwk/standard/tools/test:unittest", - "//foundation/aafwk/standard/tools/zip/test:unittest" + "//foundation/aafwk/standard/tools/test:unittest" + ] + }, + "zidl": { + "module_list": [ + "//foundation/aafwk/standard/zidl/test/native:zidl_client_test", + "//foundation/aafwk/standard/zidl/test/native:zidl_server_test" + ], + "inner_kits": [ + ], + "test_list": [ + ] + }, + "form_runtime": { + "module_list": [ + "//foundation/aafwk/standard/sa_profile:form_sa_profile", + "//foundation/aafwk/standard/services:fms_services_target", + "//foundation/aafwk/standard/interfaces/innerkits:fms_innerkits_target", + "//foundation/aafwk/standard/frameworks/kits/fmskit:fmskit_native", + "//foundation/aafwk/standard/interfaces/kits/napi:form_napi_packages", + "//foundation/aafwk/standard/test/resource/formsystemtestability:fms_system_test_app" + ], + "inner_kits": [ + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "header_files": [ + "form_death_callback.h", + "form_host_interface.h", + "form_host_stub.h", + "form_js_info.h", + "form_mgr_interface.h", + "form_mgr_stub.h", + "form_provider_data.h", + "form_provider_interface.h", + "form_provider_stub.h", + "form_supply_interface.h", + "form_supply_stub.h", + "provider_connect_stub.h", + "form_constants.h", + "form_js_info.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/form_manager:form_manager" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "header_files": [ + "form_callback_interface.h", + "form_host_client.h", + "form_mgr.h" + ] + }, + "name": "//foundation/aafwk/standard/frameworks/kits/fmskit:fmskit_native" + } + ], + "test_list": [ + "//foundation/aafwk/standard/services/formmgr/test:unittest", + "//foundation/aafwk/standard/test/systemtest:systemtest" ] } }, diff --git a/sa_profile/403.xml b/sa_profile/403.xml new file mode 100644 index 0000000000000000000000000000000000000000..7176a66dd1c65c470f5b87e043ca7a7567495ef8 --- /dev/null +++ b/sa_profile/403.xml @@ -0,0 +1,27 @@ + + + + foundation + + 403 + /system/lib64/libfms.z.so + + + true + false + 1 + + diff --git a/sa_profile/501.xml b/sa_profile/501.xml new file mode 100644 index 0000000000000000000000000000000000000000..5ea1be2dbd8f6168ace29e693b99fa6a92fede80 --- /dev/null +++ b/sa_profile/501.xml @@ -0,0 +1,27 @@ + + + + foundation + + 501 + /system/lib64/libams.z.so + + + true + false + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn index 018d522a31026761ee375fbec8cfa2ca3efa76c3..60bcceccf9796baa2d5faac3810c04871199dc14 100644 --- a/sa_profile/BUILD.gn +++ b/sa_profile/BUILD.gn @@ -17,7 +17,14 @@ ohos_sa_profile("aafwk_sa_profile") { sources = [ "180.xml", "182.xml", + "501.xml", ] - part_name = "aafwk_standard" + part_name = "ability_runtime" +} + +ohos_sa_profile("form_sa_profile") { + sources = [ "403.xml" ] + + part_name = "form_runtime" } diff --git a/services/BUILD.gn b/services/BUILD.gn index f3d58e1151eeeca939db7c27f78d450392bba5b7..8721ed8539aa6091687309428172df79b41db386 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -14,10 +14,15 @@ group("services_target") { deps = [ "abilitymgr:abilityms_target", + "appmgr:ams_target", "dataobsmgr:dataobsms", ] } +group("fms_services_target") { + deps = [ "formmgr:fms_target" ] +} + group("unittest") { testonly = true diff --git a/services/abilitymgr/BUILD.gn b/services/abilitymgr/BUILD.gn index 6865fc8bc2fdd62fe339b8068f8b83879e50d2f1..a849059eb89b3dbef725bd6ee829e6ea2a2a6163 100644 --- a/services/abilitymgr/BUILD.gn +++ b/services/abilitymgr/BUILD.gn @@ -35,6 +35,7 @@ config("abilityms_config") { "${EVENT_DIR}/frameworks/core/include", "${EVENT_DIR}/interfaces/innerkits/native/include", "${innerkits_path}/ability_manager/include", + "${innerkits_path}/app_manager/include", "${innerkits_path}/base/include", "${innerkits_path}/want/include", "${innerkits_path}/want/include/ohos/aafwk/content", @@ -53,10 +54,16 @@ config("abilityms_config") { "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk/include", "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability/include", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager/include", + "//foundation/aafwk/standard/tools/aa/include", "//foundation/graphic/standard/interfaces/innerkits/wmservice", "//base/global/i18n_standard/frameworks/intl/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//base/hiviewdfx/hiview/adapter/utility/include", + "//base/account/os_account/frameworks/common/account_error/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/log/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "//base/hiviewdfx/hicollie/interfaces/native/innerkits/include", ] cflags = [] if (target_cpu == "arm") { @@ -72,12 +79,14 @@ ohos_shared_library("abilityms") { deps = [ "${innerkits_path}/base:base", "${innerkits_path}/want:want", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/hiviewdfx/hiview/adapter/utility:hiview_adapter_utility", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", @@ -87,31 +96,33 @@ ohos_shared_library("abilityms") { "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:app_manager", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", + "device_manager_base:devicemanagersdk", "dsoftbus_standard:softbus_client", + "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "resmgr_standard:global_resmgr", ] - public_deps = [ - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", - "//foundation/graphic/standard:libwmservice", - ] + public_deps = [ "//foundation/graphic/standard:libwmservice" ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } ohos_prebuilt_etc("ams_service_config.json") { source = "//foundation/aafwk/standard/services/abilitymgr/resource/ams_service_config.json" subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } group("ams_service_config") { diff --git a/services/abilitymgr/abilitymgr.gni b/services/abilitymgr/abilitymgr.gni index 9f86004dab7293d46b557db404a37e8edd322c76..7813a63a59d19af354d3064a07a1c57bc66b5025 100644 --- a/services/abilitymgr/abilitymgr.gni +++ b/services/abilitymgr/abilitymgr.gni @@ -39,6 +39,8 @@ abilityms_files = [ "${services_path}/abilitymgr/src/lifecycle_state_info.cpp", "${services_path}/abilitymgr/src/stack_info.cpp", "${services_path}/abilitymgr/src/mission_stack_info.cpp", + "${services_path}/abilitymgr/src/ability_running_info.cpp", + "${services_path}/abilitymgr/src/extension_running_info.cpp", "${services_path}/abilitymgr/src/mission_record_info.cpp", "${services_path}/abilitymgr/src/ability_record_info.cpp", "${services_path}/abilitymgr/src/ability_mission_info.cpp", @@ -67,10 +69,8 @@ abilityms_files = [ "${services_path}/abilitymgr/src/screenshot_handler.cpp", "${services_path}/abilitymgr/src/screenshot_response.cpp", "${services_path}/abilitymgr/src/ams_configuration_parameter.cpp", - "${services_path}/abilitymgr/src/mission_index_info.cpp", "${services_path}/abilitymgr/src/lock_screen_event_subscriber.cpp", - "${services_path}/abilitymgr/src/configuration_distributor.cpp", # new ability manager service here "${services_path}/abilitymgr/src/inner_mission_info.cpp", @@ -90,4 +90,10 @@ abilityms_files = [ "${services_path}/abilitymgr/src/stop_user_callback_proxy.cpp", "${services_path}/abilitymgr/src/stop_user_callback_stub.cpp", "${services_path}/abilitymgr/src/kernal_ability_manager.cpp", + "${services_path}/abilitymgr/src/call_container.cpp", + "${services_path}/abilitymgr/src/call_record.cpp", + + #multi user + "${services_path}/abilitymgr/src/user_controller.cpp", + "${services_path}/abilitymgr/src/user_event_handler.cpp", ] diff --git a/services/abilitymgr/include/ability_connect_manager.h b/services/abilitymgr/include/ability_connect_manager.h index e5f8ceb6b409004928e03c5c4fad224b2cff8d44..1c070cc165022d97b28f9c0f44f91f084ec1666e 100644 --- a/services/abilitymgr/include/ability_connect_manager.h +++ b/services/abilitymgr/include/ability_connect_manager.h @@ -23,6 +23,8 @@ #include "ability_connect_callback_interface.h" #include "ability_event_handler.h" #include "ability_record.h" +#include "ability_running_info.h" +#include "extension_running_info.h" #include "connection_record.h" #include "element_name.h" #include "ohos/aafwk/content/want.h" @@ -181,6 +183,10 @@ public: ConnectListType GetConnectRecordListByCallback(sptr callback); void RemoveAll(); + void GetExtensionRunningInfos(int upperLimit, std::vector &info, const int32_t userId); + + void GetAbilityRunningInfos(std::vector &info); + /** * SetEventHandler. * @@ -218,7 +224,7 @@ public: */ void OnAbilityDied(const std::shared_ptr &abilityRecord); - void DumpState(std::vector &info, const std::string &args = "") const; + void DumpState(std::vector &info, bool isClient, const std::string &args = "") const; // MSG 0 - 20 represents timeout message static constexpr uint32_t LOAD_TIMEOUT_MSG = 0; diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h old mode 100755 new mode 100644 index 849cd60fd050785f28de4d9fa0dbe7733ed1c5fb..75819fbc38fec7368ba827dfc67d83d2ac0a43ce --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -39,9 +39,13 @@ public: * * @param want, the want of the ability to start. * @param requestCode, Ability request code. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE) override; + virtual int StartAbility( + const Want &want, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; /** * StartAbility with want, send want to ability manager service. @@ -49,21 +53,30 @@ public: * @param want, the want of the ability to start. * @param callerToken, caller ability token. * @param requestCode the resultCode of the ability to start. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ virtual int StartAbility( - const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + const Want &want, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; /** * Starts a new ability with specific start settings. * * @param want Indicates the ability to start. - * @param requestCode the resultCode of the ability to start. + * @param callerToken caller ability token. * @param abilityStartSetting Indicates the setting ability used to start. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + virtual int StartAbility( + const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; /** * Starts a new ability with specific start options. @@ -71,11 +84,16 @@ public: * @param want, the want of the ability to start. * @param startOptions Indicates the options used to start. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const StartOptions &startOptions, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + virtual int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; /** * TerminateAbility, terminate the special ability. @@ -111,10 +129,14 @@ public: * @param want, Special want for service type's ability. * @param connect, Callback used to notify caller the result of connecting or disconnecting. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ virtual int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) override; + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) override; /** * DisconnectAbility, connect session with service ability. @@ -207,7 +229,8 @@ public: * @return Returns ERR_OK on success, others on failure. */ virtual void DumpState(const std::string &args, std::vector &state) override; - + virtual void DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) override; /** * Destroys this Service ability if the number of times it * has been started equals the number represented by @@ -226,7 +249,7 @@ public: * @param want, Special want for service type's ability. * @return Returns true if this Service ability will be destroyed; returns false otherwise. */ - virtual int StopServiceAbility(const Want &want) override; + virtual int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) override; /** * Obtains information about ability stack that are running on the device. @@ -520,19 +543,102 @@ public: virtual int CleanAllMissions() override; virtual int MoveMissionToFront(int32_t missionId) override; + + /** + * Start Ability, connect session with common ability. + * + * @param want, Special want for service type's ability. + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) override; + + /** + * Release Ability, disconnect session with common ability. + * + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @param element, the element of target service. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ReleaseAbility( + const sptr &connect, const AppExecFwk::ElementName &element) override; virtual int StartUser(int userId) override; virtual int StopUser(int userId, const sptr &callback) override; + virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) override; + + virtual int GetAbilityRunningInfos(std::vector &info) override; + + virtual int GetExtensionRunningInfos(int upperLimit, std::vector &info) override; + + virtual int GetProcessRunningInfos(std::vector &info) override; + virtual int RegisterMissionListener(const std::string &deviceId, const sptr &listener) override; virtual int UnRegisterMissionListener(const std::string &deviceId, const sptr &listener) override; + /** + * Set ability controller. + * + * @param abilityController, The ability controller. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override; + + /** + * Is user a stability test. + * + * @return Returns true if user is a stability test. + */ + virtual bool IsRunningInStabilityTest() override; + + virtual int RegisterSnapshotHandler(const sptr& handler) override; + + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) override; + + virtual int StartUserTest(const Want &want, const sptr &observer) override; + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override; + + /** + * GetCurrentTopAbility, get the token of current top ability. + * + * @param token, the token of current top ability. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetCurrentTopAbility(sptr &token) override; + + /** + * The delegator calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DelegatorDoAbilityForeground(const sptr &token) override; + + /** + * The delegator calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DelegatorDoAbilityBackground(const sptr &token) override; + + /** + * Send not response process ID to ability manager service. + * @param pid The not response process ID. + */ + virtual bool SendANRProcessID(int pid) override; + private: - template + template int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); bool WriteInterfaceToken(MessageParcel &data); diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h old mode 100755 new mode 100644 index 04fd7a110a0ec988bafe20e06026953bf42457ab..a2c40fc3d196f824c423fc6b0d904cf0b3fc2159 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -29,8 +29,6 @@ #include "bundlemgr/bundle_mgr_interface.h" #include "bundle_constants.h" #include "data_ability_manager.h" -#include "distributed_sched_interface.h" -#include "distributed_sched_proxy.h" #include "hilog_wrapper.h" #include "iremote_object.h" #include "kernal_ability_manager.h" @@ -41,11 +39,13 @@ #include "ability_config.h" #include "pending_want_manager.h" #include "ams_configuration_parameter.h" -#include "event_handler.h" +#include "user_controller.h" namespace OHOS { namespace AAFwk { enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +const int32_t BASE_USER_RANGE = 200000; +using OHOS::AppExecFwk::IAbilityController; class PendingWantManager; /** @@ -68,20 +68,26 @@ public: * * @param want, the want of the ability to start. * @param requestCode, Ability request code. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE) override; + virtual int StartAbility( + const Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = DEFAULT_INVAL_VALUE) override; /** * StartAbility with want, send want to ability manager service. * * @param want, the want of the ability to start. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ virtual int StartAbility( - const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + const Want &want, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; /** * Starts a new ability with specific start settings. @@ -89,11 +95,16 @@ public: * @param want Indicates the ability to start. * @param abilityStartSetting Indicates the setting ability used to start. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + virtual int StartAbility( + const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; /** * Starts a new ability with specific start options. @@ -101,11 +112,16 @@ public: * @param want, the want of the ability to start. * @param startOptions Indicates the options used to start. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const StartOptions &startOptions, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + virtual int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) override; /** * TerminateAbility, terminate the special ability. @@ -141,10 +157,14 @@ public: * @param want, Special want for service type's ability. * @param connect, Callback used to notify caller the result of connecting or disconnecting. * @param callerToken, caller ability token. + * @param userId, Designation User ID. * @return Returns ERR_OK on success, others on failure. */ virtual int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) override; + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) override; /** * ContinueMission, continue ability from mission center. @@ -305,7 +325,7 @@ public: * * @param userId, user id. */ - void SetStackManager(int userId); + void SetStackManager(int userId, bool switchUser); /** * GetStackManager, get the current stack manager. @@ -329,6 +349,8 @@ public: * @return Returns ERR_OK on success, others on failure. */ virtual void DumpState(const std::string &args, std::vector &info) override; + virtual void DumpSysState( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int UserID) override; /** * Obtains information about ability stack that are running on the device. @@ -356,7 +378,7 @@ public: * @param want, Special want for service type's ability. * @return Returns true if this Service ability will be destroyed; returns false otherwise. */ - virtual int StopServiceAbility(const Want &want) override; + virtual int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) override; /** * Get the list of the missions that the user has recently launched, @@ -580,7 +602,7 @@ public: * * @param userId, user id. */ - void InitMissionListManager(int userId); + void InitMissionListManager(int userId, bool switchUser); virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override; @@ -646,6 +668,26 @@ public: */ virtual void GetSystemMemoryAttr(AppExecFwk::SystemMemoryAttr &memoryInfo) override; + /** + * Start Ability, connect session with common ability. + * + * @param want, Special want for service type's ability. + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) override; + + /** + * Release Ability, disconnect session with common ability. + * + * @param connect, Callback used to notify caller the result of connecting or disconnecting. + * @param element, the element of target service. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ReleaseAbility( + const sptr &connect, const AppExecFwk::ElementName &element) override; + /** * get service record by element name. * @@ -654,6 +696,9 @@ public: std::list> GetConnectRecordListByCallback(sptr callback); void OnAbilityDied(std::shared_ptr abilityRecord); + void OnCallConnectDied(std::shared_ptr callRecord); + void GetMaxRestartNum(int &max); + bool IsUseNewMission(); /** * wait for starting system ui. @@ -669,14 +714,26 @@ public: void RestartAbility(const sptr &token); void NotifyBmsAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime); + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid); - int StartAbility(const Want &want, const sptr &callerToken, int requestCode, int callerUid = -1); + int StartAbilityInner( + const Want &want, + const sptr &callerToken, + int requestCode, + int callerUid = DEFAULT_INVAL_VALUE, + int32_t userId = DEFAULT_INVAL_VALUE); int CheckPermission(const std::string &bundleName, const std::string &permission); void UpdateLockScreenState(bool isLockScreen); - std::shared_ptr GetConfiguration(); + + void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag); + void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want); + + virtual int GetAbilityRunningInfos(std::vector &info) override; + virtual int GetExtensionRunningInfos(int upperLimit, std::vector &info) override; + virtual int GetProcessRunningInfos(std::vector &info) override; + int GetProcessRunningInfosByUserId(std::vector &info, int32_t userId); int GetMissionSaveTime() const; @@ -685,7 +742,11 @@ public: * */ int GenerateAbilityRequest( - const Want &want, int requestCode, AbilityRequest &request, const sptr &callerToken); + const Want &want, + int requestCode, + AbilityRequest &request, + const sptr &callerToken, + int32_t userId); /** * Get mission id by target ability token. @@ -707,6 +768,69 @@ public: virtual int StopUser(int userId, const sptr &callback) override; + virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) override; + + void ClearUserData(int32_t userId); + + virtual int RegisterSnapshotHandler(const sptr& handler) override; + + virtual int32_t GetMissionSnapshot(const std::string& deviceId, int32_t missionId, + MissionSnapshot& snapshot) override; + + /** + * Set ability controller. + * + * @param abilityController, The ability controller. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetAbilityController(const sptr &abilityController, bool imAStabilityTest) override; + + /** + * Is user a stability test. + * + * @return Returns true if user is a stability test. + */ + virtual bool IsRunningInStabilityTest() override; + + virtual int StartUserTest(const Want &want, const sptr &observer) override; + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override; + + /** + * GetCurrentTopAbility, get the token of current top ability. + * + * @param token, the token of current top ability. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetCurrentTopAbility(sptr &token) override; + + /** + * The delegator calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DelegatorDoAbilityForeground(const sptr &token) override; + + /** + * The delegator calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DelegatorDoAbilityBackground(const sptr &token) override; + + bool IsAbilityControllerStart(const Want &want, const std::string &bundleName); + + bool IsAbilityControllerForeground(const std::string &bundleName); + + /** + * Send not response process ID to ability manager service. + * @param pid The not response process ID. + */ + virtual bool SendANRProcessID(int pid) override; + // MSG 0 - 20 represents timeout message static constexpr uint32_t LOAD_TIMEOUT_MSG = 0; static constexpr uint32_t ACTIVE_TIMEOUT_MSG = 1; @@ -750,7 +874,17 @@ public: KEY_DUMP_MISSION_INFOS, }; + enum DumpsysKey { + KEY_DUMPSYS_ALL = 0, + KEY_DUMPSYS_MISSION_LIST, + KEY_DUMPSYS_ABILITY, + KEY_DUMPSYS_SERVICE, + KEY_DUMPSYS_PENDING, + KEY_DUMPSYS_PROCESS, + }; + friend class AbilityStackManager; + friend class UserController; protected: void OnAbilityRequestDone(const sptr &token, const int32_t state) override; @@ -824,15 +958,18 @@ private: */ void GetGlobalConfiguration(); - sptr GetDmsProxy(); sptr GetBundleManager(); int StartRemoteAbility(const Want &want, int requestCode); int ConnectLocalAbility( - const Want &want, const sptr &connect, const sptr &callerToken); + const Want &want, + const int32_t userId, + const sptr &connect, + const sptr &callerToken); int DisconnectLocalAbility(const sptr &connect); int ConnectRemoteAbility(const Want &want, const sptr &connect); int DisconnectRemoteAbility(const sptr &connect); - int PreLoadAppDataAbilities(const std::string &bundleName); + int PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId); + void UpdateCallerInfo(Want& want); bool CheckIfOperateRemote(const Want &want); bool GetLocalDeviceId(std::string& localDeviceId); @@ -845,7 +982,8 @@ private: std::vector &missionInfos); int GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo); - int CallMissionListener(const std::string &deviceId, const sptr &listener); + int32_t GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, + MissionSnapshot& missionSnapshot); void DumpInner(const std::string &args, std::vector &info); void DumpStackListInner(const std::string &args, std::vector &info); @@ -863,9 +1001,82 @@ private: void DumpFuncInit(); bool CheckCallerIsSystemAppByIpc(); bool IsExistFile(const std::string &path); + + int CheckCallPermissions(const AbilityRequest &abilityRequest); + + + int GenerateAbilityRequestLocal( + const Want &want, + int requestCode, + AbilityRequest &request, + const sptr &callerToken, + int32_t &userId); + + int CheckMultiOsAccount(const int32_t userId); + /** + * dumpsys info + * + */ + void DumpSysFuncInit(); + void DumpSysInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + void DumpSysMissionListInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + void DumpSysAbilityInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + void DumpSysStateInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + void DumpSysPendingInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + void DumpSysProcess( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + + void InitConnectManager(int32_t userId, bool switchUser); + void InitDataAbilityManager(int32_t userId, bool switchUser); + void InitPendWantManager(int32_t userId, bool switchUser); + + int32_t GetAbilityInfoFromExtension(const Want &want, AppExecFwk::AbilityInfo& abilityInfo); + int32_t InitAbilityInfoFromExtension(AppExecFwk::ExtensionAbilityInfo &extensionInfo, + AppExecFwk::AbilityInfo &abilityInfo); + int32_t ShowPickerDialog(const Want& want, int32_t userId); + + // multi user + void StartFreezingScreen(); + void StopFreezingScreen(); + void UserStarted(int32_t userId); + void SwitchToUser(int32_t userId); + void StartLauncherAbility(int32_t userId); + void SwitchToUser(int32_t oldUserId, int32_t userId); + void SwitchManagers(int32_t userId); + void StartUserApps(int32_t userId); + void StartSystemAbilityByUser(int32_t userId); + void PauseOldUser(int32_t userId); + void PauseOldStackManager(int32_t userId); + void PauseOldMissionListManager(int32_t userId); + bool IsSystemUI(const std::string &bundleName) const; + + bool VerificationAllToken(const sptr &token); + bool CheckDataAbilityRequest(AbilityRequest &abilityRequest); + std::shared_ptr GetStackManagerByUserId(int32_t userId); + std::shared_ptr GetListManagerByUserId(int32_t userId); + std::shared_ptr GetConnectManagerByUserId(int32_t userId); + std::shared_ptr GetDataAbilityManagerByUserId(int32_t userId); + std::shared_ptr GetStackManagerByToken(const sptr &token); + std::shared_ptr GetListManagerByToken(const sptr &token); + std::shared_ptr GetConnectManagerByToken(const sptr &token); + std::shared_ptr GetDataAbilityManagerByToken(const sptr &token); + + int32_t GetValidUserId(const Want &want, const int32_t userId); + + int DelegatorMoveMissionToFront(int32_t missionId); + using DumpFuncType = void (AbilityManagerService::*)(const std::string &args, std::vector &info); std::map dumpFuncMap_; + using DumpSysFuncType = void (AbilityManagerService::*)( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID); + std::map dumpsysFuncMap_; + constexpr static int REPOLL_TIME_MICRO_SECONDS = 1000000; constexpr static int WAITING_BOOT_ANIMATION_TIMER = 5; @@ -874,22 +1085,29 @@ private: ServiceRunningState state_; std::unordered_map> stackManagers_; std::shared_ptr currentStackManager_; + std::unordered_map> connectManagers_; std::shared_ptr connectManager_; sptr iBundleManager_; std::shared_ptr appScheduler_; + std::unordered_map> dataAbilityManagers_; std::shared_ptr dataAbilityManager_; + std::shared_ptr systemDataAbilityManager_; + std::unordered_map> pendingWantManagers_; std::shared_ptr pendingWantManager_; std::shared_ptr systemAppManager_; std::shared_ptr amsConfigResolver_; - std::shared_ptr configuration_; - std::shared_ptr callListenerHandler_ = nullptr; const static std::map dumpMap; + const static std::map dumpsysMap; // new ams here bool useNewMission_ {false}; std::unordered_map> missionListManagers_; std::shared_ptr currentMissionListManager_; std::shared_ptr kernalAbilityManager_; + std::shared_ptr userController_; + sptr abilityController_ = nullptr; + bool controllerIsAStabilityTest_ = false; + std::recursive_mutex globalLock_; }; } // namespace AAFwk diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h old mode 100755 new mode 100644 index 3609c0e65b2b05162e7a6853b3c9f2d4dd35c996..ee41214b1539c09fd7673d8dfc00633e0c2a3960 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -39,6 +39,7 @@ public: private: void FirstStepInit(); void SecondStepInit(); + void ThirdStepInit(); int TerminateAbilityInner(MessageParcel &data, MessageParcel &reply); int TerminateAbilityByCallerInner(MessageParcel &data, MessageParcel &reply); int MinimizeAbilityInner(MessageParcel &data, MessageParcel &reply); @@ -66,6 +67,7 @@ private: int DisconnectAbilityInner(MessageParcel &data, MessageParcel &reply); int StopServiceAbilityInner(MessageParcel &data, MessageParcel &reply); int DumpStateInner(MessageParcel &data, MessageParcel &reply); + int DumpSysStateInner(MessageParcel &data, MessageParcel &reply); int StartAbilityForSettingsInner(MessageParcel &data, MessageParcel &reply); int StartAbilityForOptionsInner(MessageParcel &data, MessageParcel &reply); int MoveMissionToFloatingStackInner(MessageParcel &data, MessageParcel &reply); @@ -123,11 +125,32 @@ private: int CleanMissionInner(MessageParcel &data, MessageParcel &reply); int CleanAllMissionsInner(MessageParcel &data, MessageParcel &reply); int MoveMissionToFrontInner(MessageParcel &data, MessageParcel &reply); + + // for new version ability (call ability) + int StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply); + int ReleaseInner(MessageParcel &data, MessageParcel &reply); int StartUserInner(MessageParcel &data, MessageParcel &reply); int StopUserInner(MessageParcel &data, MessageParcel &reply); + int SetMissionLabelInner(MessageParcel &data, MessageParcel &reply); + int GetAbilityRunningInfosInner(MessageParcel &data, MessageParcel &reply); + int GetExtensionRunningInfosInner(MessageParcel &data, MessageParcel &reply); + int GetProcessRunningInfosInner(MessageParcel &data, MessageParcel &reply); int StartSyncRemoteMissionsInner(MessageParcel &data, MessageParcel &reply); int StopSyncRemoteMissionsInner(MessageParcel &data, MessageParcel &reply); + int RegisterSnapshotHandlerInner(MessageParcel &data, MessageParcel &reply); + int GetMissionSnapshotInfoInner(MessageParcel &data, MessageParcel &reply); + int SendANRProcessIDInner(MessageParcel &data, MessageParcel &reply); + + int SetAbilityControllerInner(MessageParcel &data, MessageParcel &reply); + + int StartUserTestInner(MessageParcel &data, MessageParcel &reply); + int FinishUserTestInner(MessageParcel &data, MessageParcel &reply); + int GetCurrentTopAbilityInner(MessageParcel &data, MessageParcel &reply); + int DelegatorDoAbilityForegroundInner(MessageParcel &data, MessageParcel &reply); + int DelegatorDoAbilityBackgroundInner(MessageParcel &data, MessageParcel &reply); + + int IsRunningInStabilityTestInner(MessageParcel &data, MessageParcel &reply); using RequestFuncType = int (AbilityManagerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index 985923f979409c61f2751fee3826ca19d5d142ac..f885b143ed440ea43d85778d65a710916f35eb3c 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -22,6 +22,7 @@ #include #include +#include "ability_connect_callback_interface.h" #include "ability_info.h" #include "ability_start_setting.h" #include "ability_token_stub.h" @@ -29,11 +30,12 @@ #include "app_scheduler.h" #include "application_info.h" #include "ability_record_info.h" -#include "configuration_holder.h" +#include "call_container.h" #include "lifecycle_deal.h" #include "lifecycle_state_info.h" #include "want.h" #include "window_info.h" +#include "uri.h" namespace OHOS { namespace AAFwk { @@ -44,6 +46,7 @@ class MissionRecord; class ConnectionRecord; class Mission; class MissionList; +class CallContainer; const std::string ABILITY_TOKEN_NAME = "AbilityToken"; const std::string LINE_SEPARATOR = "\n"; @@ -113,15 +116,27 @@ private: * @class AbilityRequest * Wrap parameters of starting ability. */ +enum AbilityCallType { + INVALID_TYPE = 0, + CALL_REQUEST_TYPE, +}; struct AbilityRequest { Want want; AppExecFwk::AbilityInfo abilityInfo; AppExecFwk::ApplicationInfo appInfo; + int32_t uid = 0; int requestCode = -1; bool restart = false; - sptr callerToken; + + // call ability + int callerUid = -1; + AbilityCallType callType = AbilityCallType::INVALID_TYPE; + sptr callerToken = nullptr; + sptr connect = nullptr; + std::shared_ptr startSetting = nullptr; int32_t compatibleVersion = 0; + std::string specifiedFlag; bool IsNewVersion() const { @@ -137,6 +152,11 @@ struct AbilityRequest { return false; } + bool IsCallType(const AbilityCallType & type) const + { + return (callType == type); + } + void Dump(std::vector &state) { std::string dumpInfo = " want [" + want.ToUri() + "]"; @@ -150,11 +170,17 @@ struct AbilityRequest { } }; +// new version +enum ResolveResultType { + OK_NO_REMOTE_OBJ = 0, + OK_HAS_REMOTE_OBJ, + NG_INNER_ERROR, +}; /** * @class AbilityRecord * AbilityRecord records ability info and states and used to schedule ability life. */ -class AbilityRecord : public ConfigurationHolder, public std::enable_shared_from_this { +class AbilityRecord : public std::enable_shared_from_this { public: AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo, int requestCode = -1, int32_t apiVersion = 1); @@ -265,6 +291,8 @@ public: */ AbilityState GetAbilityState() const; + bool IsForeground() const; + /** * set ability scheduler for accessing ability thread. * @@ -638,6 +666,12 @@ public: */ void Dump(std::vector &info); + /** + * dump ability state info. + * + */ + void DumpAbilityState(std::vector &info, bool isClient); + void SetStartTime(); int64_t GetStartTime() const; @@ -646,7 +680,7 @@ public: * dump service info. * */ - void DumpService(std::vector &info) const; + void DumpService(std::vector &info, bool isClient = false) const; /** * get ability record info. @@ -730,39 +764,58 @@ public: std::shared_ptr GetMission() const; int32_t GetMissionId() const; - void UpdateConfiguration(const AppExecFwk::Configuration &config) override; + void SetUid(int32_t uid); + int32_t GetUid(); + void SetSwitchingPause(bool state); + bool IsSwitchingPause(); + + // new version + ResolveResultType Resolve(const AbilityRequest &abilityRequest); + bool Release(const sptr & connect); + bool IsNeedToCallRequest() const; + bool IsStartedByCall() const; + void SetStartedByCall(const bool isFlag); + bool CallRequest(); + bool IsStartToBackground() const; + void SetStartToBackground(const bool flag); + + void SetSpecifiedFlag(const std::string &flag); + std::string GetSpecifiedFlag() const; + +protected: + void SendEvent(uint32_t msg, uint32_t timeOut); - int GetId() override; + sptr token_ = {}; // used to interact with kit and wms + std::unique_ptr lifecycleDeal_ = {}; // life manager used to schedule life + AbilityState currentState_ = AbilityState::INITIAL; // current life state + Want want_ = {}; // want to start this ability + LifeCycleStateInfo lifeCycleStateInfo_; // target life state info + static int64_t g_abilityRecordEventId_; + int64_t eventId_ = 0; // post event id +private: /** * get the type of ability. * */ void GetAbilityTypeString(std::string &typeStr); void OnSchedulerDied(const wptr &remote); - void SendEvent(uint32_t msg, uint32_t timeOut); static int64_t abilityRecordId; int recordId_ = 0; // record id - Want want_ = {}; // want to start this ability AppExecFwk::AbilityInfo abilityInfo_ = {}; // the ability info get from BMS AppExecFwk::ApplicationInfo applicationInfo_ = {}; // the ability info get from BMS - sptr token_ = {}; // used to interact with kit and wms std::weak_ptr missionRecord_ = {}; // mission of this ability std::weak_ptr preAbilityRecord_ = {}; // who starts this ability record std::weak_ptr nextAbilityRecord_ = {}; // ability that started by this ability std::weak_ptr backAbilityRecord_ = {}; // who back to this ability record - std::unique_ptr lifecycleDeal_ = {}; // life manager used to schedule life int64_t startTime_ = 0; // records first time of ability start bool isReady_ = false; // is ability thread attached? bool isWindowAttached_ = false; // Is window of this ability attached? bool isLauncherAbility_ = false; // is launcher? - int64_t eventId_ = 0; // post event id - static int64_t g_abilityRecordEventId_; + sptr scheduler_ = {}; // kit scheduler bool isTerminating_ = false; // is terminating ? - LifeCycleStateInfo lifeCycleStateInfo_; // target life state info - AbilityState currentState_ = AbilityState::INITIAL; // current life state std::shared_ptr windowInfo_; // add window info bool isCreateByConnect_ = false; // is created by connect ability mode? bool isToEnd_ = false; // is to end ? @@ -806,9 +859,20 @@ public: AppState appState_ = AppState::BEGIN; int32_t compatibleVersion_ = 0; // > 7 new version, <= 7 old version. + int32_t uid_ = 0; std::weak_ptr missionList_; std::weak_ptr mission_; int32_t missionId_ = -1; + bool isSwitchingPause_ = false; + + // new version + std::shared_ptr callContainer_ = nullptr; + bool isStartedByCall_ = false; + bool isStartToBackground_ = false; + + int32_t restartCount_ = -1; + int32_t restratMax_ = -1; + std::string specifiedFlag_; }; class AbilityRecordNew : public AbilityRecord { diff --git a/services/abilitymgr/include/ability_scheduler_proxy.h b/services/abilitymgr/include/ability_scheduler_proxy.h index ff961fb7429411aa4bc34ed63ae54a9ee40b3479..7b505783d67ffed965163aa966fca4e500350af7 100644 --- a/services/abilitymgr/include/ability_scheduler_proxy.h +++ b/services/abilitymgr/include/ability_scheduler_proxy.h @@ -299,6 +299,15 @@ public: */ void NotifyContinuationResult(const int32_t result) override; + /** + * Dump Ability Runner info. + * + * @param + * @return Ability Runner info. + */ + void DumpAbilityInfo(std::vector &info) override; + sptr CallRequest() override; + private: bool WriteInterfaceToken(MessageParcel &data); diff --git a/services/abilitymgr/include/ability_scheduler_stub.h b/services/abilitymgr/include/ability_scheduler_stub.h index ea8c9eb581ea3225e897ddbe5edc7805b90d0b50..ea3dc636cb0079f58bbf7de139f95445b9c27c0b 100644 --- a/services/abilitymgr/include/ability_scheduler_stub.h +++ b/services/abilitymgr/include/ability_scheduler_stub.h @@ -64,6 +64,9 @@ private: int MutiWinModeChangedInner(MessageParcel &data, MessageParcel &reply); int TopActiveAbilityChangedInner(MessageParcel &data, MessageParcel &reply); int NotifyContinuationResultInner(MessageParcel &data, MessageParcel &reply); + int DumpAbilityInfoInner(MessageParcel& data, MessageParcel& reply); + int CallRequestInner(MessageParcel &data, MessageParcel &reply); + int ContinueAbilityInner(MessageParcel &data, MessageParcel &reply); using RequestFuncType = int (AbilitySchedulerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; diff --git a/services/abilitymgr/include/ability_stack_manager.h b/services/abilitymgr/include/ability_stack_manager.h index 3e4ef96cc0018a2d7e2a5ea4d192eb6029e69e9f..32553b3b2ef299b49a8e7fe78ed1fc149a84ca6d 100644 --- a/services/abilitymgr/include/ability_stack_manager.h +++ b/services/abilitymgr/include/ability_stack_manager.h @@ -437,6 +437,10 @@ public: int SetShowOnLockScreen(const std::string &bundleName, bool isAllow); void UpdateLockScreenState(bool isLockScreen); + + bool IsStarted(); + void PauseManager(); + void ResumeManager(); private: /** * dispatch ability life cycle . diff --git a/services/abilitymgr/include/ability_util.h b/services/abilitymgr/include/ability_util.h old mode 100644 new mode 100755 index 2c2e5b1f253f35e60100aac8ac21c7c627a9633e..3b6ab7c4066706a85e3acb0a714d644b06a06b58 --- a/services/abilitymgr/include/ability_util.h +++ b/services/abilitymgr/include/ability_util.h @@ -22,7 +22,7 @@ #include "ipc_skeleton.h" #include "sa_mgr_client.h" #include "bundlemgr/bundle_mgr_interface.h" -#include "utils/system/safwk/native/include/system_ability_definition.h" +#include "system_ability_definition.h" #include "ability_manager_errors.h" namespace OHOS { diff --git a/services/abilitymgr/include/ams_configuration_parameter.h b/services/abilitymgr/include/ams_configuration_parameter.h index c04fee90ebbb295db8efda331e9f290f4e435ba2..c2226e0748c06ab421d7cda2a137413f0f801fd3 100644 --- a/services/abilitymgr/include/ams_configuration_parameter.h +++ b/services/abilitymgr/include/ams_configuration_parameter.h @@ -33,11 +33,14 @@ const std::string STARTUP_STATUS_BAR {"startup_system_ui_status_bar"}; const std::string STARTUP_NAVIGATION_BAR {"startup_system_ui_navigation_bar"}; const std::string STARTUP_PHONE_SERVICE {"startup_phone_service"}; const std::string MISSION_SAVE_TIME {"mission_save_time"}; +const std::string APP_NOT_RESPONSE_PROCESS_TIMEOUT_TIME {"app_not_response_process_timeout_time"}; +const std::string AMS_TIMEOUT_TIME {"ams_timeout_time"}; const std::string SYSTEM_CONFIGURATION {"system_configuration"}; const std::string SYSTEM_ORIENTATION {"system_orientation"}; const std::string STARTUP_CONTACTS {"startup_contacts"}; const std::string STARTUP_MMS {"startup_mms"}; const std::string USE_NEW_MISSION {"use_new_mission"}; +const std::string ROOT_LAUNCHER_RESTART_MAX {"root_launcher_restart_max"}; } // namespace AmsConfig enum class SatrtUiMode { STATUSBAR = 1, NAVIGATIONBAR = 2, STARTUIBOTH = 3 }; @@ -108,6 +111,18 @@ public: * return true if use mission list, false if use mission stack. */ bool IsUseNewMission() const; + /** + * Get the max number of restart. + */ + int GetMaxRestartNum() const; + /** + * get the application not response process timeout time. + */ + int GetANRTimeOutTime() const; + /** + * get ability manager service not response process timeout time. + */ + int GetAMSTimeOutTime() const; enum { READ_OK = 0, READ_FAIL = 1, READ_JSON_FAIL = 2 }; @@ -131,8 +146,11 @@ private: bool canStartContacts {false}; bool canStartMms {false}; bool useNewMission_ {false}; + int maxRestartNum_ = 0; std::string orientation_ {""}; int missionSaveTime_ {12 * 60 * 60 * 1000}; + int anrTime_ {5000}; + int amsTime_ {5000}; std::map memThreshold_; }; } // namespace AAFwk diff --git a/services/abilitymgr/include/app_scheduler.h b/services/abilitymgr/include/app_scheduler.h index 10cdd498cfa94c2ffef38410a59a319c77b9492b..1a4382adbc0b412bdf4f5a16b000bbce8bc2ac7b 100644 --- a/services/abilitymgr/include/app_scheduler.h +++ b/services/abilitymgr/include/app_scheduler.h @@ -23,13 +23,19 @@ // #include "app_process_data.h" #include "appmgr/app_mgr_client.h" #include "appmgr/app_state_callback_host.h" +#include "appmgr/start_specified_ability_response_stub.h" #include "application_info.h" +#include "bundle_info.h" #include "iremote_object.h" #include "refbase.h" #include "singleton.h" #include "system_memory_attr.h" +#include "running_process_info.h" namespace OHOS { +namespace AppExecFwk { +class Configuration; +} namespace AAFwk { /** * @enum AppAbilityState @@ -52,10 +58,14 @@ enum class AppState { END, }; -struct AppInfo { +struct AppData { std::string appName; - std::string processName; int32_t uid; +}; + +struct AppInfo { + std::vector appData; + std::string processName; AppState state; }; /** @@ -74,6 +84,15 @@ public: virtual void OnAppStateChanged(const AppInfo &info) = 0; }; +class StartSpecifiedAbilityResponse : public AppExecFwk::StartSpecifiedAbilityResponseStub { +public: + StartSpecifiedAbilityResponse() = default; + virtual ~StartSpecifiedAbilityResponse() = default; + + virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) override; + virtual void OnTimeoutResponse(const AAFwk::Want &want) override; +}; + /** * @class AppScheduler * AppScheduler , access app manager service. @@ -161,6 +180,14 @@ public: */ void KillProcessByAbilityToken(const sptr &token); + /** + * KillProcessesByUserId, call KillProcessesByUserId() through proxy object, + * kill the process by user id. + * + * @param userId, the user id. + */ + void KillProcessesByUserId(int32_t userId); + /** * convert ability state to app ability state. * @@ -211,11 +238,33 @@ public: */ void GetSystemMemoryAttr(AppExecFwk::SystemMemoryAttr &memoryInfo, std::string &strConfig); + void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info); /** * Start a resident process */ void StartupResidentProcess(); + void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + int GetProcessRunningInfos(std::vector &info); + + /** + * Start a user test + */ + int StartUserTest(const Want &want, const sptr &observer, const AppExecFwk::BundleInfo &bundleInfo); + + int GetProcessRunningInfosByUserId(std::vector &info, int32_t userId); + std::string ConvertAppState(const AppState &state); + + /** + * ANotify application update system environment changes. + * + * @param config System environment change parameters. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateConfiguration(const AppExecFwk::Configuration &config); + + int GetConfiguration(AppExecFwk::Configuration &config); + protected: /** * OnAbilityRequestDone, app manager service call this interface after ability request done. @@ -233,9 +282,12 @@ protected: virtual void OnAppStateChanged(const AppExecFwk::AppProcessData &appData) override; private: + std::recursive_mutex lock_; + bool isInit_ {false}; std::weak_ptr callback_; std::unique_ptr appMgrClient_; AppAbilityState appAbilityState_ = AppAbilityState::ABILITY_STATE_UNDEFINED; + sptr startSpecifiedAbilityResponse_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/call_container.h b/services/abilitymgr/include/call_container.h new file mode 100644 index 0000000000000000000000000000000000000000..725d6552e09341054de5101ab9904d0bf54090c8 --- /dev/null +++ b/services/abilitymgr/include/call_container.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_CALL_CONTAINER_H +#define OHOS_AAFWK_CALL_CONTAINER_H + +#include +#include +#include + +#include "ability_connect_callback_interface.h" +#include "call_record.h" +#include "element_name.h" +#include "iremote_object.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AAFwk { +class CallRecord; +/** + * @class CallContainer + * CallContainer provides a facility for managing the call records of ability. + */ +class CallContainer : public std::enable_shared_from_this { +public: + using CallMapType = std::map, std::shared_ptr>; + using RecipientMapType = std::map, sptr>; + + CallContainer(); + virtual ~CallContainer(); + + void AddCallRecord(const sptr & connect, const std::shared_ptr& callRecord); + std::shared_ptr GetCallRecord(const sptr & connect) const; + bool RemoveCallRecord(const sptr & connect); + bool CallRequestDone(const sptr & callStub); + void Dump(std::vector &info, const std::string &args = "") const; + bool IsNeedToCallRequest() const; + +private: + void RemoveConnectDeathRecipient(const sptr &connect); + void AddConnectDeathRecipient(const sptr &connect); + void OnConnectionDied(const wptr & remote); + +private: + CallMapType callRecordMap_; + RecipientMapType deathRecipientMap_; + + DISALLOW_COPY_AND_MOVE(CallContainer); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_CALL_CONTAINER_H + diff --git a/services/abilitymgr/include/call_record.h b/services/abilitymgr/include/call_record.h new file mode 100644 index 0000000000000000000000000000000000000000..080d3e9b48dc410cba6c24f06be451a60f4778de --- /dev/null +++ b/services/abilitymgr/include/call_record.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_CALL_RECORD_H +#define OHOS_AAFWK_CALL_RECORD_H + +#include "ability_connect_callback_interface.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AAFwk { +class AbilityRecord; +/** + * @class AbilityCallRecipient + * AbilityCallRecipient notices IRemoteBroker died. + */ +class AbilityCallRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + + AbilityCallRecipient(RemoteDiedHandler handler) : handler_(handler) {}; + virtual ~AbilityCallRecipient() = default; + + void OnRemoteDied(const wptr &__attribute__((unused)) remote) override + { + if (handler_) { + handler_(remote); + } + }; + +private: + RemoteDiedHandler handler_; +}; + +/** + * @enum CallState + * CallState defines the state of calling ability. + */ +enum class CallState { INIT, REQUESTING, REQUESTED }; +/** + * @class CallRecord + * CallRecord,This class is used to record information about a connection of calling ability. + */ +class CallRecord : public std::enable_shared_from_this { +public: + CallRecord(const int32_t callerUid, const std::shared_ptr &targetService, + const sptr &connCallback, const sptr &callToken); + virtual ~CallRecord(); + + static std::shared_ptr CreateCallRecord(const int32_t callerUid, + const std::shared_ptr &targetService, const sptr &connCallback, + const sptr &callToken); + + void SetCallStub(const sptr & call); + sptr GetCallStub(); + void SetConCallBack(const sptr &connCallback); + sptr GetConCallBack() const; + + void Dump(std::vector &info) const; + bool SchedulerConnectDone(); + bool SchedulerDisConnectDone(); + void OnCallStubDied(const wptr & remote); + + int32_t GetCallerUid() const; + bool IsCallState(const CallState& state) const; + void SetCallState(const CallState& state); + int32_t GetCallRecordId() const; + AppExecFwk::ElementName GetTargetServiceName() const; + sptr GetCallerToken() const; + +private: + static int64_t callRecordId; + int recordId_; // record id + int32_t callerUid_; // caller uid + CallState state_; // call state + sptr callRemoteObject_ = nullptr; + sptr callDeathRecipient_ = nullptr; + std::weak_ptr service_; // target:service need to be called + sptr connCallback_ = nullptr; // service connect callback + sptr callerToken_ = nullptr; // caller token + int64_t startTime_ = 0; // records first time of ability start + + DISALLOW_COPY_AND_MOVE(CallRecord); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_CALL_RECORD_H \ No newline at end of file diff --git a/services/abilitymgr/include/connection_record.h b/services/abilitymgr/include/connection_record.h old mode 100644 new mode 100755 index 78894354ecc4ec53be7b2b107dbfdd0519984c83..0dbc77a3eff2639b467fa509ff6b417670bf8b93 --- a/services/abilitymgr/include/connection_record.h +++ b/services/abilitymgr/include/connection_record.h @@ -101,7 +101,7 @@ public: * complete disconnect ability and invoke callback. * */ - void CompleteDisconnect(int resultCode); + void CompleteDisconnect(int resultCode, bool isDied); /** * scheduler target service disconnect done. diff --git a/services/abilitymgr/include/data_ability_manager.h b/services/abilitymgr/include/data_ability_manager.h index b3286f03df1bbe77a3c2d2062f0955aaee4e3010..13b5a91517eeeac46a211aa551501b9ec304fcc2 100644 --- a/services/abilitymgr/include/data_ability_manager.h +++ b/services/abilitymgr/include/data_ability_manager.h @@ -22,6 +22,7 @@ #include #include "ability_record.h" +#include "ability_running_info.h" #include "data_ability_record.h" #include "nocopyable.h" @@ -46,6 +47,7 @@ public: std::shared_ptr GetAbilityRecordByScheduler(const sptr &scheduler); void Dump(const char *func, int line); void DumpState(std::vector &info, const std::string &args = "") const; + void GetAbilityRunningInfos(std::vector &info); private: using DataAbilityRecordPtr = std::shared_ptr; diff --git a/services/abilitymgr/include/kernal_ability_manager.h b/services/abilitymgr/include/kernal_ability_manager.h index 45cae4e58a4a225812dd9c3d8c0a020ed7dff4a0..dd1ec48af3479ab646a32644bba386d48f7674fb 100644 --- a/services/abilitymgr/include/kernal_ability_manager.h +++ b/services/abilitymgr/include/kernal_ability_manager.h @@ -20,6 +20,7 @@ #include #include "ability_record.h" +#include "ability_running_info.h" #include "want.h" namespace OHOS { @@ -91,6 +92,8 @@ public: void RestartAbility(const std::shared_ptr abilityRecord); + void GetAbilityRunningInfos(std::vector &info); + private: /** * StartAbilityLocked. diff --git a/services/abilitymgr/include/mission_data_storage.h b/services/abilitymgr/include/mission_data_storage.h index ebced052d7beb228fa431da3941aa581c2d06fbf..5b7098c9b5e11807eac0e18e2506dc8021c3798d 100644 --- a/services/abilitymgr/include/mission_data_storage.h +++ b/services/abilitymgr/include/mission_data_storage.h @@ -22,6 +22,7 @@ #include "event_handler.h" #include "inner_mission_info.h" +#include "mission_snapshot.h" namespace OHOS { namespace AAFwk { @@ -29,6 +30,7 @@ const std::string TASK_DATA_FILE_BASE_PATH = "/data/service/el1/public/AbilityMa const std::string MISSION_DATA_FILE_PATH = "MissionInfo"; const std::string MISSION_JSON_FILE_PREFIX = "mission"; const std::string JSON_FILE_SUFFIX = ".json"; +const std::string PNG_FILE_SUFFIX = ".png"; class MissionDataStorage : public std::enable_shared_from_this { public: @@ -56,13 +58,38 @@ public: */ void DeleteMissionInfo(int missionId); + /** + * @brief Save mission snapshot + * @param missionId Indicates this mission id. + * @param missionSnapshot the mission snapshot to save + */ + void SaveMissionSnapshot(int missionId, const MissionSnapshot& missionSnapshot); + + /** + * @brief Delete mission snapshot + * @param missionId Indicates this mission id. + */ + void DeleteMissionSnapshot(int32_t missionId); + + /** + * @brief Get the Mission Snapshot object + * @param missionId + * @param missionSnapshot + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetMissionSnapshot(int missionId, MissionSnapshot& missionSnapshot); + private: std::string GetMissionDataDirPath(); std::string GetMissionDataFilePath(int missionId); + std::string GetMissionSnapshotPath(int missionId); + bool CheckFileNameValid(const std::string &fileName); + bool WriteToPng(const char* fileName, uint32_t width, uint32_t height, const uint8_t* data); + private: int userId_ = 0; std::shared_ptr handler_; diff --git a/services/abilitymgr/include/mission_info_mgr.h b/services/abilitymgr/include/mission_info_mgr.h index b41b2af41170c2e6f42b3816c42eeb2165d9110b..f3757a4e4622659ad75aa189e92960b150ecafab 100644 --- a/services/abilitymgr/include/mission_info_mgr.h +++ b/services/abilitymgr/include/mission_info_mgr.h @@ -22,6 +22,8 @@ #include "inner_mission_info.h" #include "mission_listener_controller.h" +#include "mission_snapshot.h" +#include "snapshot.h" #include "task_data_persistence_mgr.h" namespace OHOS { @@ -114,12 +116,47 @@ public: */ bool DeleteAllMissionInfos(const std::shared_ptr &listenerController); + /** + * @brief Update mission label. + * + * @param missionId indicates this mission id. + * @param label indicates this mission label. + * @return 0 if success. + */ + int UpdateMissionLabel(int32_t missionId, const std::string& label); + /** * @brief dump mission info * * @param info dump result. */ void Dump(std::vector &info); + + /** + * @brief update mission snapshot + * @param missionId mission id + * @param abilityToken abilityToken to get current mission snapshot + * @param missionSnapshot result of snapshot + * @return return true if update mission snapshot success, else false + */ + bool UpdateMissionSnapshot(int32_t missionId, const sptr& abilityToken, + MissionSnapshot& missionSnapshot) const; + + /** + * @brief get the mission snapshot object + * @param missionId mission id + * @param abilityToken abilityToken to get current mission snapshot + * @param missionSnapshot result of snapshot + * @return true return true if get mission snapshot success, else false + */ + bool GetMissionSnapshot(int32_t missionId, const sptr& abilityToken, + MissionSnapshot& missionSnapshot) const; + + /** + * @brief register snapshotHandler + * @param handler the snapshotHandler + */ + void RegisterSnapshotHandler(const sptr& handler); private: /** * @brief Boot query mission info. @@ -131,6 +168,7 @@ private: std::unordered_map missionIdMap_; // key:distributed misisonid, vaule: has been saved std::list missionInfoList_; std::shared_ptr taskDataPersistenceMgr_; + sptr snapshotHandler_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/mission_list.h b/services/abilitymgr/include/mission_list.h index fe2008febc1cdd5d6c219df175f9891f8a708f9b..ca093f4dca82080e320e19ea6fc125777d6e788b 100644 --- a/services/abilitymgr/include/mission_list.h +++ b/services/abilitymgr/include/mission_list.h @@ -111,7 +111,7 @@ public: * @param missionId the given missionId * @return the mission of the given id */ - std::list> GetAllMissions() const; + std::list>& GetAllMissions(); /** * @brief Get the type of the missionList @@ -145,6 +145,14 @@ public: std::shared_ptr GetAbilityRecordByCaller( const std::shared_ptr &caller, int requestCode); + /** + * @brief Get the Ability Record By elementName + * + * @param element + * @return std::shared_ptr the ability record which find + */ + std::shared_ptr GetAbilityRecordByName(const AppExecFwk::ElementName &element); + /** * Get ability token by target mission id. * @@ -165,12 +173,15 @@ public: * * @param info dump result. */ - void DumpList(std::vector &info); + void DumpList(std::vector &info, bool isClient); + void DumpStateByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId); + + std::shared_ptr GetMissionBySpecifiedFlag(const std::string &flag) const; private: std::string GetTypeName(); MissionListType type_; - std::list> missions_; + std::list> missions_ {}; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index fe7b0590606ce2f3328f5ca148f4125ab6f4ac79..a1d351aeeca864fc0bd37013e75ea3fb4ccbfc28 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -20,9 +20,13 @@ #include #include +#include "ability_running_info.h" +#include "foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/device_manager.h" #include "mission_list.h" #include "mission_listener_controller.h" #include "mission_info.h" +#include "mission_snapshot.h" +#include "snapshot.h" #include "want.h" namespace OHOS { @@ -176,6 +180,9 @@ public: */ int ClearAllMissions(); + void ClearAllMissionsLocked(std::list> &missionList, + std::list> &foregroundAbilities, bool searchActive); + /** * @brief Set the Mission Locked State object * @@ -204,7 +211,14 @@ public: * * @param abilityRecord the died ability */ - void OnAbilityDied(std::shared_ptr abilityRecord); + void OnAbilityDied(std::shared_ptr abilityRecord, int32_t currentUserId); + + /** + * @brief handle when call contection died + * + * @param callRecord the died call contection + */ + void OnCallConnectDied(const std::shared_ptr &callRecord); /** * Get mission id by target ability token. @@ -222,19 +236,30 @@ public: */ sptr GetAbilityTokenByMissionId(int32_t missionId); + /** + * Set mission label of this ability. + * + * @param abilityToken target ability token. + * @param label target label. + * @return Retun 0 if success. + */ + int SetMissionLabel(const sptr &abilityToken, const std::string &label); + /** * @brief dump all abilities * * @param info dump result. */ - void Dump(std::vector &info); + void Dump(std::vector& info); /** * @brief dump mission list * * @param info dump result. */ - void DumpMissionList(std::vector &info); + void DumpMissionList(std::vector &info, bool isClient, const std::string &args = ""); + + void DumpMissionListByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId); /** * @brief dump mission by id @@ -249,9 +274,57 @@ public: * @param info dump result. */ void DumpMissionInfos(std::vector &info); + + void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag); + + /** + * resolve the call ipc of ability for schudeling oncall. + * + * @param abilityRequest, target ability request. + */ + int ResolveLocked(const AbilityRequest &abilityRequest); + + /** + * release the connection of this call. + * + * @param connect, caller callback ipc. + * @param element, target ability name. + */ + int ReleaseLocked(const sptr &connect, const AppExecFwk::ElementName &element); + + /** + * @brief register snapshotHandler + * @param handler the snapshotHandler + */ + void RegisterSnapshotHandler(const sptr& handler); + + /** + * @brief Get the Mission Snapshot object + * @param missionId mission id + * @param abilityToken abilityToken to get current mission snapshot + * @param missionSnapshot result of snapshot + * @return Returns true on success, false on failure. + */ + bool GetMissionSnapshot(int32_t missionId, const sptr& abilityToken, + MissionSnapshot& missionSnapshot); + void GetAbilityRunningInfos(std::vector &info); + + /** + * @brief get current top ability by bundle name + * @param bundleName the bundle name + * @return the current top ability. + */ + std::shared_ptr GetCurrentTopAbility(const std::string &bundleName); + + bool IsStarted(); + void PauseManager(); + void ResumeManager(); private: int StartAbilityLocked(const std::shared_ptr ¤tTopAbility, const std::shared_ptr &callerAbility, const AbilityRequest &abilityRequest); + int StartAbility(const std::shared_ptr ¤tTopAbility, + const std::shared_ptr &callerAbility, const AbilityRequest &abilityRequest); + int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher); int MinimizeAbilityLocked(const std::shared_ptr &abilityRecord); std::shared_ptr GetCurrentTopAbilityLocked() const; std::shared_ptr GetTargetMissionList( @@ -291,6 +364,19 @@ private: void HandleAbilityDiedByDefault(std::shared_ptr abilityRecord); void DelayedStartLauncher(); void BackToLauncher(); + void GetAllForegroundAbilities(std::list>& foregroundList); + void GetForegroundAbilities(const std::shared_ptr& missionList, + std::list>& foregroundList); + bool IsPC(); + std::shared_ptr GetMissionBySpecifiedFlag(const std::string &flag) const; + + void HandleLoadTimeout(const std::shared_ptr &ability); + void HandleForgroundNewTimeout(const std::shared_ptr &ability); + + // new version for call inner function. + int ResolveAbility(const std::shared_ptr &targetAbility, const AbilityRequest &abilityRequest); + std::shared_ptr GetAbilityRecordByName(const AppExecFwk::ElementName &element); + int CallAbilityLocked(const AbilityRequest &abilityRequest); private: int userId_; @@ -306,6 +392,16 @@ private: std::queue waittingAbilityQueue_; std::shared_ptr listenerController_; + bool isPC_ = false; + +private: +class MissionDmInitCallback : public DistributedHardware::DmInitCallback { +public: + void OnRemoteDied() override; + +public: + static bool isInit_; +}; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/pending_want_manager.h b/services/abilitymgr/include/pending_want_manager.h index 8a21726b4b2ac3d2cdd8a2bf6702e6c54b7fb62d..b12cbef86a8f58bac17a474cd9f3d0940c6794de 100644 --- a/services/abilitymgr/include/pending_want_manager.h +++ b/services/abilitymgr/include/pending_want_manager.h @@ -150,12 +150,16 @@ public: void CancelWantSenderLocked(PendingWantRecord &record, bool cleanAbility); int32_t PendingWantStartAbility( - const Want &want, const sptr &callerToken, int32_t requestCode, int32_t callerUid); + const Want &want, const sptr &callerToken, int32_t requestCode, const int32_t callerUid); int32_t PendingWantStartAbilitys(const std::vector wnatsInfo, const sptr &callerToken, - int32_t requestCode, int32_t callerUid); + int32_t requestCode, const int32_t callerUid); + int32_t DeviceIdDetermine( + const Want &want, const sptr &callerToken, int32_t requestCode, const int32_t callerUid); int32_t PendingWantPublishCommonEvent(const Want &want, const SenderInfo &senderInfo, int32_t callerUid); void ClearPendingWantRecord(const std::string &bundleName); + void Dump(std::vector &info); + private: sptr GetWantSenderLocked(const int32_t callingUid, const int32_t uid, const int32_t userId, WantSenderInfo &wantSenderInfo, const sptr &callerToken); diff --git a/services/abilitymgr/include/screenshot_response.h b/services/abilitymgr/include/screenshot_response.h index 4b4d8c78dec6c850685006bbfb155665aaaf02f5..31994844bbb119a6d7f72526f6be468d2974d13f 100644 --- a/services/abilitymgr/include/screenshot_response.h +++ b/services/abilitymgr/include/screenshot_response.h @@ -20,8 +20,8 @@ #include #include #include -#include "nocopyable.h" #include +#include "nocopyable.h" #include "../wmclient/wm_common.h" namespace OHOS { diff --git a/services/abilitymgr/include/task_data_persistence_mgr.h b/services/abilitymgr/include/task_data_persistence_mgr.h index 9316c412cf725f15fd227941c63479ae7bedbe1b..4bc56c2bd45fac0e7b18e6c8be708038759f21ea 100644 --- a/services/abilitymgr/include/task_data_persistence_mgr.h +++ b/services/abilitymgr/include/task_data_persistence_mgr.h @@ -28,6 +28,8 @@ namespace AAFwk { const std::string THREAD_NAME = "TaskDataStorage"; const std::string SAVE_MISSION_INFO = "SaveMissionInfo"; const std::string DELETE_MISSION_INFO = "DeleteMissionInfo"; +const std::string SAVE_MISSION_SNAPSHOT = "SaveMissionSnapshot"; +const std::string GET_MISSION_SNAPSHOT = "GetMissionSnapshot"; class TaskDataPersistenceMgr : public std::enable_shared_from_this { DECLARE_DELAYED_SINGLETON(TaskDataPersistenceMgr) @@ -59,11 +61,35 @@ public: */ bool DeleteMissionInfo(int missionId); + /** + * @brief Remove user directory. + * @param userId Indicates this user id. + * @return Returns true if the directory is successfully removed; returns false otherwise. + */ + bool RemoveUserDir(int32_t userId); + + /** + * @brief save mission snapshot + * @param missionId id of mission + * @param snapshot result of snapshot + * @return return true if update mission snapshot success, else false + */ + bool SaveMissionSnapshot(int missionId, const MissionSnapshot& snapshot); + + /** + * @brief Get the mission snapshot object + * @param missionId id of mission + * @param missionSnapshot + * @return return true if update mission snapshot success, else false + */ + bool GetMissionSnapshot(int missionId, MissionSnapshot& missionSnapshot); + private: std::unordered_map> missionDataStorageMgr_; std::shared_ptr currentMissionDataStorage_; std::shared_ptr eventLoop_; std::shared_ptr handler_; + int32_t currentUserId_ = -1; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/user_controller.h b/services/abilitymgr/include/user_controller.h new file mode 100644 index 0000000000000000000000000000000000000000..fa08f4771853657426d5402da3fc2276fca62dfb --- /dev/null +++ b/services/abilitymgr/include/user_controller.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_USER_CONTROLLER_H +#define OHOS_AAFWK_USER_CONTROLLER_H + +#include +#include +#include + +#include "user_event_handler.h" + +namespace OHOS { +namespace AAFwk { +const int32_t USER_ID_NO_HEAD = 0; +const int32_t USER_ID_DEFAULT = 100; + +enum UserState { + STATE_BOOTING = 0, + STATE_STARTED, + STATE_STOPPING, + STATE_SHUTDOWN +}; + +class UserItem { +public: + explicit UserItem(int32_t id); + virtual ~UserItem(); + + int32_t GetUserId(); + void SetState(const UserState &state); + UserState GetState(); + +private: + int32_t userId_; + UserState curState_ = STATE_BOOTING; + UserState lastState_ = STATE_BOOTING; +}; + +struct UserEvent { + int32_t oldUserId; + int32_t newUserId; + std::shared_ptr userItem; +}; + +class UserController : public std::enable_shared_from_this { +public: + UserController(); + virtual ~UserController(); + + void Init(); + + /** + * Start user, if it is not running.. + * + * @param userId id of started user. + * @param isForeground whether user should brout to foreground. + * @return 0 if the user has been successfully started. + */ + int32_t StartUser(int32_t userId, bool isForeground); + + /** + * Stop user, if it is running.. + * + * @param userId id of started user. + * @return 0 if the user has been successfully started. + */ + int32_t StopUser(int32_t userId); + + int32_t GetCurrentUserId(); + + std::shared_ptr GetUserItem(int32_t userId); + + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event); + +private: + bool IsCurrentUser(int32_t userId); + bool IsExistOsAccount(int32_t userId); + std::shared_ptr GetOrCreateUserItem(int32_t userId); + void SetCurrentUserId(int32_t userId); + void BroadcastUserStarted(int32_t userId); + void MoveUserToForeground(int32_t oldUserId, int32_t newUserId); + void UserBootDone(std::shared_ptr &item); + void BroadcastUserBackground(int32_t userId); + void BroadcastUserForeground(int32_t userId); + void BroadcastUserStopping(int32_t userId); + void BroadcastUserStopped(int32_t userId); + + void SendSystemUserStart(int32_t userId); + void SendSystemUserCurrent(int32_t oldUserId, int32_t newUserId); + void SendReportUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem); + void SendUserSwitchTimeout(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem); + void SendContinueUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem); + void SendUserSwitchDone(int32_t userId); + + void HandleSystemUserStart(int32_t userId); + void HandleSystemUserCurrent(int32_t oldUserId, int32_t newUserId); + void HandleReportUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem); + void HandleUserSwitchTimeout(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem); + void HandleContinueUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem); + void HandleUserSwitchDone(int32_t userId); + +private: + std::recursive_mutex userLock_; + int32_t currentUserId_ = USER_ID_DEFAULT; + std::unordered_map> userItems_; + std::shared_ptr eventHandler_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_USER_CONTROLLER_H \ No newline at end of file diff --git a/services/abilitymgr/include/user_event_handler.h b/services/abilitymgr/include/user_event_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..ad22a2dcc5d291ef0feec741c50bc0c4955f6cb9 --- /dev/null +++ b/services/abilitymgr/include/user_event_handler.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_USER_EVENT_HANDLER_H +#define OHOS_AAFWK_USER_EVENT_HANDLER_H + +#include + +#include "event_handler.h" +#include "event_runner.h" + +namespace OHOS { +namespace AAFwk { +class UserController; +class UserEventHandler : public AppExecFwk::EventHandler { +public: + UserEventHandler( + const std::shared_ptr &runner, const std::weak_ptr &owner); + virtual ~UserEventHandler() = default; + + static constexpr uint32_t EVENT_SYSTEM_USER_START = 10; + static constexpr uint32_t EVENT_SYSTEM_USER_CURRENT = 20; + static constexpr uint32_t EVENT_REPORT_USER_SWITCH = 30; + static constexpr uint32_t EVENT_CONTINUE_USER_SWITCH = 40; + static constexpr uint32_t EVENT_USER_SWITCH_TIMEOUT = 50; + static constexpr uint32_t EVENT_REPORT_USER_SWITCH_DONE = 60; + + /** + * ProcessEvent with request. + * + * @param event, inner event loop. + */ + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; + +private: + std::weak_ptr controller_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_USER_EVENT_HANDLER_H \ No newline at end of file diff --git a/services/abilitymgr/resource/ams_service_config.json b/services/abilitymgr/resource/ams_service_config.json index 392255de15f3b97df40d1f5b7f66823849069ec3..a557159ea950b684fbd1ab70d82f786b7ecfdc7a 100644 --- a/services/abilitymgr/resource/ams_service_config.json +++ b/services/abilitymgr/resource/ams_service_config.json @@ -7,7 +7,11 @@ "startup_phone_service" : true, "startup_contacts":true, "startup_mms":true, - "mission_save_time" : 43200000 + "mission_save_time" : 43200000, + "root_launcher_restart_max":15, + "use_new_mission":true, + "app_not_response_process_timeout_time" : 5000, + "ams_timeout_time" : 5000 }, "memorythreshold":{ "home_application": "20" diff --git a/services/abilitymgr/src/ability_connect_callback_stub.cpp b/services/abilitymgr/src/ability_connect_callback_stub.cpp index 6eac9cd34885f046c5d3ab435612cbc57e7129dc..df6f851bec165cd5a783de8cbf4f656fc18322a0 100644 --- a/services/abilitymgr/src/ability_connect_callback_stub.cpp +++ b/services/abilitymgr/src/ability_connect_callback_stub.cpp @@ -98,6 +98,7 @@ AbilityConnectionStub::~AbilityConnectionStub() int AbilityConnectionStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + HILOG_DEBUG("AbilityConnectionStub::OnRemoteRequest OnAbilityConnectDone called."); std::u16string descriptor = AbilityConnectionStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/services/abilitymgr/src/ability_connect_manager.cpp b/services/abilitymgr/src/ability_connect_manager.cpp old mode 100644 new mode 100755 index 29356963aa464e6f8415238346f5f3c81ef18843..c07fb13c8d325905698d0d81076f9879bc0478fc --- a/services/abilitymgr/src/ability_connect_manager.cpp +++ b/services/abilitymgr/src/ability_connect_manager.cpp @@ -375,10 +375,16 @@ void AbilityConnectManager::OnAppStateChanged(const AppInfo &info) { std::lock_guard guard(Lock_); std::for_each(serviceMap_.begin(), serviceMap_.end(), [&info](ServiceMapType::reference service) { - if (service.second && service.second->GetApplicationInfo().name == info.appName && - (info.processName == service.second->GetAbilityInfo().process || - info.processName == service.second->GetApplicationInfo().bundleName)) { - service.second->SetAppState(info.state); + if (service.second && (info.processName == service.second->GetAbilityInfo().process || + info.processName == service.second->GetApplicationInfo().bundleName)) { + auto appName = service.second->GetApplicationInfo().name; + auto uid = service.second->GetAbilityInfo().applicationInfo.uid; + auto isExist = [&appName, &uid]( + const AppData &appData) { return appData.appName == appName && appData.uid == uid; }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + if (iter != info.appData.end()) { + service.second->SetAppState(info.state); + } } }); } @@ -397,13 +403,13 @@ int AbilityConnectManager::AbilityTransitionDone(const sptr &toke switch (state) { case AbilityState::INACTIVE: { - DelayedSingleton::GetInstance()->UpdateExtensionState(token, - AppExecFwk::ExtensionState::EXTENSION_STATE_CREATE); + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_CREATE); return DispatchInactive(abilityRecord, state); } case AbilityState::INITIAL: { - DelayedSingleton::GetInstance()->UpdateExtensionState(token, - AppExecFwk::ExtensionState::EXTENSION_STATE_TERMINATED); + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_TERMINATED); return DispatchTerminate(abilityRecord); } default: { @@ -432,8 +438,8 @@ int AbilityConnectManager::ScheduleConnectAbilityDoneLocked( return INVALID_CONNECTION_STATE; } - DelayedSingleton::GetInstance()->UpdateExtensionState(token, - AppExecFwk::ExtensionState::EXTENSION_STATE_CONNECTED); + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_CONNECTED); abilityRecord->SetConnRemoteObject(remoteObject); // There may be multiple callers waiting for the connection result @@ -460,8 +466,8 @@ int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptr::GetInstance()->UpdateExtensionState(token, - AppExecFwk::ExtensionState::EXTENSION_STATE_DISCONNECTED); + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_DISCONNECTED); std::string element = abilityRecord->GetWant().GetElement().GetURI(); HILOG_INFO("disconnect ability done with service %{public}s", element.c_str()); @@ -660,7 +666,7 @@ void AbilityConnectManager::HandleDisconnectTask(const ConnectListType &connectl if (targetService && connectRecord->GetConnectState() == ConnectionState::DISCONNECTED && targetService->GetConnectRecordList().size() > 1) { HILOG_WARN("This record complete disconnect directly. recordId:%{public}d", connectRecord->GetRecordId()); - connectRecord->CompleteDisconnect(ERR_OK); + connectRecord->CompleteDisconnect(ERR_OK, false); targetService->RemoveConnectRecordFromList(connectRecord); RemoveConnectionRecordFromMap(connectRecord); }; @@ -907,7 +913,7 @@ void AbilityConnectManager::HandleAbilityDiedTask(const std::shared_ptrGetConnectRecordList(); for (auto &connectRecord : connlist) { HILOG_WARN("This record complete disconnect directly. recordId:%{public}d", connectRecord->GetRecordId()); - connectRecord->CompleteDisconnect(ERR_OK); + connectRecord->CompleteDisconnect(ERR_OK, true); abilityRecord->RemoveConnectRecordFromList(connectRecord); RemoveConnectionRecordFromMap(connectRecord); } @@ -915,7 +921,7 @@ void AbilityConnectManager::HandleAbilityDiedTask(const std::shared_ptr &info, const std::string &args) const +void AbilityConnectManager::DumpState(std::vector &info, bool isClient, const std::string &args) const { if (!args.empty()) { auto it = std::find_if(serviceMap_.begin(), serviceMap_.end(), [&args](const auto &service) { @@ -923,17 +929,99 @@ void AbilityConnectManager::DumpState(std::vector &info, const std: }); if (it != serviceMap_.end()) { info.emplace_back("uri [ " + it->first + " ]"); - it->second->DumpService(info); + it->second->DumpService(info, isClient); } else { info.emplace_back(args + ": Nothing to dump."); } } else { - info.emplace_back("serviceAbilityRecords:"); + auto abilityMgr = DelayedSingleton::GetInstance(); + if (abilityMgr && abilityMgr->IsUseNewMission()) { + info.emplace_back(" ExtensionRecords:"); + } else { + info.emplace_back(" serviceAbilityRecords:"); + } for (auto &&service : serviceMap_) { - info.emplace_back(" uri [" + service.first + "]"); - service.second->DumpService(info); + info.emplace_back(" uri [" + service.first + "]"); + service.second->DumpService(info, isClient); } } } + +void AbilityConnectManager::GetExtensionRunningInfos(int upperLimit, std::vector &info, + const int32_t userId) +{ + HILOG_INFO("Get extension running info."); + std::lock_guard guard(Lock_); + auto queryInfo = [&info, upperLimit, userId](ServiceMapType::reference service) { + if (static_cast(info.size()) >= upperLimit) { + return; + } + auto abilityRecord = service.second; + CHECK_POINTER(abilityRecord); + ExtensionRunningInfo extensionInfo; + AppExecFwk::RunningProcessInfo processInfo; + extensionInfo.extension = abilityRecord->GetWant().GetElement(); + auto bms = AbilityUtil::GetBundleManager(); + CHECK_POINTER(bms); + std::vector extensionInfos; + bool queryResult = bms->QueryExtensionAbilityInfos(abilityRecord->GetWant(), + AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, userId, extensionInfos); + if (queryResult) { + HILOG_INFO("Query Extension Ability Infos Success."); + auto abilityInfo = abilityRecord->GetAbilityInfo(); + auto isExist = [&abilityInfo](const AppExecFwk::ExtensionAbilityInfo &extensionInfo) { + HILOG_INFO("%{public}s, %{public}s", extensionInfo.bundleName.c_str(), extensionInfo.name.c_str()); + return extensionInfo.bundleName == abilityInfo.bundleName && extensionInfo.name == abilityInfo.name + && extensionInfo.applicationInfo.uid == abilityInfo.applicationInfo.uid; + }; + auto infoIter = std::find_if(extensionInfos.begin(), extensionInfos.end(), isExist); + if (infoIter != extensionInfos.end()) { + HILOG_INFO("Get target success."); + extensionInfo.type = (*infoIter).type; + } + } + DelayedSingleton::GetInstance()-> + GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo); + extensionInfo.pid = processInfo.pid_; + extensionInfo.uid = processInfo.uid_; + extensionInfo.processName = processInfo.processName_; + extensionInfo.startTime = abilityRecord->GetStartTime(); + ConnectListType connectRecordList = abilityRecord->GetConnectRecordList(); + for (auto &connectRecord : connectRecordList) { + CHECK_POINTER(connectRecord); + auto callerAbilityRecord = Token::GetAbilityRecordByToken(connectRecord->GetToken()); + CHECK_POINTER(callerAbilityRecord); + std::string package = callerAbilityRecord->GetAbilityInfo().bundleName; + extensionInfo.clientPackage.emplace_back(package); + } + info.emplace_back(extensionInfo); + // extension type + }; + std::for_each(serviceMap_.begin(), serviceMap_.end(), queryInfo); +} + +void AbilityConnectManager::GetAbilityRunningInfos(std::vector &info) +{ + HILOG_INFO("Query running ability infos."); + std::lock_guard guard(Lock_); + + auto queryInfo = [&info](ServiceMapType::reference service) { + auto abilityRecord = service.second; + CHECK_POINTER(abilityRecord); + AbilityRunningInfo runningInfo; + AppExecFwk::RunningProcessInfo processInfo; + runningInfo.ability = abilityRecord->GetWant().GetElement(); + DelayedSingleton::GetInstance()-> + GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo); + runningInfo.pid = processInfo.pid_; + runningInfo.uid = processInfo.uid_; + runningInfo.processName = processInfo.processName_; + runningInfo.startTime = abilityRecord->GetStartTime(); + runningInfo.abilityState = static_cast(abilityRecord->GetAbilityState()); + info.emplace_back(runningInfo); + }; + + std::for_each(serviceMap_.begin(), serviceMap_.end(), queryInfo); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index 8c336f67077ae0a39f8f55b7db44da05f84fdb0a..96c02789a0b44b0a631a3e39da0df2a769b2d623 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -107,34 +107,41 @@ void AbilityManagerClient::AddWindowInfo(const sptr &token, int32 abms->AddWindowInfo(token, windowToken); } -ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode) +ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode, int32_t userId) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); - return abms->StartAbility(want, requestCode); + return abms->StartAbility(want, userId, requestCode); } -ErrCode AbilityManagerClient::StartAbility(const Want &want, const sptr &callerToken, int requestCode) +ErrCode AbilityManagerClient::StartAbility( + const Want &want, const sptr &callerToken, int requestCode, int32_t userId) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + HILOG_INFO("%{public}s called, bundleName=%{public}s, abilityName=%{public}s, userId=%{public}d", + __func__, want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId); sptr abms = iface_cast(remoteObject_); - return abms->StartAbility(want, callerToken, requestCode); + return abms->StartAbility(want, callerToken, userId, requestCode); } ErrCode AbilityManagerClient::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode) + const sptr &callerToken, int requestCode, int32_t userId) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); - return abms->StartAbility(want, abilityStartSetting, callerToken, requestCode); + return abms->StartAbility(want, abilityStartSetting, callerToken, userId, requestCode); } ErrCode AbilityManagerClient::StartAbility(const Want &want, const StartOptions &startOptions, - const sptr &callerToken, int requestCode) + const sptr &callerToken, int requestCode, int32_t userId) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + HILOG_INFO("%{public}s called, bundleName=%{public}s, abilityName=%{public}s", + __func__, want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str()); + HILOG_INFO("%{public}s called, userId=%{public}d, windowMode_=%{public}d, displayId_=%{public}d", + __func__, userId, startOptions.GetWindowMode(), startOptions.GetDisplayID()); sptr abms = iface_cast(remoteObject_); - return abms->StartAbility(want, startOptions, callerToken, requestCode); + return abms->StartAbility(want, startOptions, callerToken, userId, requestCode); } ErrCode AbilityManagerClient::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) @@ -166,11 +173,13 @@ ErrCode AbilityManagerClient::MinimizeAbility(const sptr &token) } ErrCode AbilityManagerClient::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + HILOG_INFO("%{public}s called, bundleName=%{public}s, abilityName=%{public}s, userId=%{public}d", + __func__, want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId); sptr abms = iface_cast(remoteObject_); - return abms->ConnectAbility(want, connect, callerToken); + return abms->ConnectAbility(want, connect, callerToken, userId); } ErrCode AbilityManagerClient::DisconnectAbility(const sptr &connect) @@ -204,6 +213,15 @@ ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector& state, bool isClient, bool isUserID, int UserID) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + abms->DumpSysState(args, state, isClient, isUserID, UserID); + return ERR_OK; +} + ErrCode AbilityManagerClient::Connect() { std::lock_guard lock(mutex_); @@ -753,6 +771,44 @@ ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId) return abms->MoveMissionToFront(missionId); } +ErrCode AbilityManagerClient::StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callToken) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + HILOG_DEBUG("AbilityManagerClient::StartAbilityByCall called."); + return abms->StartAbilityByCall(want, connect, callToken); +} + +ErrCode AbilityManagerClient::ReleaseAbility( + const sptr &connect, const AppExecFwk::ElementName &element) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->ReleaseAbility(connect, element); +} + +ErrCode AbilityManagerClient::GetAbilityRunningInfos(std::vector &info) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->GetAbilityRunningInfos(info); +} + +ErrCode AbilityManagerClient::GetExtensionRunningInfos(int upperLimit, std::vector &info) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->GetExtensionRunningInfos(upperLimit, info); +} + +ErrCode AbilityManagerClient::GetProcessRunningInfos(std::vector &info) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->GetProcessRunningInfos(info); +} + /** * Start synchronizing remote device mission * @param devId, deviceId. @@ -760,39 +816,96 @@ ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId) * @param tag, call tag. * @return Returns ERR_OK on success, others on failure. */ -ErrCode AbilityManagerClient::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) +ErrCode AbilityManagerClient::StartSyncRemoteMissions(const std::string &devId, bool fixConflict, int64_t tag) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); auto abms = iface_cast(remoteObject_); return abms->StartSyncRemoteMissions(devId, fixConflict, tag); } - /** * Stop synchronizing remote device mission * @param devId, deviceId. * @return Returns ERR_OK on success, others on failure. */ -ErrCode AbilityManagerClient::StopSyncRemoteMissions(const std::string& devId) +ErrCode AbilityManagerClient::StopSyncRemoteMissions(const std::string &devId) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); auto abms = iface_cast(remoteObject_); return abms->StopSyncRemoteMissions(devId); } - ErrCode AbilityManagerClient::StartUser(int accountId) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); - sptr abms = iface_cast(remoteObject_); return abms->StartUser(accountId); } - ErrCode AbilityManagerClient::StopUser(int accountId, const sptr &callback) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); - sptr abms = iface_cast(remoteObject_); return abms->StopUser(accountId, callback); } + +ErrCode AbilityManagerClient::RegisterSnapshotHandler(const sptr& handler) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + auto abms = iface_cast(remoteObject_); + return abms->RegisterSnapshotHandler(handler); +} + +ErrCode AbilityManagerClient::GetMissionSnapshot(const std::string& deviceId, int32_t missionId, + MissionSnapshot& snapshot) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + auto abms = iface_cast(remoteObject_); + return abms->GetMissionSnapshot(deviceId, missionId, snapshot); +} + +ErrCode AbilityManagerClient::StartUserTest(const Want &want, const sptr &observer) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + + sptr abms = iface_cast(remoteObject_); + return abms->StartUserTest(want, observer); +} + +ErrCode AbilityManagerClient::FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + + sptr abms = iface_cast(remoteObject_); + return abms->FinishUserTest(msg, resultCode, bundleName, observer); +} + +ErrCode AbilityManagerClient::GetCurrentTopAbility(sptr &token) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->GetCurrentTopAbility(token); +} + +ErrCode AbilityManagerClient::DelegatorDoAbilityForeground(const sptr &token) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + + sptr abms = iface_cast(remoteObject_); + return abms->DelegatorDoAbilityForeground(token); +} + +ErrCode AbilityManagerClient::DelegatorDoAbilityBackground(const sptr &token) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + + sptr abms = iface_cast(remoteObject_); + return abms->DelegatorDoAbilityBackground(token); +} + +ErrCode AbilityManagerClient::SetMissionLabel(const sptr &token, const std::string& label) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + auto abms = iface_cast(remoteObject_); + return abms->SetMissionLabel(token, label); +} +} // namespace AAFwk } // namespace AAFwk -} // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp old mode 100755 new mode 100644 index 0d8de5e105ba4e84e45187b0a90fb3b8ff63ad3f..11095952104e1426545e4db5c7a559b695fb3183 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -39,7 +39,7 @@ bool AbilityManagerProxy::WriteInterfaceToken(MessageParcel &data) return true; } -int AbilityManagerProxy::StartAbility(const Want &want, int requestCode) +int AbilityManagerProxy::StartAbility(const Want &want, int32_t userId, int requestCode) { int error; MessageParcel data; @@ -53,6 +53,12 @@ int AbilityManagerProxy::StartAbility(const Want &want, int requestCode) HILOG_ERROR("want write failed."); return INNER_ERR; } + + if (!data.WriteInt32(userId)) { + HILOG_ERROR("userId write failed."); + return INNER_ERR; + } + if (!data.WriteInt32(requestCode)) { HILOG_ERROR("requestCode write failed."); return INNER_ERR; @@ -67,7 +73,7 @@ int AbilityManagerProxy::StartAbility(const Want &want, int requestCode) } int AbilityManagerProxy::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode) + const sptr &callerToken, int32_t userId, int requestCode) { int error; MessageParcel data; @@ -88,6 +94,10 @@ int AbilityManagerProxy::StartAbility(const Want &want, const AbilityStartSettin HILOG_ERROR("callerToken write failed."); return INNER_ERR; } + if (!data.WriteInt32(userId)) { + HILOG_ERROR("userId write failed."); + return INNER_ERR; + } if (!data.WriteInt32(requestCode)) { HILOG_ERROR("requestCode write failed."); return INNER_ERR; @@ -100,7 +110,8 @@ int AbilityManagerProxy::StartAbility(const Want &want, const AbilityStartSettin return reply.ReadInt32(); } -int AbilityManagerProxy::StartAbility(const Want &want, const sptr &callerToken, int requestCode) +int AbilityManagerProxy::StartAbility( + const Want &want, const sptr &callerToken, int32_t userId, int requestCode) { int error; MessageParcel data; @@ -118,6 +129,10 @@ int AbilityManagerProxy::StartAbility(const Want &want, const sptr &callerToken, int requestCode) + const sptr &callerToken, int32_t userId, int requestCode) { int error; MessageParcel data; @@ -153,6 +168,10 @@ int AbilityManagerProxy::StartAbility(const Want &want, const StartOptions &star HILOG_ERROR("callerToken write failed."); return INNER_ERR; } + if (!data.WriteInt32(userId)) { + HILOG_ERROR("userId write failed."); + return INNER_ERR; + } if (!data.WriteInt32(requestCode)) { HILOG_ERROR("requestCode write failed."); return INNER_ERR; @@ -210,7 +229,7 @@ int AbilityManagerProxy::TerminateAbilityByCaller(const sptr &cal } int AbilityManagerProxy::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { int error; MessageParcel data; @@ -236,7 +255,10 @@ int AbilityManagerProxy::ConnectAbility( HILOG_ERROR("callerToken write failed."); return ERR_INVALID_VALUE; } - + if (!data.WriteInt32(userId)) { + HILOG_ERROR("userId write failed."); + return INNER_ERR; + } error = Remote()->SendRequest(IAbilityManager::CONNECT_ABILITY, data, reply, option); if (error != NO_ERROR) { HILOG_ERROR("Send request error: %{public}d", error); @@ -360,11 +382,11 @@ int AbilityManagerProxy::AbilityTransitionDone(const sptr &token, return INNER_ERR; } if (!data.WriteParcelable(token) || !data.WriteInt32(state)) { - HILOG_ERROR("data write failed."); + HILOG_ERROR("token or state write failed."); return INNER_ERR; } if (!data.WriteParcelable(&saveData)) { - HILOG_ERROR("data write failed."); + HILOG_ERROR("saveData write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::ABILITY_TRANSITION_DONE, data, reply, option); @@ -469,6 +491,43 @@ void AbilityManagerProxy::AddWindowInfo(const sptr &token, int32_ } } +void AbilityManagerProxy::DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return; + } + data.WriteString16(Str8ToStr16(args)); + + if (!data.WriteBool(isClient)) { + HILOG_ERROR("data write failed."); + return ; + } + if (!data.WriteBool(isUserID)) { + HILOG_ERROR("data write failed."); + return ; + } + if (!data.WriteInt32(UserID)) { + HILOG_ERROR("data write failed."); + return ; + } + error = Remote()->SendRequest(IAbilityManager::DUMPSYS_STATE, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("AbilityManagerProxy: SendRequest err %{public}d", error); + return; + } + int32_t stackNum = reply.ReadInt32(); + for (int i = 0; i < stackNum; i++) { + std::string stac = Str16ToStr8(reply.ReadString16()); + state.emplace_back(stac); + } +} + void AbilityManagerProxy::DumpState(const std::string &args, std::vector &state) { int error; @@ -536,7 +595,7 @@ int AbilityManagerProxy::MinimizeAbility(const sptr &token) return reply.ReadInt32(); } -int AbilityManagerProxy::StopServiceAbility(const Want &want) +int AbilityManagerProxy::StopServiceAbility(const Want &want, int32_t userId) { int error; MessageParcel data; @@ -550,6 +609,10 @@ int AbilityManagerProxy::StopServiceAbility(const Want &want) HILOG_ERROR("want write failed."); return INNER_ERR; } + if (!data.WriteInt32(userId)) { + HILOG_ERROR("userId write failed."); + return INNER_ERR; + } error = Remote()->SendRequest(IAbilityManager::STOP_SERVICE_ABILITY, data, reply, option); if (error != NO_ERROR) { HILOG_ERROR("Send request error: %{public}d", error); @@ -592,7 +655,7 @@ int AbilityManagerProxy::GetAllStackInfo(StackInfo &stackInfo) return result; } -template +template int AbilityManagerProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) { int32_t infoSize = reply.ReadInt32(); @@ -666,6 +729,38 @@ int AbilityManagerProxy::GetMissionSnapshot(const int32_t missionId, MissionPixe return reply.ReadInt32(); } +int AbilityManagerProxy::GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteString(deviceId)) { + HILOG_ERROR("deviceId write failed."); + return INNER_ERR; + } + if (!data.WriteInt32(missionId)) { + HILOG_ERROR("missionId write failed."); + return ERR_INVALID_VALUE; + } + error = Remote()->SendRequest(IAbilityManager::GET_MISSION_SNAPSHOT_INFO, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + HILOG_ERROR("readParcelableInfo failed."); + return ERR_UNKNOWN_OBJECT; + } + snapshot = *info; + return reply.ReadInt32(); +} + int AbilityManagerProxy::MoveMissionToTop(int32_t missionId) { int error; @@ -1951,6 +2046,104 @@ int AbilityManagerProxy::StopUser(int userId, const sptr &cal return reply.ReadInt32(); } +int AbilityManagerProxy::SetMissionLabel(const sptr &token, const std::string &label) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteRemoteObject(token)) { + HILOG_ERROR("SetMissionLabel write token failed."); + return ERR_INVALID_VALUE; + } + if (!data.WriteString16(Str8ToStr16(label))) { + HILOG_ERROR("SetMissionLabel write label failed."); + return ERR_INVALID_VALUE; + } + auto error = Remote()->SendRequest(IAbilityManager::SET_MISSION_LABEL, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("SetMissionLabel Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::GetAbilityRunningInfos(std::vector &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + auto error = Remote()->SendRequest(IAbilityManager::GET_ABILITY_RUNNING_INFO, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Get ability running info, error: %{public}d", error); + return error; + } + error = GetParcelableInfos(reply, info); + if (error != NO_ERROR) { + HILOG_ERROR("GetParcelableInfos fail, error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::GetExtensionRunningInfos(int upperLimit, std::vector &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + if (!data.WriteInt32(upperLimit)) { + HILOG_ERROR("upperLimit write failed."); + return INNER_ERR; + } + + auto error = Remote()->SendRequest(IAbilityManager::GET_EXTENSION_RUNNING_INFO, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Get extension running info failed., error: %{public}d", error); + return error; + } + error = GetParcelableInfos(reply, info); + if (error != NO_ERROR) { + HILOG_ERROR("GetParcelableInfos fail, error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::GetProcessRunningInfos(std::vector &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + auto error = Remote()->SendRequest(IAbilityManager::GET_PROCESS_RUNNING_INFO, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Get process running info, error: %{public}d", error); + return error; + } + error = GetParcelableInfos(reply, info); + if (error != NO_ERROR) { + HILOG_ERROR("GetParcelableInfos fail, error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + int AbilityManagerProxy::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) { HILOG_INFO("called"); @@ -2033,5 +2226,292 @@ int AbilityManagerProxy::UnRegisterMissionListener(const std::string &deviceId, } return reply.ReadInt32(); } + +int AbilityManagerProxy::StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) +{ + HILOG_DEBUG("AbilityManagerProxy::StartAbilityByCall begin."); + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(&want)) { + HILOG_ERROR("want write failed."); + return ERR_INVALID_VALUE; + } + if (connect == nullptr) { + HILOG_ERROR("resolve ability fail, connect is nullptr"); + return ERR_INVALID_VALUE; + } + if (!data.WriteParcelable(connect->AsObject())) { + HILOG_ERROR("resolve write failed."); + return ERR_INVALID_VALUE; + } + if (!data.WriteParcelable(callerToken)) { + HILOG_ERROR("callerToken write failed."); + return INNER_ERR; + } + + HILOG_DEBUG("AbilityManagerProxy::StartAbilityByCall SendRequest Call."); + error = Remote()->SendRequest(IAbilityManager::START_CALL_ABILITY, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + HILOG_DEBUG("AbilityManagerProxy::StartAbilityByCall end."); + return reply.ReadInt32(); +} + +int AbilityManagerProxy::ReleaseAbility(const sptr &connect, const AppExecFwk::ElementName &element) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (connect == nullptr) { + HILOG_ERROR("release calll ability fail, connect is nullptr"); + return ERR_INVALID_VALUE; + } + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(connect->AsObject())) { + HILOG_ERROR("release ability connect write failed."); + return ERR_INVALID_VALUE; + } + if (!data.WriteParcelable(&element)) { + HILOG_ERROR("element error."); + return ERR_INVALID_VALUE; + } + + error = Remote()->SendRequest(IAbilityManager::RELEASE_CALL_ABILITY, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::RegisterSnapshotHandler(const sptr& handler) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteRemoteObject(handler->AsObject())) { + HILOG_ERROR("snapshot: handler write failed."); + return INNER_ERR; + } + auto error = Remote()->SendRequest(IAbilityManager::REGISTER_SNAPSHOT_HANDLER, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("snapshot: send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) +{ + if (!abilityController) { + HILOG_ERROR("abilityController nullptr"); + return ERR_INVALID_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteRemoteObject(abilityController->AsObject())) { + HILOG_ERROR("abilityController write failed."); + return ERR_INVALID_VALUE; + } + if (!data.WriteBool(imAStabilityTest)) { + HILOG_ERROR("imAStabilityTest write failed."); + return ERR_INVALID_VALUE; + } + auto error = Remote()->SendRequest(IAbilityManager::SET_ABILITY_CONTROLLER, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +bool AbilityManagerProxy::IsRunningInStabilityTest() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return false; + } + auto error = Remote()->SendRequest(IAbilityManager::IS_USER_A_STABILITY_TEST, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return false; + } + return reply.ReadBool(); +} + +int AbilityManagerProxy::StartUserTest(const Want &want, const sptr &observer) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(&want)) { + HILOG_ERROR("want write failed."); + return INNER_ERR; + } + if (!data.WriteParcelable(observer)) { + HILOG_ERROR("observer write failed."); + return INNER_ERR; + } + auto error = Remote()->SendRequest(IAbilityManager::START_USER_TEST, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteString(msg)) { + HILOG_ERROR("msg write failed."); + return ERR_INVALID_VALUE; + } + if (!data.WriteInt32(resultCode)) { + HILOG_ERROR("resultCode:WriteInt32 fail."); + return ERR_INVALID_VALUE; + } + if (!data.WriteString(bundleName)) { + HILOG_ERROR("bundleName write failed."); + return ERR_INVALID_VALUE; + } + if (!data.WriteParcelable(observer)) { + HILOG_ERROR("observer write failed."); + return ERR_INVALID_VALUE; + } + auto error = Remote()->SendRequest(IAbilityManager::FINISH_USER_TEST, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::GetCurrentTopAbility(sptr &token) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + auto error = Remote()->SendRequest(IAbilityManager::GET_CURRENT_TOP_ABILITY, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + + token = sptr(reply.ReadParcelable()); + if (!token) { + HILOG_ERROR("read IRemoteObject failed."); + return ERR_UNKNOWN_OBJECT; + } + + return reply.ReadInt32(); +} + +int AbilityManagerProxy::DelegatorDoAbilityForeground(const sptr &token) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + if (!data.WriteParcelable(token)) { + HILOG_ERROR("data write failed."); + return ERR_INVALID_VALUE; + } + + auto error = Remote()->SendRequest(IAbilityManager::DELEGATOR_DO_ABILITY_FOREGROUND, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + + return reply.ReadInt32(); +} + +int AbilityManagerProxy::DelegatorDoAbilityBackground(const sptr &token) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + if (!data.WriteParcelable(token)) { + HILOG_ERROR("data write failed."); + return ERR_INVALID_VALUE; + } + + auto error = Remote()->SendRequest(IAbilityManager::DELEGATOR_DO_ABILITY_BACKGROUND, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + + return reply.ReadInt32(); +} + +bool AbilityManagerProxy::SendANRProcessID(int pid) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return false; + } + if (!data.WriteInt32(pid)) { + HILOG_ERROR("pid WriteInt32 fail."); + return false; + } + error = Remote()->SendRequest(IAbilityManager::SEND_APP_NOT_RESPONSE_PROCESS_ID, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("SendANRProcessID error: %d", error); + return false; + } + return reply.ReadBool(); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp old mode 100644 new mode 100755 index 3fc23ab7ce50183bde2b7f60c854cd450cdfd77b..552d089a9d5cfe9b1b1de3c6dc97a9465b964bee --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -23,36 +23,48 @@ #include #include #include +#include #include "ability_info.h" #include "ability_manager_errors.h" #include "ability_util.h" #include "bytrace.h" -#include "configuration_distributor.h" +#include "bundle_mgr_client.h" +#include "distributed_client.h" #include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" +#include "itest_observer.h" #include "locale_config.h" #include "lock_screen_white_list.h" #include "mission/mission_info_converter.h" +#include "mission_info_mgr.h" #include "sa_mgr_client.h" #include "softbus_bus_center.h" #include "string_ex.h" #include "system_ability_definition.h" +#include "os_account_manager.h" +#include "png.h" +#include "ui_service_mgr_client.h" +#include "xcollie/watchdog.h" using OHOS::AppExecFwk::ElementName; namespace OHOS { namespace AAFwk { using namespace std::chrono; +const int32_t MAIN_USER_ID = 100; +const int32_t U0_USER_ID = 0; static const int EXPERIENCE_MEM_THRESHOLD = 20; constexpr auto DATA_ABILITY_START_TIMEOUT = 5s; constexpr int32_t NON_ANONYMIZE_LENGTH = 6; const int32_t EXTENSION_SUPPORT_API_VERSION = 8; const int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20; +const int32_t MAX_NUMBER_OF_CONNECT_BMS = 15; const std::string EMPTY_DEVICE_ID = ""; const std::string PKG_NAME = "ohos.distributedhardware.devicemanager"; +const std::string ACTION_CHOOSE = "ohos.want.action.select"; const std::map AbilityManagerService::dumpMap = { std::map::value_type("--all", KEY_DUMP_ALL), std::map::value_type("-a", KEY_DUMP_ALL), @@ -81,6 +93,22 @@ const std::map AbilityManagerServic std::map::value_type("--mission-infos", KEY_DUMP_MISSION_INFOS), std::map::value_type("-S", KEY_DUMP_MISSION_INFOS), }; + +const std::map AbilityManagerService::dumpsysMap = { + std::map::value_type("--all", KEY_DUMPSYS_ALL), + std::map::value_type("-a", KEY_DUMPSYS_ALL), + std::map::value_type("--mission-list", KEY_DUMPSYS_MISSION_LIST), + std::map::value_type("-l", KEY_DUMPSYS_MISSION_LIST), + std::map::value_type("--ability", KEY_DUMPSYS_ABILITY), + std::map::value_type("-i", KEY_DUMPSYS_ABILITY), + std::map::value_type("--extension", KEY_DUMPSYS_SERVICE), + std::map::value_type("-e", KEY_DUMPSYS_SERVICE), + std::map::value_type("--pending", KEY_DUMPSYS_PENDING), + std::map::value_type("-p", KEY_DUMPSYS_PENDING), + std::map::value_type("--process", KEY_DUMPSYS_PROCESS), + std::map::value_type("-r", KEY_DUMPSYS_PROCESS), +}; + const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); @@ -89,13 +117,13 @@ AbilityManagerService::AbilityManagerService() eventLoop_(nullptr), handler_(nullptr), state_(ServiceRunningState::STATE_NOT_START), - connectManager_(std::make_shared()), iBundleManager_(nullptr) { std::shared_ptr appScheduler( DelayedSingleton::GetInstance().get(), [](AppScheduler *x) { x->DecStrongRef(x); }); appScheduler_ = appScheduler; DumpFuncInit(); + DumpSysFuncInit(); } AbilityManagerService::~AbilityManagerService() @@ -132,14 +160,16 @@ bool AbilityManagerService::Init() handler_ = std::make_shared(eventLoop_, weak_from_this()); CHECK_POINTER_RETURN_BOOL(handler_); - CHECK_POINTER_RETURN_BOOL(connectManager_); - connectManager_->SetEventHandler(handler_); - // init ConfigurationDistributor - DelayedSingleton::GetInstance(); + // init user controller. + userController_ = std::make_shared(); + userController_->Init(); + int userId = MAIN_USER_ID; - auto dataAbilityManager = std::make_shared(); - CHECK_POINTER_RETURN_BOOL(dataAbilityManager); + InitConnectManager(userId, true); + InitDataAbilityManager(userId, true); + InitPendWantManager(userId, true); + systemDataAbilityManager_ = std::make_shared(); amsConfigResolver_ = std::make_shared(); if (amsConfigResolver_) { @@ -148,25 +178,19 @@ bool AbilityManagerService::Init() } useNewMission_ = amsConfigResolver_->IsUseNewMission(); - auto pendingWantManager = std::make_shared(); - if (!pendingWantManager) { - HILOG_ERROR("Failed to init pending want ability manager."); - return false; - } - - // after amsConfigResolver_ - configuration_ = std::make_shared(); - GetGlobalConfiguration(); - - int userId = GetUserId(); - SetStackManager(userId); - systemAppManager_ = std::make_shared(userId); + SetStackManager(userId, true); + systemAppManager_ = std::make_shared(0); CHECK_POINTER_RETURN_BOOL(systemAppManager_); - InitMissionListManager(userId); - kernalAbilityManager_ = std::make_shared(userId); + InitMissionListManager(userId, true); + kernalAbilityManager_ = std::make_shared(0); CHECK_POINTER_RETURN_BOOL(kernalAbilityManager_); + int amsTimeOut = amsConfigResolver_->GetAMSTimeOutTime(); + if (HiviewDFX::Watchdog::GetInstance().AddThread("AMSWatchdog", handler_, amsTimeOut) != 0) { + HILOG_ERROR("HiviewDFX::Watchdog::GetInstance AddThread Fail"); + } + auto startLauncherAbilityTask = [aams = shared_from_this()]() { aams->StartSystemApplication(); }; handler_->PostTask(startLauncherAbilityTask, "startLauncherAbility"); auto creatWhiteListTask = [aams = shared_from_this()]() { @@ -185,8 +209,6 @@ bool AbilityManagerService::Init() outFile.close(); }; handler_->PostTask(creatWhiteListTask, "creatWhiteList"); - dataAbilityManager_ = dataAbilityManager; - pendingWantManager_ = pendingWantManager; HILOG_INFO("Init success."); return true; } @@ -197,7 +219,6 @@ void AbilityManagerService::OnStop() eventLoop_.reset(); handler_.reset(); state_ = ServiceRunningState::STATE_NOT_START; - DelayedSingleton::DestroyInstance(); } ServiceRunningState AbilityManagerService::QueryServiceState() const @@ -205,13 +226,14 @@ ServiceRunningState AbilityManagerService::QueryServiceState() const return state_; } -int AbilityManagerService::StartAbility(const Want &want, int requestCode) +int AbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode) { HILOG_INFO("%{public}s", __func__); - return StartAbility(want, nullptr, requestCode, -1); + return StartAbilityInner(want, nullptr, requestCode, -1, userId); } -int AbilityManagerService::StartAbility(const Want &want, const sptr &callerToken, int requestCode) +int AbilityManagerService::StartAbility(const Want &want, const sptr &callerToken, + int32_t userId, int requestCode) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto flags = want.GetFlags(); @@ -225,22 +247,29 @@ int AbilityManagerService::StartAbility(const Want &want, const sptr &callerToken, int requestCode, int callerUid) +int AbilityManagerService::StartAbilityInner(const Want &want, const sptr &callerToken, + int requestCode, int callerUid, int32_t userId) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s", __func__); + HILOG_DEBUG("%{public}s begin.", __func__); if (callerToken != nullptr && !VerificationToken(callerToken)) { + HILOG_ERROR("%{public}s VerificationToken failed.", __func__); return ERR_INVALID_VALUE; } + int32_t userIdValid = GetValidUserId(want, userId); + int result = CheckMultiOsAccount(userIdValid); + if (result != ERR_OK) { + HILOG_ERROR("CheckMultiOsAccount error."); + return result; + } AbilityRequest abilityRequest; - int result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken); + result = GenerateAbilityRequestLocal(want, requestCode, abilityRequest, callerToken, userIdValid); if (result != ERR_OK) { - HILOG_ERROR("Generate ability request error."); + HILOG_ERROR("Generate ability request local error."); return result; } auto abilityInfo = abilityRequest.abilityInfo; @@ -250,52 +279,86 @@ int AbilityManagerService::StartAbility( return result; } auto type = abilityInfo.type; + HILOG_DEBUG("%{public}s Current ability type:%{public}d", __func__, type); if (type == AppExecFwk::AbilityType::DATA) { HILOG_ERROR("Cannot start data ability, use 'AcquireDataAbility()' instead."); return ERR_INVALID_VALUE; } - if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) { - result = PreLoadAppDataAbilities(abilityInfo.bundleName); + HILOG_DEBUG("%{public}s PreLoadAppDataAbilities:%{public}s", __func__, abilityInfo.bundleName.c_str()); + result = PreLoadAppDataAbilities(abilityInfo.bundleName, userIdValid); if (result != ERR_OK) { HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d", - abilityInfo.bundleName.c_str(), - result); + abilityInfo.bundleName.c_str(), result); return result; } } - + UpdateCallerInfo(abilityRequest.want); if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) { - return connectManager_->StartAbility(abilityRequest); + auto connectManager = GetConnectManagerByUserId(userIdValid); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userIdValid); + return ERR_INVALID_VALUE; + } + HILOG_DEBUG("%{public}s Start SERVICE or EXTENSION", __func__); + return connectManager->StartAbility(abilityRequest); + } + + if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) { + HILOG_ERROR("IsAbilityControllerStart failed: %{public}s", abilityInfo.bundleName.c_str()); + return ERR_WOULD_BLOCK; } if (useNewMission_) { if (IsSystemUiApp(abilityRequest.abilityInfo)) { + HILOG_DEBUG("%{public}s NewMission Start SystemUiApp", __func__); return kernalAbilityManager_->StartAbility(abilityRequest); } - return currentMissionListManager_->StartAbility(abilityRequest); + + userIdValid = abilityInfo.applicationInfo.singleUser ? DEFAULT_USER_ID : userIdValid; + + auto missionListManager = GetListManagerByUserId(userIdValid); + if (missionListManager == nullptr) { + HILOG_ERROR("missionListManager is nullptr. userId=%{public}d", userIdValid); + return ERR_INVALID_VALUE; + } + HILOG_DEBUG("%{public}s StartAbility by MissionList", __func__); + return missionListManager->StartAbility(abilityRequest); } else { if (IsSystemUiApp(abilityRequest.abilityInfo)) { + HILOG_DEBUG("%{public}s OldMission Start SystemUiApp", __func__); return systemAppManager_->StartAbility(abilityRequest); } - return currentStackManager_->StartAbility(abilityRequest); + auto stackManager = GetStackManagerByUserId(userIdValid); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userIdValid); + return ERR_INVALID_VALUE; + } + HILOG_DEBUG("%{public}s StartAbility by StackManager", __func__); + return stackManager->StartAbility(abilityRequest); } } int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode) + const sptr &callerToken, int32_t userId, int requestCode) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("Start ability setting."); + HILOG_DEBUG("Start ability setting."); if (callerToken != nullptr && !VerificationToken(callerToken)) { return ERR_INVALID_VALUE; } + int32_t userIdValid = GetValidUserId(want, userId); + int result = CheckMultiOsAccount(userIdValid); + if (result != ERR_OK) { + HILOG_ERROR("CheckMultiOsAccount error."); + return result; + } AbilityRequest abilityRequest; - int result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken); + result = GenerateAbilityRequestLocal(want, requestCode, abilityRequest, callerToken, userIdValid); if (result != ERR_OK) { - HILOG_ERROR("Generate ability request error."); + HILOG_ERROR("Generate ability request local error."); return result; } auto abilityInfo = abilityRequest.abilityInfo; @@ -313,7 +376,7 @@ int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSett } if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) { - result = PreLoadAppDataAbilities(abilityInfo.bundleName); + result = PreLoadAppDataAbilities(abilityInfo.bundleName, userIdValid); if (result != ERR_OK) { HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d", abilityInfo.bundleName.c_str(), @@ -326,34 +389,57 @@ int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSett HILOG_ERROR("Only support for page type ability."); return ERR_INVALID_VALUE; } + + if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) { + return ERR_WOULD_BLOCK; + } if (useNewMission_) { if (IsSystemUiApp(abilityRequest.abilityInfo)) { return kernalAbilityManager_->StartAbility(abilityRequest); } - return currentMissionListManager_->StartAbility(abilityRequest); + userIdValid = abilityInfo.applicationInfo.singleUser ? DEFAULT_USER_ID : userIdValid; + + auto missionListManager = GetListManagerByUserId(userIdValid); + if (missionListManager == nullptr) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userIdValid); + return ERR_INVALID_VALUE; + } + return missionListManager->StartAbility(abilityRequest); } else { if (IsSystemUiApp(abilityRequest.abilityInfo)) { return systemAppManager_->StartAbility(abilityRequest); } - return currentStackManager_->StartAbility(abilityRequest); + auto stackManager = GetStackManagerByUserId(userIdValid); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userIdValid); + return ERR_INVALID_VALUE; + } + return stackManager->StartAbility(abilityRequest); } } int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions, - const sptr &callerToken, int requestCode) + const sptr &callerToken, int32_t userId, int requestCode) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("Start ability options."); + HILOG_DEBUG("Start ability options."); if (callerToken != nullptr && !VerificationToken(callerToken)) { return ERR_INVALID_VALUE; } + int32_t userIdValid = GetValidUserId(want, userId); + int result = CheckMultiOsAccount(userIdValid); + if (result != ERR_OK) { + HILOG_ERROR("CheckMultiOsAccount error."); + return result; + } + AbilityRequest abilityRequest; - int result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken); + result = GenerateAbilityRequestLocal(want, requestCode, abilityRequest, callerToken, userIdValid); if (result != ERR_OK) { - HILOG_ERROR("Generate ability request error."); + HILOG_ERROR("Generate ability request local error."); return result; } @@ -370,7 +456,7 @@ int AbilityManagerService::StartAbility(const Want &want, const StartOptions &st } if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) { - result = PreLoadAppDataAbilities(abilityInfo.bundleName); + result = PreLoadAppDataAbilities(abilityInfo.bundleName, userIdValid); if (result != ERR_OK) { HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d", abilityInfo.bundleName.c_str(), @@ -379,6 +465,9 @@ int AbilityManagerService::StartAbility(const Want &want, const StartOptions &st } } + if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) { + return ERR_WOULD_BLOCK; + } if (IsSystemUiApp(abilityRequest.abilityInfo)) { if (useNewMission_) { return kernalAbilityManager_->StartAbility(abilityRequest); @@ -386,20 +475,31 @@ int AbilityManagerService::StartAbility(const Want &want, const StartOptions &st return systemAppManager_->StartAbility(abilityRequest); } } - - abilityRequest.want.SetParam(StartOptions::STRING_WINDOW_MODE, startOptions.GetWindowMode()); - + abilityRequest.want.SetParam(StartOptions::STRING_DISPLAY_ID, startOptions.GetDisplayID()); + abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_MODE, startOptions.GetWindowMode()); if (useNewMission_) { - return currentMissionListManager_->StartAbility(abilityRequest); + userIdValid = abilityInfo.applicationInfo.singleUser ? DEFAULT_USER_ID : userIdValid; + + auto missionListManager = GetListManagerByUserId(userIdValid); + if (missionListManager == nullptr) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userIdValid); + return ERR_INVALID_VALUE; + } + return missionListManager->StartAbility(abilityRequest); } else { - return currentStackManager_->StartAbility(abilityRequest); + auto stackManager = GetStackManagerByUserId(userIdValid); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userIdValid); + return ERR_INVALID_VALUE; + } + return stackManager->StartAbility(abilityRequest); } } int AbilityManagerService::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("Terminate ability for result: %{public}d", (resultWant != nullptr)); + HILOG_DEBUG("Terminate ability for result: %{public}d", (resultWant != nullptr)); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } @@ -417,9 +517,15 @@ int AbilityManagerService::TerminateAbility(const sptr &token, in return ERR_INVALID_VALUE; } + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; auto type = abilityRecord->GetAbilityInfo().type; if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) { - return connectManager_->TerminateAbility(token); + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->TerminateAbility(token); } if (type == AppExecFwk::AbilityType::DATA) { @@ -436,10 +542,24 @@ int AbilityManagerService::TerminateAbility(const sptr &token, in RequestPermission(resultWant); } + if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) { + return ERR_WOULD_BLOCK; + } + if (useNewMission_) { - return currentMissionListManager_->TerminateAbility(abilityRecord, resultCode, resultWant); + auto missionListManager = GetListManagerByUserId(userId); + if (missionListManager == nullptr) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant); } else { - return currentStackManager_->TerminateAbility(token, resultCode, resultWant); + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return stackManager->TerminateAbility(token, resultCode, resultWant); } } @@ -447,14 +567,10 @@ int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode) { HILOG_INFO("%{public}s", __func__); want.DumpInfo(0); - sptr dms = GetDmsProxy(); - if (dms == nullptr) { - HILOG_ERROR("AbilityManagerService::StartAbility failed to get dms."); - return ERR_INVALID_VALUE; - } int32_t callerUid = IPCSkeleton::GetCallingUid(); + DistributedClient dmsClient; HILOG_INFO("AbilityManagerService::Try to StartRemoteAbility, callerUid = %{public}d", callerUid); - int result = dms->StartRemoteAbility(want, callerUid, requestCode); + int result = dmsClient.StartRemoteAbility(want, callerUid, requestCode); if (result != ERR_NONE) { HILOG_ERROR("AbilityManagerService::StartRemoteAbility failed, result = %{public}d", result); } @@ -494,22 +610,6 @@ bool AbilityManagerService::CheckIfOperateRemote(const Want &want) return true; } -sptr AbilityManagerService::GetDmsProxy() -{ - HILOG_INFO("%{public}s begin.", __func__); - auto remoteObject = - OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); - if (remoteObject == nullptr) { - HILOG_ERROR("failed to get dms service"); - return nullptr; - } - HILOG_INFO("get dms proxy success."); - sptr dmsProxy = - iface_cast(remoteObject); - HILOG_INFO("%{public}s end.", __func__); - return dmsProxy; -} - bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId) { auto localNode = std::make_unique(); @@ -568,20 +668,46 @@ int AbilityManagerService::TerminateAbilityByCaller(const sptr &c return ERR_INVALID_VALUE; } + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; auto type = abilityRecord->GetAbilityInfo().type; + auto stackManager = GetStackManagerByUserId(userId); + auto connectManager = GetConnectManagerByUserId(userId); switch (type) { case AppExecFwk::AbilityType::SERVICE: case AppExecFwk::AbilityType::EXTENSION: { - auto result = connectManager_->TerminateAbility(abilityRecord, requestCode); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + auto result = connectManager->TerminateAbility(abilityRecord, requestCode); if (result == NO_FOUND_ABILITY_BY_CALLER) { - return currentStackManager_->TerminateAbility(abilityRecord, requestCode); + if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) { + return ERR_WOULD_BLOCK; + } + + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return stackManager->TerminateAbility(abilityRecord, requestCode); } return result; } case AppExecFwk::AbilityType::PAGE: { - auto result = currentStackManager_->TerminateAbility(abilityRecord, requestCode); + if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) { + return ERR_WOULD_BLOCK; + } + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + auto result = stackManager->TerminateAbility(abilityRecord, requestCode); if (result == NO_FOUND_ABILITY_BY_CALLER) { - return connectManager_->TerminateAbility(abilityRecord, requestCode); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->TerminateAbility(abilityRecord, requestCode); } return result; } @@ -593,7 +719,7 @@ int AbilityManagerService::TerminateAbilityByCaller(const sptr &c int AbilityManagerService::MinimizeAbility(const sptr &token) { HILOG_INFO("Minimize ability."); - if (!VerificationToken(token)) { + if (!VerificationToken(token) && !VerificationAllToken(token)) { return ERR_INVALID_VALUE; } @@ -605,16 +731,31 @@ int AbilityManagerService::MinimizeAbility(const sptr &token) return result; } + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; auto type = abilityRecord->GetAbilityInfo().type; if (type != AppExecFwk::AbilityType::PAGE) { HILOG_ERROR("Cannot minimize except page ability."); return ERR_INVALID_VALUE; } + if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) { + return ERR_WOULD_BLOCK; + } + if (useNewMission_) { - return currentMissionListManager_->MinimizeAbility(token); + auto missionListManager = GetListManagerByUserId(userId); + if (!missionListManager) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return missionListManager->MinimizeAbility(token); } else { - return currentStackManager_->MinimizeAbility(token); + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return stackManager->MinimizeAbility(token); } } @@ -653,7 +794,13 @@ int AbilityManagerService::SetMissionDescriptionInfo( auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); - return currentStackManager_->SetMissionDescriptionInfo(abilityRecord, description); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return stackManager->SetMissionDescriptionInfo(abilityRecord, description); } int AbilityManagerService::GetMissionLockModeState() @@ -666,63 +813,7 @@ int AbilityManagerService::GetMissionLockModeState() int AbilityManagerService::UpdateConfiguration(const AppExecFwk::Configuration &config) { HILOG_INFO("%{public}s called", __func__); - CHECK_POINTER_AND_RETURN(configuration_, ERR_INVALID_VALUE); - - std::vector changeKeyV; - configuration_->CompareDifferent(changeKeyV, config); - int size = changeKeyV.size(); - HILOG_INFO("changeKeyV size :%{public}d", size); - if (!changeKeyV.empty()) { - for (const auto &iter : changeKeyV) { - configuration_->Merge(iter, config); - } - auto FindKeyFromKeychain = [](const std::string &findItemKey, const std::vector &keychain) -> int { - int amount = 0; - if (findItemKey.empty()) { - return amount; - } - - for (const auto &it :keychain) { - if (it.find(findItemKey) != std::string::npos) { - ++amount; - } - } - HILOG_INFO("amount :%{public}d", amount); - return amount; - }; - // the part that currently focuses on language - if (FindKeyFromKeychain(GlobalConfigurationKey::SYSTEM_LANGUAGE, changeKeyV) > 0 || - FindKeyFromKeychain(GlobalConfigurationKey::SYSTEM_ORIENTATION, changeKeyV) > 0) { - DelayedSingleton::GetInstance()->UpdateConfiguration(*configuration_); - } - - return ERR_OK; - } - return ERR_INVALID_VALUE; -} - -void AbilityManagerService::GetGlobalConfiguration() -{ - if (!GetConfiguration()) { - HILOG_INFO("configuration_ is null"); - return; - } - // Currently only this interface is known - auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); - HILOG_INFO("current global language is : %{public}s", language.c_str()); - GetConfiguration()->AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, language); - CHECK_POINTER(amsConfigResolver_); - // This is a temporary plan - std::string direction = amsConfigResolver_->GetOrientation(); - HILOG_INFO("current global direction is : %{public}s", direction.c_str()); - GetConfiguration()->AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, direction); - - DelayedSingleton::GetInstance()->InitConfiguration(*GetConfiguration()); -} - -std::shared_ptr AbilityManagerService::GetConfiguration() -{ - return configuration_; + return DelayedSingleton::GetInstance()->UpdateConfiguration(config); } int AbilityManagerService::MoveMissionToTop(int32_t missionId) @@ -743,7 +834,14 @@ int AbilityManagerService::MoveMissionToEnd(const sptr &token, co if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } - return currentStackManager_->MoveMissionToEnd(token, nonFirst); + auto abilityRecord = Token::GetAbilityRecordByToken(token); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return stackManager->MoveMissionToEnd(token, nonFirst); } int AbilityManagerService::RemoveMission(int id) @@ -771,7 +869,7 @@ int AbilityManagerService::RemoveStack(int id) } int AbilityManagerService::ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_INFO("Connect ability."); @@ -782,7 +880,14 @@ int AbilityManagerService::ConnectAbility( HILOG_INFO("AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility"); return ConnectRemoteAbility(want, connect->AsObject()); } - return ConnectLocalAbility(want, connect, callerToken); + + int32_t userIdValid = GetValidUserId(want, userId); + int result = CheckMultiOsAccount(userIdValid); + if (result != ERR_OK) { + HILOG_ERROR("CheckMultiOsAccount error."); + return result; + } + return ConnectLocalAbility(want, userIdValid, connect, callerToken); } int AbilityManagerService::DisconnectAbility(const sptr &connect) @@ -797,13 +902,13 @@ int AbilityManagerService::DisconnectAbility(const sptr &con return ERR_OK; } -int AbilityManagerService::ConnectLocalAbility( - const Want &want, const sptr &connect, const sptr &callerToken) +int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId, + const sptr &connect, const sptr &callerToken) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_INFO("%{public}s begin ConnectAbilityLocal", __func__); AbilityRequest abilityRequest; - ErrCode result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken); + ErrCode result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId); if (result != ERR_OK) { HILOG_ERROR("Generate ability request error."); return result; @@ -819,27 +924,29 @@ int AbilityManagerService::ConnectLocalAbility( HILOG_ERROR("Connect Ability failed, target Ability is not Service."); return TARGET_ABILITY_NOT_SERVICE; } - result = PreLoadAppDataAbilities(abilityInfo.bundleName); + result = PreLoadAppDataAbilities(abilityInfo.bundleName, userId); if (result != ERR_OK) { HILOG_ERROR("ConnectAbility: App data ability preloading failed, '%{public}s', %{public}d", abilityInfo.bundleName.c_str(), result); return result; } - return connectManager_->ConnectAbilityLocked(abilityRequest, connect, callerToken); + + auto connectManager = GetConnectManagerByUserId(userId); + if (connectManager == nullptr) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken); } int AbilityManagerService::ConnectRemoteAbility(const Want &want, const sptr &connect) { HILOG_INFO("%{public}s begin ConnectAbilityRemote", __func__); - sptr dms = GetDmsProxy(); - if (dms == nullptr) { - HILOG_ERROR("AbilityManagerService::ConnectRemoteAbility failed to get dms."); - return ERR_INVALID_VALUE; - } int32_t callerUid = IPCSkeleton::GetCallingUid(); int32_t callerPid = IPCSkeleton::GetCallingPid(); - return dms->ConnectRemoteAbility(want, connect, callerUid, callerPid); + DistributedClient dmsClient; + return dmsClient.ConnectRemoteAbility(want, connect, callerUid, callerPid); } int AbilityManagerService::DisconnectLocalAbility(const sptr &connect) @@ -851,12 +958,8 @@ int AbilityManagerService::DisconnectLocalAbility(const sptr int AbilityManagerService::DisconnectRemoteAbility(const sptr &connect) { HILOG_INFO("%{public}s begin DisconnectAbilityRemote", __func__); - sptr dms = GetDmsProxy(); - if (dms == nullptr) { - HILOG_ERROR("AbilityManagerService::DisconnectRemoteAbility failed to get dms."); - return ERR_INVALID_VALUE; - } - return dms->DisconnectRemoteAbility(connect); + DistributedClient dmsClient; + return dmsClient.DisconnectRemoteAbility(connect); } int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, @@ -864,13 +967,8 @@ int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const { HILOG_INFO("ContinueMission srcDeviceId: %{public}s, dstDeviceId: %{public}s, missionId: %{public}d", srcDeviceId.c_str(), dstDeviceId.c_str(), missionId); - - sptr dmsProxy = GetDmsProxy(); - if (dmsProxy == nullptr) { - HILOG_ERROR("ContinueMission failed to get dms."); - return ERR_INVALID_VALUE; - } - return dmsProxy->ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams); + DistributedClient dmsClient; + return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams); } int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId) @@ -897,18 +995,13 @@ int AbilityManagerService::StartContinuation(const Want &want, const sptr dmsProxy = GetDmsProxy(); - if (dmsProxy == nullptr) { - HILOG_ERROR("AbilityManagerService::StartContinuation failed to get dms."); - return ERR_INVALID_VALUE; - } int32_t missionId = GetMissionIdByAbilityToken(abilityToken); if (missionId == -1) { HILOG_ERROR("AbilityManagerService::StartContinuation failed to get missionId."); return ERR_INVALID_VALUE; } - auto result = dmsProxy->StartContinuation(want, missionId, appUid, status); + DistributedClient dmsClient; + auto result = dmsClient.StartContinuation(want, missionId, appUid, status); if (result != ERR_OK) { HILOG_ERROR("StartContinuation failed, result = %{public}d, notify caller", result); NotifyContinuationResult(missionId, result); @@ -920,13 +1013,8 @@ void AbilityManagerService::NotifyCompleteContinuation(const std::string &device int32_t sessionId, bool isSuccess) { HILOG_INFO("NotifyCompleteContinuation."); - - sptr dmsProxy = GetDmsProxy(); - if (dmsProxy == nullptr) { - HILOG_ERROR("AbilityManagerService::NotifyCompleteContinuation failed to get dms."); - return; - } - dmsProxy->NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess); + DistributedClient dmsClient; + dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess); } int AbilityManagerService::NotifyContinuationResult(int32_t missionId, const int32_t result) @@ -945,22 +1033,14 @@ int AbilityManagerService::NotifyContinuationResult(int32_t missionId, const int int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) { - sptr dmsProxy = GetDmsProxy(); - if (dmsProxy == nullptr) { - HILOG_ERROR("AbilityManagerService::StartSyncRemoteMissions failed to get dms."); - return ERR_INVALID_VALUE; - } - return dmsProxy->StartSyncRemoteMissions(devId, fixConflict, tag); + DistributedClient dmsClient; + return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag); } int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId) { - sptr dmsProxy = GetDmsProxy(); - if (dmsProxy == nullptr) { - HILOG_ERROR("AbilityManagerService::StopSyncRemoteMissions failed to get dms."); - return ERR_INVALID_VALUE; - } - return dmsProxy->StopSyncRemoteMissions(devId); + DistributedClient dmsClient; + return dmsClient.StopSyncRemoteMissions(devId); } int AbilityManagerService::RegisterMissionListener(const std::string &deviceId, @@ -971,40 +1051,9 @@ int AbilityManagerService::RegisterMissionListener(const std::string &deviceId, HILOG_ERROR("RegisterMissionListener: Check DeviceId failed"); return REGISTER_REMOTE_MISSION_LISTENER_FAIL; } - return CallMissionListener(deviceId, listener); -} - -int AbilityManagerService::CallMissionListener(const std::string &deviceId, - const sptr &listener) -{ - if (callListenerHandler_ == nullptr) { - HILOG_INFO("init callListenerHandler_"); - auto parseRunner = AppExecFwk::EventRunner::Create("CallRemoteMissionListener"); - callListenerHandler_ = std::make_shared(parseRunner); - } - int32_t delayTime = 2000; - auto callNotifyMissionsChanged = [listener, deviceId, this]() { - HILOG_INFO("callNotifyMissionsChanged"); - listener->NotifyMissionsChanged(deviceId); - }; - if (!callListenerHandler_->PostTask(callNotifyMissionsChanged, delayTime)) { - HILOG_ERROR("CallMissionListener: post NotifyMissionsChanged task failed"); - } - auto callNotifySnapshot = [listener, deviceId, this]() { - HILOG_INFO("callNotifySnapshot"); - listener->NotifySnapshot(deviceId, 1); - }; - if (!callListenerHandler_->PostTask(callNotifySnapshot, delayTime)) { - HILOG_ERROR("CallMissionListener: post NotifySnapshot task failed"); - } - auto callNotifyNetDisconnect = [listener, deviceId, this]() { - HILOG_INFO("callNotifyNetDisconnect"); - listener->NotifyNetDisconnect(deviceId, 1); - }; - if (!callListenerHandler_->PostTask(callNotifyNetDisconnect, delayTime)) { - HILOG_ERROR("CallMissionListener: post NotifyNetDisconnect task failed"); - } - return ERR_OK; + CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE); + DistributedClient dmsClient; + return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject()); } int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId, @@ -1015,7 +1064,9 @@ int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId HILOG_ERROR("RegisterMissionListener: Check DeviceId failed"); return REGISTER_REMOTE_MISSION_LISTENER_FAIL; } - return ERR_OK; + CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE); + DistributedClient dmsClient; + return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject()); } void AbilityManagerService::RemoveAllServiceRecord() @@ -1268,18 +1319,13 @@ int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, in std::vector &missionInfos) { HILOG_INFO("GetRemoteMissionInfos begin"); - sptr dmsProxy = GetDmsProxy(); - if (dmsProxy == nullptr) { - HILOG_ERROR("GetRemoteMissionInfos failed to get dms."); - return ERR_INVALID_VALUE; - } - std::vector dstbMissionInfos; - int result = dmsProxy->GetMissionInfos(deviceId, numMax, dstbMissionInfos); + DistributedClient dmsClient; + int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos); if (result != ERR_OK) { HILOG_ERROR("GetRemoteMissionInfos failed, result = %{public}d", result); return result; } - return DistributedSchedule::MissionInfoConverter::ConvertToMissionInfos(dstbMissionInfos, missionInfos); + return ERR_OK; } int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId, @@ -1401,33 +1447,48 @@ sptr AbilityManagerService::AcquireDataAbility( return nullptr; } + auto userId = GetUserId(); AbilityRequest abilityRequest; std::string dataAbilityUri = localUri.ToString(); - bool queryResult = iBundleManager_->QueryAbilityInfoByUri(dataAbilityUri, abilityRequest.abilityInfo); + HILOG_INFO("%{public}s, called. userId %{public}d", __func__, userId); + bool queryResult = iBundleManager_->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo); if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) { HILOG_ERROR("Invalid ability info for data ability acquiring."); return nullptr; } + + if (!CheckDataAbilityRequest(abilityRequest)) { + HILOG_ERROR("Invalid ability request info for data ability acquiring."); + return nullptr; + } + + HILOG_DEBUG("Query data ability info: %{public}s|%{public}s|%{public}s", + abilityRequest.appInfo.name.c_str(), + abilityRequest.appInfo.bundleName.c_str(), + abilityRequest.abilityInfo.name.c_str()); + + CHECK_POINTER_AND_RETURN(dataAbilityManager_, nullptr); + return dataAbilityManager_->Acquire(abilityRequest, tryBind, callerToken, isSystem); +} + +bool AbilityManagerService::CheckDataAbilityRequest(AbilityRequest &abilityRequest) +{ int result = AbilityUtil::JudgeAbilityVisibleControl(abilityRequest.abilityInfo); if (result != ERR_OK) { HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); - return nullptr; + return false; } abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo; if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) { HILOG_ERROR("Invalid app info for data ability acquiring."); - return nullptr; + return false; } if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) { HILOG_ERROR("BMS query result is not a data ability."); - return nullptr; + return false; } - HILOG_DEBUG("Query data ability info: %{public}s|%{public}s|%{public}s", - abilityRequest.appInfo.name.c_str(), - abilityRequest.appInfo.bundleName.c_str(), - abilityRequest.abilityInfo.name.c_str()); - - return dataAbilityManager_->Acquire(abilityRequest, tryBind, callerToken, isSystem); + abilityRequest.uid = abilityRequest.appInfo.uid; + return true; } int AbilityManagerService::ReleaseDataAbility( @@ -1460,14 +1521,25 @@ int AbilityManagerService::AttachAbilityThread( auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; auto abilityInfo = abilityRecord->GetAbilityInfo(); auto type = abilityInfo.type; int returnCode = -1; if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) { - returnCode = connectManager_->AttachAbilityThreadLocked(scheduler, token); + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + returnCode = connectManager->AttachAbilityThreadLocked(scheduler, token); } else if (type == AppExecFwk::AbilityType::DATA) { - returnCode = dataAbilityManager_->AttachAbilityThread(scheduler, token); + auto dataAbilityManager = GetDataAbilityManagerByUserId(userId); + if (!dataAbilityManager) { + HILOG_ERROR("dataAbilityManager is Null. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + returnCode = dataAbilityManager->AttachAbilityThread(scheduler, token); } else if (IsSystemUiApp(abilityInfo)) { if (useNewMission_) { returnCode = kernalAbilityManager_->AttachAbilityThread(scheduler, token); @@ -1476,17 +1548,22 @@ int AbilityManagerService::AttachAbilityThread( } } else { if (useNewMission_) { - returnCode = currentMissionListManager_->AttachAbilityThread(scheduler, token); + auto missionListManager = GetListManagerByUserId(userId); + if (!missionListManager) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + returnCode = missionListManager->AttachAbilityThread(scheduler, token); } else { - returnCode = currentStackManager_->AttachAbilityThread(scheduler, token); + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + returnCode = stackManager->AttachAbilityThread(scheduler, token); } } - HILOG_INFO("attach ability type [%{public}d] | returnCode [%{public}d]", type, returnCode); - if (SUCCEEDED(returnCode) && type != AppExecFwk::AbilityType::DATA) { - DelayedSingleton::GetInstance()->Atach(abilityRecord); - } - return returnCode; } @@ -1507,94 +1584,274 @@ void AbilityManagerService::DumpFuncInit() dumpFuncMap_[KEY_DUMP_MISSION_INFOS] = &AbilityManagerService::DumpMissionInfosInner; } -void AbilityManagerService::DumpInner(const std::string &args, std::vector &info) -{ - if (useNewMission_) { - if (currentMissionListManager_) { - currentMissionListManager_->Dump(info); - } - } else { - if (currentStackManager_) { - currentStackManager_->Dump(info); - } - } -} - -void AbilityManagerService::DumpStackListInner(const std::string &args, std::vector &info) -{ - currentStackManager_->DumpStackList(info); -} - -void AbilityManagerService::DumpFocusMapInner(const std::string &args, std::vector &info) -{ - currentStackManager_->DumpFocusMap(info); -} - -void AbilityManagerService::DumpWindowModeInner(const std::string &args, std::vector &info) +void AbilityManagerService::DumpSysFuncInit() { - currentStackManager_->DumpWindowMode(info); + dumpsysFuncMap_[KEY_DUMPSYS_ALL] = &AbilityManagerService::DumpSysInner; + dumpsysFuncMap_[KEY_DUMPSYS_MISSION_LIST] = &AbilityManagerService::DumpSysMissionListInner; + dumpsysFuncMap_[KEY_DUMPSYS_ABILITY] = &AbilityManagerService::DumpSysAbilityInner; + dumpsysFuncMap_[KEY_DUMPSYS_SERVICE] = &AbilityManagerService::DumpSysStateInner; + dumpsysFuncMap_[KEY_DUMPSYS_PENDING] = &AbilityManagerService::DumpSysPendingInner; + dumpsysFuncMap_[KEY_DUMPSYS_PROCESS] = &AbilityManagerService::DumpSysProcess; } -void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector &info) +void AbilityManagerService::DumpSysInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) { - if (currentMissionListManager_) { - currentMissionListManager_->DumpMissionList(info); + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { + return; } + DumpSysMissionListInner(args, info, isClient, isUserID, userId); + DumpSysStateInner(args, info, isClient, isUserID, userId); + DumpSysPendingInner(args, info, isClient, isUserID, userId); + DumpSysProcess(args, info, isClient, isUserID, userId); } -void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector &info) +void AbilityManagerService::DumpSysMissionListInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) { - if (currentMissionListManager_) { - currentMissionListManager_->DumpMissionInfos(info); + std::shared_ptr targetManager; + if (isUserID) { + auto it = missionListManagers_.find(userId); + if (it == missionListManagers_.end()) { + info.push_back("error: No user found'."); + return; + } + targetManager = it->second; + } else { + targetManager = currentMissionListManager_; } -} -void AbilityManagerService::DumpStackInner(const std::string &args, std::vector &info) -{ + CHECK_POINTER(targetManager); + std::vector argList; SplitStr(args, " ", argList); if (argList.empty()) { return; } - if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { - info.push_back("error: invalid argument, please see 'ability dump -h'."); - return; + + if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { + targetManager->DumpMissionList(info, isClient, argList[1]); + } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { + targetManager->DumpMissionList(info, isClient); + } else { + info.emplace_back("error: invalid argument, please see 'ability dumpsys -h'."); } - int stackId = DEFAULT_INVAL_VALUE; - (void)StrToInt(argList[1], stackId); - currentStackManager_->DumpStack(stackId, info); } - -void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector &info) +void AbilityManagerService::DumpSysAbilityInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) { + std::shared_ptr targetManager; + if (isUserID) { + auto it = missionListManagers_.find(userId); + if (it == missionListManagers_.end()) { + info.push_back("error: No user found'."); + return; + } + targetManager = it->second; + } else { + targetManager = currentMissionListManager_; + } + + CHECK_POINTER(targetManager); + std::vector argList; SplitStr(args, " ", argList); if (argList.empty()) { return; } - if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { - info.push_back("error: invalid argument, please see 'ability dump -h'."); - return; - } - int missionId = DEFAULT_INVAL_VALUE; - (void)StrToInt(argList[1], missionId); - if (useNewMission_) { - currentMissionListManager_->DumpMission(missionId, info); + if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { + HILOG_INFO("argList = %{public}s", argList[1].c_str()); + targetManager->DumpMissionListByRecordId(info, isClient, std::stoi(argList[1])); } else { - currentStackManager_->DumpMission(missionId, info); + info.emplace_back("error: invalid argument, please see 'ability dumpsys -h'."); } } -void AbilityManagerService::DumpTopAbilityInner(const std::string &args, std::vector &info) +void AbilityManagerService::DumpSysStateInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) { - currentStackManager_->DumpTopAbility(info); -} + std::shared_ptr targetManager; -void AbilityManagerService::DumpWaittingAbilityQueueInner(const std::string &args, std::vector &info) -{ - std::string result; - DumpWaittingAbilityQueue(result); - info.push_back(result); + if (isUserID) { + auto it = connectManagers_.find(userId); + if (it == connectManagers_.end()) { + info.push_back("error: No user found'."); + return; + } + targetManager = it->second; + } else { + targetManager = connectManager_; + } + + CHECK_POINTER(targetManager); + + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { + return; + } + + if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { + targetManager->DumpState(info, isClient, argList[1]); + } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { + targetManager->DumpState(info, isClient); + } else { + info.emplace_back("error: invalid argument, please see 'ability dumpsys -h'."); + } +} + +void AbilityManagerService::DumpSysPendingInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) +{ + if (isUserID) { + auto it = pendingWantManagers_.find(userId); + if (it != pendingWantManagers_.end()) { + it->second->Dump(info); + return; + } + info.push_back("error: No user found'."); + return; + } + + CHECK_POINTER(pendingWantManager_); + pendingWantManager_->Dump(info); +} + +void AbilityManagerService::DumpSysProcess( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) +{ + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { + return; + } + std::vector ProcessInfos; + int ret = 0; + if (isUserID) { + ret = GetProcessRunningInfosByUserId(ProcessInfos, userId); + } else { + ret = GetProcessRunningInfos(ProcessInfos); + } + + if (ret != ERR_OK || ProcessInfos.size() == 0) { + return; + } + + std::string dumpInfo = " AppRunningRecords:"; + info.push_back(dumpInfo); + auto processInfoID = 0; + auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false); + for (const auto& ProcessInfo : ProcessInfos) { + if (hasProcessName && argList[1] != ProcessInfo.processName_) { + continue; + } + + dumpInfo = " AppRunningRecord ID #" + std::to_string(processInfoID); + processInfoID++; + info.push_back(dumpInfo); + dumpInfo = " process name [" + ProcessInfo.processName_ + "]"; + info.push_back(dumpInfo); + dumpInfo = " pid #" + std::to_string(ProcessInfo.pid_) + + " uid #" + std::to_string(ProcessInfo.uid_); + info.push_back(dumpInfo); + auto appState = static_cast(ProcessInfo.state_); + if (appScheduler_) { + dumpInfo = " state #" + appScheduler_->ConvertAppState(appState); + } + info.push_back(dumpInfo); + } +} + +void AbilityManagerService::DumpInner(const std::string &args, std::vector &info) +{ + if (useNewMission_) { + if (currentMissionListManager_) { + currentMissionListManager_->Dump(info); + } + } else { + if (currentStackManager_) { + currentStackManager_->Dump(info); + } + } +} + +void AbilityManagerService::DumpStackListInner(const std::string &args, std::vector &info) +{ + currentStackManager_->DumpStackList(info); +} + +void AbilityManagerService::DumpFocusMapInner(const std::string &args, std::vector &info) +{ + currentStackManager_->DumpFocusMap(info); +} + +void AbilityManagerService::DumpWindowModeInner(const std::string &args, std::vector &info) +{ + currentStackManager_->DumpWindowMode(info); +} + +void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector &info) +{ + if (currentMissionListManager_) { + currentMissionListManager_->DumpMissionList(info, false, ""); + } +} + +void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector &info) +{ + if (currentMissionListManager_) { + currentMissionListManager_->DumpMissionInfos(info); + } +} + +void AbilityManagerService::DumpStackInner(const std::string &args, std::vector &info) +{ + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { + return; + } + if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { + info.push_back("error: invalid argument, please see 'ability dump -h'."); + return; + } + int stackId = DEFAULT_INVAL_VALUE; + (void)StrToInt(argList[1], stackId); + currentStackManager_->DumpStack(stackId, info); +} + +void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector &info) +{ + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { + return; + } + if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { + info.push_back("error: invalid argument, please see 'ability dump -h'."); + return; + } + int missionId = DEFAULT_INVAL_VALUE; + (void)StrToInt(argList[1], missionId); + if (useNewMission_) { + currentMissionListManager_->DumpMission(missionId, info); + } else { + currentStackManager_->DumpMission(missionId, info); + } +} + +void AbilityManagerService::DumpTopAbilityInner(const std::string &args, std::vector &info) +{ + currentStackManager_->DumpTopAbility(info); +} + +void AbilityManagerService::DumpWaittingAbilityQueueInner(const std::string &args, std::vector &info) +{ + std::string result; + DumpWaittingAbilityQueue(result); + info.push_back(result); } void AbilityManagerService::DumpStateInner(const std::string &args, std::vector &info) @@ -1605,9 +1862,9 @@ void AbilityManagerService::DumpStateInner(const std::string &args, std::vector< return; } if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { - connectManager_->DumpState(info, argList[1]); + connectManager_->DumpState(info, false, argList[1]); } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { - connectManager_->DumpState(info); + connectManager_->DumpState(info, false); } else { info.emplace_back("error: invalid argument, please see 'ability dump -h'."); } @@ -1671,11 +1928,35 @@ void AbilityManagerService::DumpState(const std::string &args, std::vector& info, bool isClient, bool isUserID, int userId) +{ + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { + return; + } + auto it = dumpsysMap.find(argList[0]); + if (it == dumpsysMap.end()) { + return; + } + DumpsysKey key = it->second; + auto itFunc = dumpsysFuncMap_.find(key); + if (itFunc != dumpsysFuncMap_.end()) { + auto dumpsysFunc = itFunc->second; + if (dumpsysFunc != nullptr) { + (this->*dumpsysFunc)(args, info, isClient, isUserID, userId); + return; + } + } + info.push_back("error: invalid argument, please see 'ability dump -h'."); +} + int AbilityManagerService::AbilityTransitionDone(const sptr &token, int state, const PacMap &saveData) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_INFO("Ability transition done, state:%{public}d", state); - if (!VerificationToken(token)) { + if (!VerificationToken(token) && !VerificationAllToken(token)) { return ERR_INVALID_VALUE; } @@ -1685,32 +1966,44 @@ int AbilityManagerService::AbilityTransitionDone(const sptr &toke auto abilityInfo = abilityRecord->GetAbilityInfo(); HILOG_DEBUG("state:%{public}d name:%{public}s", state, abilityInfo.name.c_str()); auto type = abilityInfo.type; - - if (type != AppExecFwk::AbilityType::DATA) { - int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast(state)); - if (targetState == AbilityState::INITIAL) { - DelayedSingleton::GetInstance()->Detach(abilityRecord); - } - } + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) { - return connectManager_->AbilityTransitionDone(token, state); + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->AbilityTransitionDone(token, state); } if (type == AppExecFwk::AbilityType::DATA) { - return dataAbilityManager_->AbilityTransitionDone(token, state); + auto dataAbilityManager = GetDataAbilityManagerByUserId(userId); + if (!dataAbilityManager) { + HILOG_ERROR("dataAbilityManager is Null. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return dataAbilityManager->AbilityTransitionDone(token, state); } if (useNewMission_) { if (IsSystemUiApp(abilityInfo)) { return kernalAbilityManager_->AbilityTransitionDone(token, state); } - - return currentMissionListManager_->AbilityTransactionDone(token, state, saveData); + auto missionListManager = GetListManagerByUserId(userId); + if (!missionListManager) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return missionListManager->AbilityTransactionDone(token, state, saveData); } else { if (IsSystemUiApp(abilityInfo)) { return systemAppManager_->AbilityTransitionDone(token, state); } - - return currentStackManager_->AbilityTransitionDone(token, state, saveData); + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return stackManager->AbilityTransitionDone(token, state, saveData); } } @@ -1731,8 +2024,13 @@ int AbilityManagerService::ScheduleConnectAbilityDone( HILOG_ERROR("Connect ability failed, target ability is not service."); return TARGET_ABILITY_NOT_SERVICE; } - - return connectManager_->ScheduleConnectAbilityDoneLocked(token, remoteObject); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject); } int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr &token) @@ -1751,8 +2049,13 @@ int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptrScheduleDisconnectAbilityDoneLocked(token); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->ScheduleDisconnectAbilityDoneLocked(token); } int AbilityManagerService::ScheduleCommandAbilityDone(const sptr &token) @@ -1771,8 +2074,13 @@ int AbilityManagerService::ScheduleCommandAbilityDone(const sptr HILOG_ERROR("Connect ability failed, target ability is not service."); return TARGET_ABILITY_NOT_SERVICE; } - - return connectManager_->ScheduleCommandAbilityDoneLocked(token); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->ScheduleCommandAbilityDoneLocked(token); } void AbilityManagerService::AddWindowInfo(const sptr &token, int32_t windowToken) @@ -1781,42 +2089,69 @@ void AbilityManagerService::AddWindowInfo(const sptr &token, int3 if (!VerificationToken(token)) { return; } - currentStackManager_->AddWindowInfo(token, windowToken); + auto abilityRecord = Token::GetAbilityRecordByToken(token); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ; + } + stackManager->AddWindowInfo(token, windowToken); } void AbilityManagerService::OnAbilityRequestDone(const sptr &token, const int32_t state) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_INFO("On ability request done."); - if (!VerificationToken(token)) { - return; - } auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER(abilityRecord); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; auto type = abilityRecord->GetAbilityInfo().type; switch (type) { case AppExecFwk::AbilityType::SERVICE: - case AppExecFwk::AbilityType::EXTENSION: - connectManager_->OnAbilityRequestDone(token, state); + case AppExecFwk::AbilityType::EXTENSION: { + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return; + } + connectManager->OnAbilityRequestDone(token, state); break; - case AppExecFwk::AbilityType::DATA: - dataAbilityManager_->OnAbilityRequestDone(token, state); + } + case AppExecFwk::AbilityType::DATA: { + auto dataAbilityManager = GetDataAbilityManagerByUserId(userId); + if (!dataAbilityManager) { + HILOG_ERROR("dataAbilityManager is Null. userId=%{public}d", userId); + return; + } + dataAbilityManager->OnAbilityRequestDone(token, state); break; + } default: { if (useNewMission_) { if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { kernalAbilityManager_->OnAbilityRequestDone(token, state); break; } - currentMissionListManager_->OnAbilityRequestDone(token, state); + auto missionListManager = GetListManagerByUserId(userId); + if (!missionListManager) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); + return; + } + missionListManager->OnAbilityRequestDone(token, state); } else { if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { systemAppManager_->OnAbilityRequestDone(token, state); break; } - currentStackManager_->OnAbilityRequestDone(token, state); + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return; + } + stackManager->OnAbilityRequestDone(token, state); } break; } @@ -1841,27 +2176,38 @@ std::shared_ptr AbilityManagerService::GetEventHandler() return handler_; } -void AbilityManagerService::SetStackManager(int userId) +void AbilityManagerService::SetStackManager(int userId, bool switchUser) { auto iterator = stackManagers_.find(userId); if (iterator != stackManagers_.end()) { - currentStackManager_ = iterator->second; + if (switchUser) { + currentStackManager_ = iterator->second; + } } else { - currentStackManager_ = std::make_shared(userId); - currentStackManager_->Init(); - stackManagers_.emplace(userId, currentStackManager_); + auto manager = std::make_shared(userId); + manager->Init(); + stackManagers_.emplace(userId, manager); + if (switchUser) { + currentStackManager_ = manager; + } } } -void AbilityManagerService::InitMissionListManager(int userId) +void AbilityManagerService::InitMissionListManager(int userId, bool switchUser) { auto iterator = missionListManagers_.find(userId); if (iterator != missionListManagers_.end()) { - currentMissionListManager_ = iterator->second; + if (switchUser) { + DelayedSingleton::GetInstance()->Init(userId); + currentMissionListManager_ = iterator->second; + } } else { - currentMissionListManager_ = std::make_shared(userId); - currentMissionListManager_->Init(); - missionListManagers_.emplace(userId, currentMissionListManager_); + auto manager = std::make_shared(userId); + manager->Init(); + missionListManagers_.emplace(userId, manager); + if (switchUser) { + currentMissionListManager_ = manager; + } } } @@ -1879,6 +2225,9 @@ void AbilityManagerService::DumpWaittingAbilityQueue(std::string &result) // multi user scene int AbilityManagerService::GetUserId() { + if (userController_) { + return userController_->GetCurrentUserId(); + } return DEFAULT_USER_ID; } @@ -1893,16 +2242,18 @@ void AbilityManagerService::StartingLauncherAbility() /* query if launcher ability has installed */ AppExecFwk::AbilityInfo abilityInfo; /* First stage, hardcoding for the first launcher App */ + auto userId = GetUserId(); Want want; want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME); - while (!(iBundleManager_->QueryAbilityInfo(want, abilityInfo))) { + while (!(iBundleManager_->QueryAbilityInfo(want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, + userId, abilityInfo))) { HILOG_INFO("Waiting query launcher ability info completed."); usleep(REPOLL_TIME_MICRO_SECONDS); } HILOG_INFO("Start Home Launcher Ability."); /* start launch ability */ - (void)StartAbility(want, DEFAULT_INVAL_VALUE); + (void)StartAbility(want, userId, DEFAULT_INVAL_VALUE); return; } @@ -1919,12 +2270,17 @@ void AbilityManagerService::StartingPhoneServiceAbility() phoneServiceWant.SetElementName(AbilityConfig::PHONE_SERVICE_BUNDLE_NAME, AbilityConfig::PHONE_SERVICE_ABILITY_NAME); - while (!(iBundleManager_->QueryAbilityInfo(phoneServiceWant, phoneServiceInfo))) { + auto userId = GetUserId(); + int attemptNums = 1; + while (!(iBundleManager_->QueryAbilityInfo(phoneServiceWant, + OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId, phoneServiceInfo)) && + attemptNums <= MAX_NUMBER_OF_CONNECT_BMS) { HILOG_INFO("Waiting query phone service ability info completed."); usleep(REPOLL_TIME_MICRO_SECONDS); + attemptNums++; } - (void)StartAbility(phoneServiceWant, DEFAULT_INVAL_VALUE); + (void)StartAbility(phoneServiceWant, userId, DEFAULT_INVAL_VALUE); } void AbilityManagerService::StartingContactsAbility() @@ -1939,12 +2295,20 @@ void AbilityManagerService::StartingContactsAbility() Want contactsWant; contactsWant.SetElementName(AbilityConfig::CONTACTS_BUNDLE_NAME, AbilityConfig::CONTACTS_ABILITY_NAME); - while (!(iBundleManager_->QueryAbilityInfo(contactsWant, contactsInfo))) { + auto userId = GetUserId(); + int attemptNums = 1; + while (!(iBundleManager_->QueryAbilityInfo(contactsWant, + OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId, contactsInfo)) && + attemptNums <= MAX_NUMBER_OF_CONNECT_BMS) { HILOG_INFO("Waiting query contacts service completed."); usleep(REPOLL_TIME_MICRO_SECONDS); + attemptNums++; } - (void)StartAbility(contactsWant, DEFAULT_INVAL_VALUE); + HILOG_INFO("attemptNums : %{public}d", attemptNums); + if (attemptNums <= MAX_NUMBER_OF_CONNECT_BMS) { + (void)StartAbility(contactsWant, userId, DEFAULT_INVAL_VALUE); + } } void AbilityManagerService::StartingMmsAbility() @@ -1959,12 +2323,20 @@ void AbilityManagerService::StartingMmsAbility() Want mmsWant; mmsWant.SetElementName(AbilityConfig::MMS_BUNDLE_NAME, AbilityConfig::MMS_ABILITY_NAME); - while (!(iBundleManager_->QueryAbilityInfo(mmsWant, mmsInfo))) { + auto userId = GetUserId(); + int attemptNums = 1; + while (!(iBundleManager_->QueryAbilityInfo(mmsWant, + OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId, mmsInfo)) && + attemptNums <= MAX_NUMBER_OF_CONNECT_BMS) { HILOG_INFO("Waiting query mms service completed."); usleep(REPOLL_TIME_MICRO_SECONDS); + attemptNums++; } - (void)StartAbility(mmsWant, DEFAULT_INVAL_VALUE); + HILOG_INFO("attemptNums : %{public}d", attemptNums); + if (attemptNums <= MAX_NUMBER_OF_CONNECT_BMS) { + (void)StartAbility(mmsWant, userId, DEFAULT_INVAL_VALUE); + } } void AbilityManagerService::StartSystemUi(const std::string abilityName) @@ -1973,12 +2345,12 @@ void AbilityManagerService::StartSystemUi(const std::string abilityName) Want want; want.SetElementName(AbilityConfig::SYSTEM_UI_BUNDLE_NAME, abilityName); HILOG_INFO("Ability name: %{public}s.", abilityName.c_str()); - (void)StartAbility(want, DEFAULT_INVAL_VALUE); + (void)StartAbility(want, USER_ID_DEFAULT, DEFAULT_INVAL_VALUE); return; } int AbilityManagerService::GenerateAbilityRequest( - const Want &want, int requestCode, AbilityRequest &request, const sptr &callerToken) + const Want &want, int requestCode, AbilityRequest &request, const sptr &callerToken, int32_t userId) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); request.want = want; @@ -1989,16 +2361,24 @@ int AbilityManagerService::GenerateAbilityRequest( auto bms = GetBundleManager(); CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); - bms->QueryAbilityInfo(want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, 0, request.abilityInfo); + if (want.GetAction().compare(ACTION_CHOOSE) == 0) { + return ShowPickerDialog(want, userId); + } + bms->QueryAbilityInfo(want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, + userId, request.abilityInfo); if (request.abilityInfo.name.empty() || request.abilityInfo.bundleName.empty()) { - HILOG_ERROR("Get ability info failed."); - return RESOLVE_ABILITY_ERR; + // try to find extension + int ret = GetAbilityInfoFromExtension(want, request.abilityInfo); + if (!ret) { + HILOG_ERROR("Get ability info failed."); + return RESOLVE_ABILITY_ERR; + } } HILOG_DEBUG("Query ability name: %{public}s,", request.abilityInfo.name.c_str()); if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE) { AppExecFwk::BundleInfo bundleInfo; bool ret = bms->GetBundleInfo(request.abilityInfo.bundleName, - AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId); if (!ret) { HILOG_ERROR("Failed to get bundle info when GenerateAbilityRequest."); return RESOLVE_ABILITY_ERR; @@ -2018,11 +2398,13 @@ int AbilityManagerService::GenerateAbilityRequest( HILOG_DEBUG("Query app name: %{public}s,", request.appInfo.name.c_str()); AppExecFwk::BundleInfo bundleInfo; - if (!bms->GetBundleInfo(request.appInfo.bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo)) { + if (!bms->GetBundleInfo(request.appInfo.bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, + bundleInfo, userId)) { HILOG_ERROR("Failed to get bundle info when generate ability request."); return RESOLVE_APP_ERR; } request.compatibleVersion = bundleInfo.compatibleVersion; + request.uid = bundleInfo.uid; return ERR_OK; } @@ -2050,23 +2432,36 @@ int AbilityManagerService::TerminateAbilityResult(const sptr &tok return result; } + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; auto type = abilityRecord->GetAbilityInfo().type; if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) { HILOG_ERROR("target ability is not service."); return TARGET_ABILITY_NOT_SERVICE; } - return connectManager_->TerminateAbilityResult(token, startId); + auto connectManager = GetConnectManagerByUserId(userId); + if (!connectManager) { + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return connectManager->TerminateAbilityResult(token, startId); } -int AbilityManagerService::StopServiceAbility(const Want &want) +int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_DEBUG("Stop service ability."); + + int32_t userIdValid = GetValidUserId(want, userId); + int result = CheckMultiOsAccount(userIdValid); + if (result != ERR_OK) { + HILOG_ERROR("CheckMultiOsAccount error."); + return result; + } AbilityRequest abilityRequest; - int result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr); + result = GenerateAbilityRequestLocal(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, userIdValid); if (result != ERR_OK) { - HILOG_ERROR("Generate ability request error."); + HILOG_ERROR("Generate ability request local error."); return result; } auto abilityInfo = abilityRequest.abilityInfo; @@ -2075,7 +2470,13 @@ int AbilityManagerService::StopServiceAbility(const Want &want) HILOG_ERROR("Target ability is not service type."); return TARGET_ABILITY_NOT_SERVICE; } - return connectManager_->StopServiceAbility(abilityRequest); + + auto connectManager = GetConnectManagerByUserId(userIdValid); + if (connectManager == nullptr) { + return ERR_INVALID_VALUE; + } + + return connectManager->StopServiceAbility(abilityRequest); } void AbilityManagerService::OnAbilityDied(std::shared_ptr abilityRecord) @@ -2088,8 +2489,10 @@ void AbilityManagerService::OnAbilityDied(std::shared_ptr ability return; } - if (currentMissionListManager_) { - currentMissionListManager_->OnAbilityDied(abilityRecord); + auto manager = GetListManagerByToken(abilityRecord->GetToken()); + if (manager) { + manager->OnAbilityDied(abilityRecord, GetUserId()); + return; } } else { if (systemAppManager_ && abilityRecord->IsKernalSystemAbility()) { @@ -2097,20 +2500,45 @@ void AbilityManagerService::OnAbilityDied(std::shared_ptr ability return; } - if (currentStackManager_) { - currentStackManager_->OnAbilityDied(abilityRecord); + auto manager = GetStackManagerByToken(abilityRecord->GetToken()); + if (manager) { + manager->OnAbilityDied(abilityRecord); + return; } } - if (connectManager_) { - connectManager_->OnAbilityDied(abilityRecord); + auto manager = GetConnectManagerByToken(abilityRecord->GetToken()); + if (manager) { + manager->OnAbilityDied(abilityRecord); + return; + } + + auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken()); + if (dataAbilityManager) { + dataAbilityManager->OnAbilityDied(abilityRecord); + } +} + +void AbilityManagerService::OnCallConnectDied(std::shared_ptr callRecord) +{ + CHECK_POINTER(callRecord); + if (currentMissionListManager_) { + currentMissionListManager_->OnCallConnectDied(callRecord); } +} - if (dataAbilityManager_) { - dataAbilityManager_->OnAbilityDied(abilityRecord); +void AbilityManagerService::GetMaxRestartNum(int &max) +{ + if (amsConfigResolver_) { + max = amsConfigResolver_->GetMaxRestartNum(); } } +bool AbilityManagerService::IsUseNewMission() +{ + return useNewMission_; +} + int AbilityManagerService::KillProcess(const std::string &bundleName) { HILOG_DEBUG("Kill process, bundleName: %{public}s", bundleName.c_str()); @@ -2121,9 +2549,9 @@ int AbilityManagerService::KillProcess(const std::string &bundleName) auto bms = GetBundleManager(); CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED); - + int32_t userId = GetUserId(); AppExecFwk::BundleInfo bundleInfo; - if (!bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo)) { + if (!bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId)) { HILOG_ERROR("Failed to get bundle info when kill process."); return GET_BUNDLE_INFO_FAILED; } @@ -2143,6 +2571,10 @@ int AbilityManagerService::KillProcess(const std::string &bundleName) int AbilityManagerService::ClearUpApplicationData(const std::string &bundleName) { HILOG_DEBUG("ClearUpApplicationData, bundleName: %{public}s", bundleName.c_str()); + if (!CheckCallerIsSystemAppByIpc()) { + HILOG_ERROR("caller is not systemApp"); + return CALLER_ISNOT_SYSTEMAPP; + } int ret = DelayedSingleton::GetInstance()->ClearUpApplicationData(bundleName); if (ret != ERR_OK) { return CLEAR_APPLICATION_DATA_FAIL; @@ -2179,14 +2611,15 @@ sptr AbilityManagerService::GetBundleManager() return iBundleManager_; } -int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName) +int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId) { if (bundleName.empty()) { HILOG_ERROR("Invalid bundle name when app data abilities preloading."); return ERR_INVALID_VALUE; } - if (dataAbilityManager_ == nullptr) { + auto dataAbilityManager = GetDataAbilityManagerByUserId(userId); + if (dataAbilityManager == nullptr) { HILOG_ERROR("Invalid data ability manager when app data abilities preloading."); return ERR_INVALID_STATE; } @@ -2195,7 +2628,7 @@ int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); AppExecFwk::BundleInfo bundleInfo; - bool ret = bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); + bool ret = bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId); if (!ret) { HILOG_ERROR("Failed to get bundle info when app data abilities preloading."); return RESOLVE_APP_ERR; @@ -2215,9 +2648,10 @@ int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName return ERR_TIMED_OUT; } dataAbilityRequest.abilityInfo = *it; + dataAbilityRequest.uid = bundleInfo.uid; HILOG_INFO("App data ability preloading: '%{public}s.%{public}s'...", it->bundleName.c_str(), it->name.c_str()); - auto dataAbility = dataAbilityManager_->Acquire(dataAbilityRequest, false, nullptr, false); + auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false); if (dataAbility == nullptr) { HILOG_ERROR( "Failed to preload data ability '%{public}s.%{public}s'.", it->bundleName.c_str(), it->name.c_str()); @@ -2238,6 +2672,11 @@ bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) c return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR || info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR); } +bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const +{ + return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME; +} + void AbilityManagerService::HandleLoadTimeOut(int64_t eventId) { HILOG_DEBUG("Handle load timeout."); @@ -2245,14 +2684,21 @@ void AbilityManagerService::HandleLoadTimeOut(int64_t eventId) if (kernalAbilityManager_) { kernalAbilityManager_->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); } + for (auto& item : missionListManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); + } + } } else { if (systemAppManager_) { systemAppManager_->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); } + for (auto& item : stackManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); + } + } } - if (currentStackManager_) { - currentStackManager_->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); - } } void AbilityManagerService::HandleActiveTimeOut(int64_t eventId) @@ -2263,21 +2709,38 @@ void AbilityManagerService::HandleActiveTimeOut(int64_t eventId) if (kernalAbilityManager_) { kernalAbilityManager_->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); } + for (auto& item : missionListManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); + } + } } else { if (systemAppManager_) { systemAppManager_->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); } - } - if (currentStackManager_) { - currentStackManager_->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); + for (auto& item : stackManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); + } + } } } void AbilityManagerService::HandleInactiveTimeOut(int64_t eventId) { HILOG_DEBUG("Handle inactive timeout."); - if (currentStackManager_) { - currentStackManager_->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, eventId); + if (useNewMission_) { + for (auto& item : missionListManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, eventId); + } + } + } else { + for (auto& item : stackManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, eventId); + } + } } } @@ -2288,13 +2751,20 @@ void AbilityManagerService::HandleForegroundNewTimeOut(int64_t eventId) if (kernalAbilityManager_) { kernalAbilityManager_->OnTimeOut(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, eventId); } + for (auto& item : missionListManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, eventId); + } + } } else { if (systemAppManager_) { systemAppManager_->OnTimeOut(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, eventId); } - } - if (currentStackManager_) { - currentStackManager_->OnTimeOut(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, eventId); + for (auto& item : stackManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, eventId); + } + } } } @@ -2305,13 +2775,20 @@ void AbilityManagerService::HandleBackgroundNewTimeOut(int64_t eventId) if (kernalAbilityManager_) { kernalAbilityManager_->OnTimeOut(AbilityManagerService::BACKGROUNDNEW_TIMEOUT_MSG, eventId); } + for (auto& item : missionListManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::BACKGROUNDNEW_TIMEOUT_MSG, eventId); + } + } } else { if (systemAppManager_) { systemAppManager_->OnTimeOut(AbilityManagerService::BACKGROUNDNEW_TIMEOUT_MSG, eventId); } - } - if (currentStackManager_) { - currentStackManager_->OnTimeOut(AbilityManagerService::BACKGROUNDNEW_TIMEOUT_MSG, eventId); + for (auto& item : stackManagers_) { + if (item.second) { + item.second->OnTimeOut(AbilityManagerService::BACKGROUNDNEW_TIMEOUT_MSG, eventId); + } + } } } @@ -2364,6 +2841,153 @@ bool AbilityManagerService::VerificationToken(const sptr &token) return false; } +bool AbilityManagerService::VerificationAllToken(const sptr &token) +{ + HILOG_INFO("VerificationAllToken."); + + if (useNewMission_) { + for (auto item: missionListManagers_) { + if (item.second && item.second->GetAbilityRecordByToken(token)) { + return true; + } + + if (item.second && item.second->GetAbilityFromTerminateList(token)) { + return true; + } + } + } else { + for (auto item: stackManagers_) { + if (item.second && item.second->GetAbilityRecordByToken(token)) { + return true; + } + + if (item.second && item.second->GetAbilityFromTerminateList(token)) { + return true; + } + } + } + + for (auto item: dataAbilityManagers_) { + if (item.second && item.second->GetAbilityRecordByToken(token)) { + return true; + } + } + + for (auto item: connectManagers_) { + if (item.second && item.second->GetServiceRecordByToken(token)) { + return true; + } + } + + if (useNewMission_) { + if (kernalAbilityManager_->GetAbilityRecordByToken(token)) { + return true; + } + } else { + if (systemAppManager_->GetAbilityRecordByToken(token)) { + return true; + } + } + + HILOG_ERROR("Failed to verify all token."); + return false; +} + +std::shared_ptr AbilityManagerService::GetStackManagerByUserId(int32_t userId) +{ + auto it = stackManagers_.find(userId); + if (it != stackManagers_.end()) { + return it->second; + } + HILOG_ERROR("%{public}s, Failed to get Manager. UserId = %{public}d", __func__, userId); + return nullptr; +} + +std::shared_ptr AbilityManagerService::GetListManagerByUserId(int32_t userId) +{ + auto it = missionListManagers_.find(userId); + if (it != missionListManagers_.end()) { + return it->second; + } + HILOG_ERROR("%{public}s, Failed to get Manager. UserId = %{public}d", __func__, userId); + return nullptr; +} + +std::shared_ptr AbilityManagerService::GetConnectManagerByUserId(int32_t userId) +{ + auto it = connectManagers_.find(userId); + if (it != connectManagers_.end()) { + return it->second; + } + HILOG_ERROR("%{public}s, Failed to get Manager. UserId = %{public}d", __func__, userId); + return nullptr; +} + +std::shared_ptr AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId) +{ + auto it = dataAbilityManagers_.find(userId); + if (it != dataAbilityManagers_.end()) { + return it->second; + } + HILOG_ERROR("%{public}s, Failed to get Manager. UserId = %{public}d", __func__, userId); + return nullptr; +} + +std::shared_ptr AbilityManagerService::GetStackManagerByToken(const sptr &token) +{ + for (auto item: stackManagers_) { + if (item.second && item.second->GetAbilityRecordByToken(token)) { + return item.second; + } + + if (item.second && item.second->GetAbilityFromTerminateList(token)) { + return item.second; + } + } + + return nullptr; +} + +std::shared_ptr AbilityManagerService::GetListManagerByToken(const sptr &token) +{ + for (auto item: missionListManagers_) { + if (item.second && item.second->GetAbilityRecordByToken(token)) { + return item.second; + } + + if (item.second && item.second->GetAbilityFromTerminateList(token)) { + return item.second; + } + } + + return nullptr; +} + +std::shared_ptr AbilityManagerService::GetConnectManagerByToken( + const sptr &token) +{ + for (auto item: connectManagers_) { + if (item.second && item.second->GetServiceRecordByToken(token)) { + return item.second; + } + } + + return nullptr; +} + +std::shared_ptr AbilityManagerService::GetDataAbilityManagerByToken( + const sptr &token) +{ + for (auto item: dataAbilityManagers_) { + if (item.second && item.second->GetAbilityRecordByToken(token)) { + return item.second; + } + } + + return nullptr; +} + + int AbilityManagerService::MoveMissionToFloatingStack(const MissionOption &missionOption) { HILOG_INFO("Move mission to floating stack."); @@ -2436,8 +3060,14 @@ bool AbilityManagerService::IsFirstInMission(const sptr &token) if (!VerificationToken(token)) { return false; } - - return currentStackManager_->IsFirstInMission(token); + auto abilityRecord = Token::GetAbilityRecordByToken(token); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return ERR_INVALID_VALUE; + } + return stackManager->IsFirstInMission(token); } int AbilityManagerService::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) @@ -2503,6 +3133,7 @@ void AbilityManagerService::RestartAbility(const sptr &token) } auto abilityRecord = Token::GetAbilityRecordByToken(token); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; CHECK_POINTER(abilityRecord); if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { @@ -2513,16 +3144,21 @@ void AbilityManagerService::RestartAbility(const sptr &token) } return; } - - currentStackManager_->RestartAbility(abilityRecord); + auto stackManager = GetStackManagerByUserId(userId); + if (!stackManager) { + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); + return; + } + stackManager->RestartAbility(abilityRecord); } void AbilityManagerService::NotifyBmsAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) { auto bundleManager = GetBundleManager(); CHECK_POINTER(bundleManager); - bundleManager->NotifyAbilityLifeStatus(bundleName, abilityName, launchTime); + HILOG_INFO("NotifyBmsAbilityLifeStatus is called, uid :%{public}d", uid); + bundleManager->NotifyAbilityLifeStatus(bundleName, abilityName, launchTime, uid); } void AbilityManagerService::StartSystemApplication() @@ -2533,22 +3169,10 @@ void AbilityManagerService::StartSystemApplication() if (!amsConfigResolver_ || amsConfigResolver_->NonConfigFile()) { HILOG_INFO("start all"); - StartingLauncherAbility(); - StartingSettingsDataAbility(); StartingSystemUiAbility(SatrtUiMode::STARTUIBOTH); return; } - if (amsConfigResolver_->GetStartLauncherState()) { - HILOG_INFO("start launcher"); - StartingLauncherAbility(); - } - - if (amsConfigResolver_->GetStartSettingsDataState()) { - HILOG_INFO("start settingsdata"); - StartingSettingsDataAbility(); - } - if (amsConfigResolver_->GetStatusBarState()) { HILOG_INFO("start status bar"); StartingSystemUiAbility(SatrtUiMode::STATUSBAR); @@ -2559,16 +3183,6 @@ void AbilityManagerService::StartSystemApplication() StartingSystemUiAbility(SatrtUiMode::NAVIGATIONBAR); } - if (amsConfigResolver_->GetStartContactsState()) { - HILOG_INFO("start contacts"); - StartingContactsAbility(); - } - - if (amsConfigResolver_->GetStartMmsState()) { - HILOG_INFO("start mms"); - StartingMmsAbility(); - } - // Location may change DelayedSingleton::GetInstance()->StartupResidentProcess(); } @@ -2614,8 +3228,11 @@ void AbilityManagerService::StartingSystemUiAbility(const SatrtUiMode &mode) navigationBarWant.SetElementName(AbilityConfig::SYSTEM_UI_BUNDLE_NAME, AbilityConfig::SYSTEM_UI_NAVIGATION_BAR); uint32_t waitCnt = 0; // Wait 10 minutes for the installation to complete. - while ((!(iBundleManager_->QueryAbilityInfo(statusBarWant, statusBarInfo)) || - !(iBundleManager_->QueryAbilityInfo(navigationBarWant, navigationBarInfo))) && + auto userId = MAIN_USER_ID; + while ((!(iBundleManager_->QueryAbilityInfo(statusBarWant, + OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId, statusBarInfo)) || + !(iBundleManager_->QueryAbilityInfo(navigationBarWant, + OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId, navigationBarInfo))) && waitCnt < MAX_WAIT_SYSTEM_UI_NUM) { HILOG_INFO("Waiting query system ui info completed."); usleep(REPOLL_TIME_MICRO_SECONDS); @@ -2703,10 +3320,15 @@ int AbilityManagerService::GetMissionSaveTime() const int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr &token) { - if (!currentMissionListManager_) { + auto abilityRecord = Token::GetAbilityRecordByToken(token); + auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; + auto missionListManager = GetListManagerByUserId(userId); + if (!missionListManager) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); return -1; } - return currentMissionListManager_->GetMissionIdByAbilityToken(token); + + return missionListManager->GetMissionIdByAbilityToken(token); } sptr AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId) @@ -2730,7 +3352,9 @@ void AbilityManagerService::StartingSettingsDataAbility() want.SetElementName(AbilityConfig::SETTINGS_DATA_BUNDLE_NAME, AbilityConfig::SETTINGS_DATA_ABILITY_NAME); uint32_t waitCnt = 0; // Wait 5 minutes for the installation to complete. - while (!iBundleManager_->QueryAbilityInfo(want, abilityInfo) && waitCnt < MAX_WAIT_SETTINGS_DATA_NUM) { + auto userId = GetUserId(); + while (!iBundleManager_->QueryAbilityInfo(want, OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, + userId, abilityInfo) && waitCnt < MAX_WAIT_SETTINGS_DATA_NUM) { HILOG_INFO("Waiting query settings data info completed."); usleep(REPOLL_TIME_MICRO_SECONDS); waitCnt++; @@ -2762,19 +3386,738 @@ void AbilityManagerService::StartingSettingsDataAbility() (void)AcquireDataAbility(uri, true, nullptr); } -int AbilityManagerService::StartUser(int userId) +int AbilityManagerService::StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) +{ + HILOG_INFO("call ability."); + CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE); + + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.callerUid = IPCSkeleton::GetCallingUid(); + abilityRequest.callerToken = callerToken; + abilityRequest.startSetting = nullptr; + abilityRequest.want = want; + abilityRequest.connect = connect; + int result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId()); + if (result != ERR_OK) { + HILOG_ERROR("Generate ability request error."); + return result; + } + + if (!abilityRequest.IsNewVersion()) { + HILOG_ERROR("target ability compatible version is lower than 8."); + return RESOLVE_CALL_ABILITY_VERSION_ERR; + } + + result = CheckCallPermissions(abilityRequest); + if (result != ERR_OK) { + HILOG_ERROR("CheckCallPermissions fail, result: %{public}d", result); + return RESOLVE_CALL_NO_PERMISSIONS; + } + + return currentMissionListManager_->ResolveLocked(abilityRequest); +} + +int AbilityManagerService::ReleaseAbility( + const sptr &connect, const AppExecFwk::ElementName &element) +{ + HILOG_DEBUG("Release called ability."); + + CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE); + + std::string elementName = element.GetURI(); + HILOG_DEBUG("try to release called ability, name: %{public}s.", elementName.c_str()); + + return currentMissionListManager_->ReleaseLocked(connect, element); +} + +int AbilityManagerService::CheckCallPermissions(const AbilityRequest &abilityRequest) +{ + HILOG_DEBUG("%{public}s begin", __func__); + + auto abilityInfo = abilityRequest.abilityInfo; + auto callerUid = abilityRequest.callerUid; + auto targetUid = abilityInfo.applicationInfo.uid; + + if (AbilityUtil::ROOT_UID == callerUid) { + HILOG_DEBUG("uid is root,ability cannot be called."); + return RESOLVE_CALL_NO_PERMISSIONS; + } + + auto bms = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); + + auto isSystemApp = bms->CheckIsSystemAppByUid(callerUid); + if (callerUid != SYSTEM_UID && !isSystemApp) { + HILOG_DEBUG("caller is common app."); + std::string bundleName; + bool result = bms->GetBundleNameForUid(callerUid, bundleName); + if (!result) { + HILOG_ERROR("GetBundleNameForUid frome bms fail."); + return RESOLVE_CALL_NO_PERMISSIONS; + } + if (bundleName != abilityInfo.bundleName && callerUid != targetUid) { + HILOG_ERROR("the bundlename of caller is different from target one, caller: %{public}s " + "target: %{public}s", + bundleName.c_str(), + abilityInfo.bundleName.c_str()); + return RESOLVE_CALL_NO_PERMISSIONS; + } + } else { + HILOG_DEBUG("caller is systemapp or system ability."); + } + + HILOG_DEBUG("the caller has permission to resolve the callproxy of common ability."); + + // check whether the target ability is singleton mode and page type. + if (abilityInfo.type == AppExecFwk::AbilityType::PAGE && + abilityInfo.launchMode == AppExecFwk::LaunchMode::SINGLETON) { + HILOG_DEBUG("called ability is common ability and singleton."); + } else { + HILOG_ERROR("called ability is not common ability or singleton."); + return RESOLVE_CALL_ABILITY_TYPE_ERR; + } + + return ERR_OK; +} + +int AbilityManagerService::SetMissionLabel(const sptr &token, const std::string &label) { HILOG_DEBUG("%{public}s", __func__); + auto missionListManager = currentMissionListManager_; + if (missionListManager) { + missionListManager->SetMissionLabel(token, label); + } + return 0; +} + +int AbilityManagerService::StartUser(int userId) +{ + HILOG_DEBUG("%{public}s, userId:%{public}d", __func__, userId); + if (userController_) { + return userController_->StartUser(userId, true); + } return 0; } int AbilityManagerService::StopUser(int userId, const sptr &callback) { HILOG_DEBUG("%{public}s", __func__); + auto ret = -1; + if (userController_) { + ret = userController_->StopUser(userId); + HILOG_DEBUG("ret = %{public}d", ret); + } if (callback) { - callback->OnStopUserDone(userId, ERR_OK); + callback->OnStopUserDone(userId, ret); + } + return 0; +} + +void AbilityManagerService::OnAcceptWantResponse( + const AAFwk::Want &want, const std::string &flag) +{ + HILOG_DEBUG("On accept want response"); + if (!currentMissionListManager_) { + return; + } + currentMissionListManager_->OnAcceptWantResponse(want, flag); +} + +void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want) +{ + return; +} +int AbilityManagerService::GetAbilityRunningInfos(std::vector &info) +{ + HILOG_DEBUG("Get running ability infos."); + auto bundleMgr = GetBundleManager(); + if (!bundleMgr) { + HILOG_ERROR("bundleMgr is nullptr."); + return INNER_ERR; + } + + auto callerUid = IPCSkeleton::GetCallingUid(); + auto isSystem = bundleMgr->CheckIsSystemAppByUid(callerUid); + HILOG_DEBUG("callerUid : %{public}d, isSystem : %{public}d", callerUid, static_cast(isSystem)); + + if (!isSystem) { + HILOG_ERROR("callar is not system app."); + return INNER_ERR; + } + + currentMissionListManager_->GetAbilityRunningInfos(info); + kernalAbilityManager_->GetAbilityRunningInfos(info); + connectManager_->GetAbilityRunningInfos(info); + dataAbilityManager_->GetAbilityRunningInfos(info); + + return ERR_OK; +} + +int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector &info) +{ + HILOG_DEBUG("Get extension infos, upperLimit : %{public}d", upperLimit); + auto bundleMgr = GetBundleManager(); + if (!bundleMgr) { + HILOG_ERROR("bundleMgr is nullptr."); + return INNER_ERR; + } + + auto callerUid = IPCSkeleton::GetCallingUid(); + auto isSystem = bundleMgr->CheckIsSystemAppByUid(callerUid); + HILOG_DEBUG("callerUid : %{public}d, isSystem : %{public}d", callerUid, static_cast(isSystem)); + + if (!isSystem) { + HILOG_ERROR("callar is not system app."); + return INNER_ERR; + } + + connectManager_->GetExtensionRunningInfos(upperLimit, info, GetUserId()); + return ERR_OK; +} + +int AbilityManagerService::GetProcessRunningInfos(std::vector &info) +{ + return DelayedSingleton::GetInstance()->GetProcessRunningInfos(info); +} + +int AbilityManagerService::GetProcessRunningInfosByUserId( + std::vector &info, int32_t userId) +{ + return DelayedSingleton::GetInstance()->GetProcessRunningInfosByUserId(info, userId); +} + +void AbilityManagerService::ClearUserData(int32_t userId) +{ + HILOG_DEBUG("%{public}s", __func__); + missionListManagers_.erase(userId); + connectManagers_.erase(userId); + dataAbilityManagers_.erase(userId); + pendingWantManagers_.erase(userId); +} + +int AbilityManagerService::RegisterSnapshotHandler(const sptr& handler) +{ + if (!currentMissionListManager_) { + HILOG_ERROR("snapshot: currentMissionListManager_ is nullptr."); + return INNER_ERR; + } + currentMissionListManager_->RegisterSnapshotHandler(handler); + HILOG_INFO("snapshot: AbilityManagerService register snapshot handler success."); + return ERR_OK; +} + +int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId, + MissionSnapshot& missionSnapshot) +{ + if (CheckIsRemote(deviceId)) { + HILOG_INFO("get remote mission snapshot."); + return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot); + } + HILOG_INFO("get local mission snapshot."); + if (!currentMissionListManager_) { + HILOG_ERROR("snapshot: currentMissionListManager_ is nullptr."); + return INNER_ERR; + } + auto token = GetAbilityTokenByMissionId(missionId); + bool result = currentMissionListManager_->GetMissionSnapshot(missionId, token, missionSnapshot); + if (!result) { + return INNER_ERR; + } + return ERR_OK; +} + +int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, + MissionSnapshot& missionSnapshot) +{ + HILOG_INFO("GetRemoteMissionSnapshotInfo begin"); + std::unique_ptr missionSnapshotPtr = std::make_unique(); + DistributedClient dmsClient; + int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr); + if (result != ERR_OK) { + HILOG_ERROR("GetRemoteMissionSnapshotInfo failed, result = %{public}d", result); + return result; + } + missionSnapshot = *missionSnapshotPtr; + return ERR_OK; +} + +void AbilityManagerService::StartFreezingScreen() +{ + HILOG_INFO("%{public}s", __func__); +} + +void AbilityManagerService::StopFreezingScreen() +{ + HILOG_INFO("%{public}s", __func__); +} + +void AbilityManagerService::UserStarted(int32_t userId) +{ + HILOG_INFO("%{public}s", __func__); + InitConnectManager(userId, false); + SetStackManager(userId, false); + InitMissionListManager(userId, false); + InitDataAbilityManager(userId, false); + InitPendWantManager(userId, false); +} + +void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId) +{ + HILOG_INFO("%{public}s, oldUserId:%{public}d, newUserId:%{public}d", __func__, oldUserId, userId); + SwitchManagers(userId); + PauseOldUser(oldUserId); + StartUserApps(userId); +} + +void AbilityManagerService::SwitchManagers(int32_t userId) +{ + HILOG_INFO("%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId); + InitConnectManager(userId, true); + SetStackManager(userId, true); + InitMissionListManager(userId, true); + InitDataAbilityManager(userId, true); + InitPendWantManager(userId, true); + HILOG_INFO("%{public}s, SwitchManagers:%{public}d-----end", __func__, userId); +} + +void AbilityManagerService::PauseOldUser(int32_t userId) +{ + HILOG_INFO("%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId); + if (useNewMission_) { + PauseOldMissionListManager(userId); + } else { + PauseOldStackManager(userId); + } + HILOG_INFO("%{public}s, PauseOldUser:%{public}d-----end", __func__, userId); +} + +void AbilityManagerService::PauseOldMissionListManager(int32_t userId) +{ + HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId); + auto it = missionListManagers_.find(userId); + if (it == missionListManagers_.end()) { + HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----end1", __func__, userId); + return; + } + auto manager = it->second; + if (!manager) { + HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----end2", __func__, userId); + return; + } + manager->PauseManager(); + HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId); +} + +void AbilityManagerService::PauseOldStackManager(int32_t userId) +{ + auto it = stackManagers_.find(userId); + if (it == stackManagers_.end()) { + return; + } + auto manager = it->second; + if (!manager) { + return; + } + manager->PauseManager(); +} + +void AbilityManagerService::StartUserApps(int32_t userId) +{ + HILOG_INFO("StartUserApps, userId:%{public}d, currentUserId:%{public}d", userId, GetUserId()); + if (useNewMission_) { + if (currentMissionListManager_ && currentMissionListManager_->IsStarted()) { + HILOG_INFO("missionListManager ResumeManager"); + currentMissionListManager_->ResumeManager(); + return; + } + } else { + if (currentStackManager_ && currentStackManager_->IsStarted()) { + HILOG_INFO("stack ResumeManager"); + currentStackManager_->ResumeManager(); + return; + } + } + StartSystemAbilityByUser(userId); +} + +void AbilityManagerService::StartSystemAbilityByUser(int32_t userId) +{ + HILOG_INFO("StartSystemAbilityByUser, userId:%{public}d, currentUserId:%{public}d", userId, GetUserId()); + ConnectBmsService(); + + if (!amsConfigResolver_ || amsConfigResolver_->NonConfigFile()) { + HILOG_INFO("start all"); + StartingLauncherAbility(); + StartingSettingsDataAbility(); + return; + } + + if (amsConfigResolver_->GetStartLauncherState()) { + HILOG_INFO("start launcher"); + StartingLauncherAbility(); + } + + if (amsConfigResolver_->GetStartSettingsDataState()) { + HILOG_INFO("start settingsdata"); + StartingSettingsDataAbility(); + } + + if (amsConfigResolver_->GetPhoneServiceState()) { + HILOG_INFO("start phone service"); + StartingPhoneServiceAbility(); + } + + if (amsConfigResolver_->GetStartContactsState()) { + HILOG_INFO("start contacts"); + StartingContactsAbility(); + } + + if (amsConfigResolver_->GetStartMmsState()) { + HILOG_INFO("start mms"); + StartingMmsAbility(); + } +} + +void AbilityManagerService::InitConnectManager(int32_t userId, bool switchUser) +{ + auto it = connectManagers_.find(userId); + if (it == connectManagers_.end()) { + auto manager = std::make_shared(); + manager->SetEventHandler(handler_); + connectManagers_.emplace(userId, manager); + if (switchUser) { + connectManager_ = manager; + } + } else { + if (switchUser) { + connectManager_ = it->second; + } + } +} + +void AbilityManagerService::InitDataAbilityManager(int32_t userId, bool switchUser) +{ + auto it = dataAbilityManagers_.find(userId); + if (it == dataAbilityManagers_.end()) { + auto manager = std::make_shared(); + dataAbilityManagers_.emplace(userId, manager); + if (switchUser) { + dataAbilityManager_ = manager; + } + } else { + if (switchUser) { + dataAbilityManager_ = it->second; + } + } +} + +void AbilityManagerService::InitPendWantManager(int32_t userId, bool switchUser) +{ + auto it = pendingWantManagers_.find(userId); + if (it == pendingWantManagers_.end()) { + auto manager = std::make_shared(); + pendingWantManagers_.emplace(userId, manager); + if (switchUser) { + pendingWantManager_ = manager; + } + } else { + if (switchUser) { + pendingWantManager_ = it->second; + } + } +} + +int32_t AbilityManagerService::GetValidUserId(const Want &want, const int32_t userId) +{ + HILOG_DEBUG("%{public}s userId = %{public}d", __func__, userId); + int32_t userIdValid = DEFAULT_INVAL_VALUE; + if (IsSystemUI(want.GetBundle())) { + HILOG_DEBUG("systemUI ability, user is default"); + return MAIN_USER_ID; + } + + if (DEFAULT_INVAL_VALUE == userId) { + userIdValid = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE; + HILOG_DEBUG("%{public}s userIdValid = %{public}d, CallingUid = %{public}d", __func__, userIdValid, + IPCSkeleton::GetCallingUid()); + } else { + userIdValid = userId; + } + return userIdValid; +} +int AbilityManagerService::SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) +{ + HILOG_DEBUG("%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest); + std::lock_guard guard(globalLock_); + abilityController_ = abilityController; + controllerIsAStabilityTest_ = imAStabilityTest; + return ERR_OK; +} + +bool AbilityManagerService::SendANRProcessID(int pid) +{ + int anrTimeOut = amsConfigResolver_->GetANRTimeOutTime(); + auto timeoutTask = [pid]() { + if (kill(pid, SIGKILL) != ERR_OK) { + HILOG_ERROR("Kill app not response process failed"); + } + }; + if (kill(pid, SIGUSR1) != ERR_OK) { + HILOG_ERROR("Send sig to app not response process failed"); } + handler_->PostTask(timeoutTask, "TIME_OUT_TASK", anrTimeOut); + return true; +} + +bool AbilityManagerService::IsRunningInStabilityTest() +{ + std::lock_guard guard(globalLock_); + bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_; + HILOG_DEBUG("%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret); + return ret; +} + +bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName) +{ + if (abilityController_ != nullptr) { + HILOG_DEBUG("%{public}s, controllerIsAStabilityTest_: %{public}d", __func__, controllerIsAStabilityTest_); + bool isStart = abilityController_->AllowAbilityStart(want, bundleName); + if (!isStart) { + HILOG_INFO("Not finishing start ability because controller starting: %{public}s", bundleName.c_str()); + return false; + } + } + return true; +} + +bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName) +{ + if (abilityController_ != nullptr) { + HILOG_DEBUG("%{public}s, controllerIsAStabilityTest_: %{public}d", __func__, controllerIsAStabilityTest_); + bool isResume = abilityController_->AllowAbilityForeground(bundleName); + if (!isResume) { + HILOG_INFO("Not finishing terminate ability because controller resuming: %{public}s", bundleName.c_str()); + return false; + } + } + return true; +} + +int32_t AbilityManagerService::InitAbilityInfoFromExtension(AppExecFwk::ExtensionAbilityInfo &extensionInfo, + AppExecFwk::AbilityInfo &abilityInfo) +{ + abilityInfo.bundleName = extensionInfo.bundleName; + abilityInfo.package = extensionInfo.moduleName; + abilityInfo.moduleName = extensionInfo.moduleName; + abilityInfo.name = extensionInfo.name; + abilityInfo.srcEntrance = extensionInfo.srcEntrance; + abilityInfo.srcPath = extensionInfo.srcEntrance; + abilityInfo.iconPath = extensionInfo.icon; + abilityInfo.iconId = extensionInfo.iconId; + abilityInfo.label = extensionInfo.label; + abilityInfo.labelId = extensionInfo.labelId; + abilityInfo.description = extensionInfo.description; + abilityInfo.descriptionId = extensionInfo.descriptionId; + abilityInfo.permissions = extensionInfo.permissions; + abilityInfo.readPermission = extensionInfo.readPermission; + abilityInfo.writePermission = extensionInfo.writePermission; + abilityInfo.extensionAbilityType = extensionInfo.type; + abilityInfo.visible = extensionInfo.visible; + abilityInfo.applicationInfo = extensionInfo.applicationInfo; + abilityInfo.resourcePath = extensionInfo.resourcePath; + abilityInfo.enabled = extensionInfo.enabled; + abilityInfo.isModuleJson = true; + abilityInfo.isStageBasedModel = true; + abilityInfo.process = extensionInfo.process; + abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; return 0; } + +int32_t AbilityManagerService::GetAbilityInfoFromExtension(const Want &want, AppExecFwk::AbilityInfo &abilityInfo) +{ + ElementName elementName = want.GetElement(); + std::string bundleName = elementName.GetBundleName(); + std::string abilityName = elementName.GetAbilityName(); + AppExecFwk::BundleMgrClient bundleClient; + AppExecFwk::BundleInfo bundleInfo; + if (!bundleClient.GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo)) { + HILOG_ERROR("Failed to get bundle info when generate ability request."); + return RESOLVE_APP_ERR; + } + bool found = false; + + for (auto &extensionInfo: bundleInfo.extensionInfos) { + if (extensionInfo.name != abilityName) { + continue; + } + found = true; + HILOG_DEBUG("GetExtensionAbilityInfo, extension ability info found, name=%{public}s", abilityName.c_str()); + abilityInfo.applicationName = bundleInfo.applicationInfo.name; + InitAbilityInfoFromExtension(extensionInfo, abilityInfo); + break; + } + + return found; +} + +int AbilityManagerService::StartUserTest(const Want &want, const sptr &observer) +{ + HILOG_DEBUG("enter"); + if (observer == nullptr) { + HILOG_ERROR("observer is nullptr"); + return ERR_INVALID_VALUE; + } + + std::string bundleName = want.GetStringParam("-p"); + if (bundleName.empty()) { + HILOG_ERROR("Invalid bundle name"); + return ERR_INVALID_VALUE; + } + + auto bms = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL); + AppExecFwk::BundleInfo bundleInfo; + if (!bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID)) { + HILOG_ERROR("Failed to get bundle info by U0_USER_ID %{public}d.", U0_USER_ID); + int32_t userId = GetUserId(); + if (!bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, GetUserId())) { + HILOG_ERROR("Failed to get bundle info by userId %{public}d.", userId); + return GET_BUNDLE_INFO_FAILED; + } + } + + int ret = KillProcess(bundleName); + if (ret) { + HILOG_ERROR("Failed to kill process."); + return ret; + } + + return DelayedSingleton::GetInstance()->StartUserTest(want, observer, bundleInfo); +} + +int AbilityManagerService::FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) +{ + HILOG_DEBUG("enter"); + int ret = KillProcess(bundleName); + if (ret) { + HILOG_ERROR("Failed to kill process."); + return ret; + } + + sptr observerProxy = iface_cast(observer); + if (!observerProxy) { + HILOG_ERROR("Failed to get ITestObserver proxy"); + return ERR_INVALID_VALUE; + } + observerProxy->TestFinished(msg, resultCode); + return ERR_OK; +} + +int AbilityManagerService::GetCurrentTopAbility(sptr &token) +{ + HILOG_DEBUG("enter"); + + auto bms = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); + + auto callerUid = IPCSkeleton::GetCallingUid(); + std::string bundleName; + auto result = bms->GetBundleNameForUid(callerUid, bundleName); + if (!result) { + HILOG_ERROR("GetBundleNameForUid fail"); + return GET_BUNDLENAME_BY_UID_FAIL; + } + + auto abilityRecord = currentMissionListManager_->GetCurrentTopAbility(bundleName); + if (!abilityRecord) { + HILOG_ERROR("Failed to get top ability"); + return ERR_INVALID_VALUE; + } + + token = abilityRecord->GetToken(); + return ERR_OK; +} + +int AbilityManagerService::DelegatorDoAbilityForeground(const sptr &token) +{ + HILOG_DEBUG("enter"); + CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); + + auto missionId = GetMissionIdByAbilityToken(token); + return DelegatorMoveMissionToFront(missionId); +} + +int AbilityManagerService::DelegatorDoAbilityBackground(const sptr &token) +{ + HILOG_DEBUG("enter"); + return MinimizeAbility(token); +} + +int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId) +{ + HILOG_INFO("enter missionId : %{public}d", missionId); + CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT); + + return currentMissionListManager_->MoveMissionToFront(missionId); +} + +int32_t AbilityManagerService::ShowPickerDialog(const Want& want, int32_t userId) +{ + auto bms = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); + HILOG_INFO("share content: ShowPickerDialog"); + std::vector abilityInfos; + bms->QueryAbilityInfos(want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, userId, abilityInfos); + return Ace::UIServiceMgrClient::GetInstance()->ShowAppPickerDialog(want, abilityInfos, userId); +} + +void AbilityManagerService::UpdateCallerInfo(Want& want) +{ + int32_t tokenId = IPCSkeleton::GetCallingTokenID(); + int32_t callerUid = IPCSkeleton::GetCallingUid(); + int32_t callerPid = IPCSkeleton::GetCallingPid(); + want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId); + want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid); + want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid); +} + +int AbilityManagerService::CheckMultiOsAccount(const int32_t userId) +{ + BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + bool isMultiOsAccountEnable = false; + AccountSA::OsAccountManager::IsMultiOsAccountEnable(isMultiOsAccountEnable); + HILOG_DEBUG("%{public}s isMultiOsAccountEnable = %{public}d", __func__, isMultiOsAccountEnable); + if (!isMultiOsAccountEnable) { + if (userId != GetUserId()) { + HILOG_ERROR("%{public}s userId(%{public}d) Unequal CurrentUserId(%{public}d).", __func__, + userId, GetUserId()); + return INVALID_USERID_VALUE; + } + } + return ERR_OK; +} + +int AbilityManagerService::GenerateAbilityRequestLocal( + const Want &want, int requestCode, AbilityRequest &request, const sptr &callerToken, int32_t &userId) +{ + BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + int result = GenerateAbilityRequest(want, requestCode, request, callerToken, userId); + if ((userId == U0_USER_ID) && (result != ERR_OK)) { + HILOG_DEBUG("Generate ability request error. But userId is 0, Use current user get."); + userId = GetUserId(); + result = GenerateAbilityRequest(want, requestCode, request, callerToken, userId); + if (result != ERR_OK) { + HILOG_ERROR("Generate ability request error. userId = %{public}d", userId); + return result; + } + } + return result; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp old mode 100755 new mode 100644 index 8f0ec348e006f7dbc60f281764cb985235cc7c9d..d9c23205e6e99b831d49e561d1bab9e4b095837a --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -31,6 +31,7 @@ AbilityManagerStub::AbilityManagerStub() { FirstStepInit(); SecondStepInit(); + ThirdStepInit(); } AbilityManagerStub::~AbilityManagerStub() @@ -67,6 +68,7 @@ void AbilityManagerStub::FirstStepInit() requestFuncMap_[DISCONNECT_ABILITY] = &AbilityManagerStub::DisconnectAbilityInner; requestFuncMap_[STOP_SERVICE_ABILITY] = &AbilityManagerStub::StopServiceAbilityInner; requestFuncMap_[DUMP_STATE] = &AbilityManagerStub::DumpStateInner; + requestFuncMap_[DUMPSYS_STATE] = &AbilityManagerStub::DumpSysStateInner; requestFuncMap_[START_ABILITY_FOR_SETTINGS] = &AbilityManagerStub::StartAbilityForSettingsInner; requestFuncMap_[CONTINUE_MISSION] = &AbilityManagerStub::ContinueMissionInner; requestFuncMap_[CONTINUE_ABILITY] = &AbilityManagerStub::ContinueAbilityInner; @@ -123,8 +125,27 @@ void AbilityManagerStub::SecondStepInit() requestFuncMap_[CLEAN_MISSION] = &AbilityManagerStub::CleanMissionInner; requestFuncMap_[CLEAN_ALL_MISSIONS] = &AbilityManagerStub::CleanAllMissionsInner; requestFuncMap_[MOVE_MISSION_TO_FRONT] = &AbilityManagerStub::MoveMissionToFrontInner; + requestFuncMap_[START_CALL_ABILITY] = &AbilityManagerStub::StartAbilityByCallInner; + requestFuncMap_[RELEASE_CALL_ABILITY] = &AbilityManagerStub::ReleaseInner; + requestFuncMap_[SET_MISSION_LABEL] = &AbilityManagerStub::SetMissionLabelInner; requestFuncMap_[START_USER] = &AbilityManagerStub::StartUserInner; requestFuncMap_[STOP_USER] = &AbilityManagerStub::StopUserInner; + requestFuncMap_[GET_ABILITY_RUNNING_INFO] = &AbilityManagerStub::GetAbilityRunningInfosInner; + requestFuncMap_[GET_EXTENSION_RUNNING_INFO] = &AbilityManagerStub::GetExtensionRunningInfosInner; + requestFuncMap_[GET_PROCESS_RUNNING_INFO] = &AbilityManagerStub::GetProcessRunningInfosInner; + requestFuncMap_[SET_ABILITY_CONTROLLER] = &AbilityManagerStub::SetAbilityControllerInner; + requestFuncMap_[GET_MISSION_SNAPSHOT_INFO] = &AbilityManagerStub::GetMissionSnapshotInfoInner; + requestFuncMap_[IS_USER_A_STABILITY_TEST] = &AbilityManagerStub::IsRunningInStabilityTestInner; + requestFuncMap_[SEND_APP_NOT_RESPONSE_PROCESS_ID] = &AbilityManagerStub::SendANRProcessIDInner; +} + +void AbilityManagerStub::ThirdStepInit() +{ + requestFuncMap_[START_USER_TEST] = &AbilityManagerStub::StartUserTestInner; + requestFuncMap_[FINISH_USER_TEST] = &AbilityManagerStub::FinishUserTestInner; + requestFuncMap_[GET_CURRENT_TOP_ABILITY] = &AbilityManagerStub::GetCurrentTopAbilityInner; + requestFuncMap_[DELEGATOR_DO_ABILITY_FOREGROUND] = &AbilityManagerStub::DelegatorDoAbilityForegroundInner; + requestFuncMap_[DELEGATOR_DO_ABILITY_BACKGROUND] = &AbilityManagerStub::DelegatorDoAbilityBackgroundInner; } int AbilityManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -403,8 +424,9 @@ int AbilityManagerStub::StartAbilityInner(MessageParcel &data, MessageParcel &re HILOG_ERROR("want is nullptr"); return ERR_INVALID_VALUE; } + int32_t userId = data.ReadInt32(); int requestCode = data.ReadInt32(); - int32_t result = StartAbility(*want, requestCode); + int32_t result = StartAbility(*want, userId, requestCode); reply.WriteInt32(result); delete want; return NO_ERROR; @@ -418,8 +440,9 @@ int AbilityManagerStub::StartAbilityAddCallerInner(MessageParcel &data, MessageP return ERR_INVALID_VALUE; } auto callerToken = data.ReadParcelable(); + int32_t userId = data.ReadInt32(); int requestCode = data.ReadInt32(); - int32_t result = StartAbility(*want, callerToken, requestCode); + int32_t result = StartAbility(*want, callerToken, userId, requestCode); reply.WriteInt32(result); delete want; return NO_ERROR; @@ -434,7 +457,8 @@ int AbilityManagerStub::ConnectAbilityInner(MessageParcel &data, MessageParcel & } auto callback = iface_cast(data.ReadParcelable()); auto token = data.ReadParcelable(); - int32_t result = ConnectAbility(*want, callback, token); + int32_t userId = data.ReadInt32(); + int32_t result = ConnectAbility(*want, callback, token, userId); reply.WriteInt32(result); delete want; return NO_ERROR; @@ -456,12 +480,34 @@ int AbilityManagerStub::StopServiceAbilityInner(MessageParcel &data, MessageParc HILOG_ERROR("want is nullptr"); return ERR_INVALID_VALUE; } - int32_t result = StopServiceAbility(*want); + int32_t userId = data.ReadInt32(); + int32_t result = StopServiceAbility(*want, userId); reply.WriteInt32(result); delete want; return NO_ERROR; } +int AbilityManagerStub::DumpSysStateInner(MessageParcel &data, MessageParcel &reply) +{ + std::vector result; + std::string args = Str16ToStr8(data.ReadString16()); + std::vector argList; + + auto isClient = data.ReadBool(); + auto isUserID = data.ReadBool(); + auto UserID = data.ReadInt32(); + SplitStr(args, " ", argList); + if (argList.empty()) { + return ERR_INVALID_VALUE; + } + DumpSysState(args, result, isClient, isUserID, UserID); + reply.WriteInt32(result.size()); + for (auto stack : result) { + reply.WriteString16(Str8ToStr16(stack)); + } + return NO_ERROR; +} + int AbilityManagerStub::DumpStateInner(MessageParcel &data, MessageParcel &reply) { std::vector result; @@ -493,8 +539,9 @@ int AbilityManagerStub::StartAbilityForSettingsInner(MessageParcel &data, Messag return ERR_INVALID_VALUE; } auto callerToken = data.ReadParcelable(); + int32_t userId = data.ReadInt32(); int requestCode = data.ReadInt32(); - int32_t result = StartAbility(*want, *abilityStartSetting, callerToken, requestCode); + int32_t result = StartAbility(*want, *abilityStartSetting, callerToken, userId, requestCode); reply.WriteInt32(result); delete want; delete abilityStartSetting; @@ -515,8 +562,9 @@ int AbilityManagerStub::StartAbilityForOptionsInner(MessageParcel &data, Message return ERR_INVALID_VALUE; } auto callerToken = data.ReadParcelable(); + int32_t userId = data.ReadInt32(); int requestCode = data.ReadInt32(); - int32_t result = StartAbility(*want, *startOptions, callerToken, requestCode); + int32_t result = StartAbility(*want, *startOptions, callerToken, userId, requestCode); reply.WriteInt32(result); delete want; delete startOptions; @@ -1097,6 +1145,52 @@ int AbilityManagerStub::MoveMissionToFrontInner(MessageParcel &data, MessageParc return NO_ERROR; } +int AbilityManagerStub::StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply) +{ + + HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner begin."); + Want *want = data.ReadParcelable(); + if (want == nullptr) { + HILOG_ERROR("want is nullptr"); + return ERR_INVALID_VALUE; + } + + auto callback = iface_cast(data.ReadParcelable()); + auto callerToken = data.ReadParcelable(); + int32_t result = StartAbilityByCall(*want, callback, callerToken); + + HILOG_DEBUG("resolve call ability ret = %d", result); + + reply.WriteInt32(result); + delete want; + + HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner end."); + + return NO_ERROR; +} + +int AbilityManagerStub::ReleaseInner(MessageParcel &data, MessageParcel &reply) +{ + auto callback = iface_cast(data.ReadParcelable()); + if (callback == nullptr) { + HILOG_ERROR("callback is nullptr"); + return ERR_INVALID_VALUE; + } + + auto element = data.ReadParcelable(); + if (element == nullptr) { + HILOG_ERROR("callback stub receive element is nullptr"); + return ERR_INVALID_VALUE; + } + int32_t result = ReleaseAbility(callback, *element); + + HILOG_DEBUG("release call ability ret = %d", result); + + reply.WriteInt32(result); + + return NO_ERROR; +} + int AbilityManagerStub::StartUserInner(MessageParcel &data, MessageParcel &reply) { int32_t userId = data.ReadInt32(); @@ -1123,6 +1217,72 @@ int AbilityManagerStub::StopUserInner(MessageParcel &data, MessageParcel &reply) return NO_ERROR; } +int AbilityManagerStub::SetMissionLabelInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + if (!token) { + HILOG_ERROR("SetMissionLabelInner read ability token failed."); + return ERR_NULL_OBJECT; + } + + std::string label = Str16ToStr8(data.ReadString16()); + int result = SetMissionLabel(token, label); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("SetMissionLabel failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int AbilityManagerStub::GetAbilityRunningInfosInner(MessageParcel &data, MessageParcel &reply) +{ + std::vector abilityRunningInfos; + auto result = GetAbilityRunningInfos(abilityRunningInfos); + reply.WriteInt32(abilityRunningInfos.size()); + for (auto &it : abilityRunningInfos) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} + +int AbilityManagerStub::GetExtensionRunningInfosInner(MessageParcel &data, MessageParcel &reply) +{ + auto upperLimit = data.ReadInt32(); + std::vector infos; + auto result = GetExtensionRunningInfos(upperLimit, infos); + reply.WriteInt32(infos.size()); + for (auto &it : infos) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} + +int AbilityManagerStub::GetProcessRunningInfosInner(MessageParcel &data, MessageParcel &reply) +{ + std::vector infos; + auto result = GetProcessRunningInfos(infos); + reply.WriteInt32(infos.size()); + for (auto &it : infos) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int AbilityManagerStub::StartSyncRemoteMissionsInner(MessageParcel &data, MessageParcel &reply) { std::string deviceId = data.ReadString(); @@ -1179,5 +1339,123 @@ int AbilityManagerStub::UnRegisterRemoteMissionListenerInner(MessageParcel &data HILOG_INFO("AbilityManagerStub: UnRegisterRemoteMissionListenerInner result = %{public}d", result); return result; } + +int AbilityManagerStub::RegisterSnapshotHandlerInner(MessageParcel &data, MessageParcel &reply) +{ + sptr handler = iface_cast(data.ReadRemoteObject()); + if (handler == nullptr) { + HILOG_ERROR("snapshot: AbilityManagerStub read snapshot handler failed!"); + return ERR_NULL_OBJECT; + } + int32_t result = RegisterSnapshotHandler(handler); + HILOG_INFO("snapshot: AbilityManagerStub register snapshot handler result = %{public}d", result); + return result; +} + +int AbilityManagerStub::GetMissionSnapshotInfoInner(MessageParcel &data, MessageParcel &reply) +{ + std::string deviceId = data.ReadString(); + int32_t missionId = data.ReadInt32(); + MissionSnapshot missionSnapshot; + int32_t result = GetMissionSnapshot(deviceId, missionId, missionSnapshot); + HILOG_INFO("snapshot: AbilityManagerStub get snapshot result = %{public}d", result); + reply.WriteParcelable(&missionSnapshot); + return result; +} + +int AbilityManagerStub::SetAbilityControllerInner(MessageParcel &data, MessageParcel &reply) +{ + sptr controller = + iface_cast(data.ReadRemoteObject()); + if (controller == nullptr) { + HILOG_ERROR("AbilityManagerStub: setAbilityControllerInner controller readParcelable failed!"); + return ERR_NULL_OBJECT; + } + bool imAStabilityTest = data.ReadBool(); + int32_t result = SetAbilityController(controller, imAStabilityTest); + HILOG_INFO("AbilityManagerStub: setAbilityControllerInner result = %{public}d", result); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("setAbilityControllerInner failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int AbilityManagerStub::IsRunningInStabilityTestInner(MessageParcel &data, MessageParcel &reply) +{ + bool result = IsRunningInStabilityTest(); + HILOG_INFO("AbilityManagerStub: IsRunningInStabilityTest result = %{public}d", result); + if (!reply.WriteBool(result)) { + HILOG_ERROR("IsRunningInStabilityTest failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int AbilityManagerStub::StartUserTestInner(MessageParcel &data, MessageParcel &reply) +{ + Want *want = data.ReadParcelable(); + if (want == nullptr) { + HILOG_ERROR("want is nullptr"); + return ERR_INVALID_VALUE; + } + auto observer = data.ReadParcelable(); + int32_t result = StartUserTest(*want, observer); + reply.WriteInt32(result); + delete want; + return result; +} + +int AbilityManagerStub::FinishUserTestInner(MessageParcel &data, MessageParcel &reply) +{ + std::string msg = data.ReadString(); + int resultCode = data.ReadInt32(); + std::string bundleName = data.ReadString(); + auto observer = data.ReadParcelable(); + int32_t result = FinishUserTest(msg, resultCode, bundleName, observer); + reply.WriteInt32(result); + return result; +} + +int AbilityManagerStub::GetCurrentTopAbilityInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token; + auto result = GetCurrentTopAbility(token); + if (!reply.WriteParcelable(token)) { + HILOG_ERROR("data write failed."); + return ERR_INVALID_VALUE; + } + reply.WriteInt32(result); + + return NO_ERROR; +} + +int AbilityManagerStub::DelegatorDoAbilityForegroundInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + auto result = DelegatorDoAbilityForeground(token); + reply.WriteInt32(result); + + return NO_ERROR; +} + +int AbilityManagerStub::DelegatorDoAbilityBackgroundInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + auto result = DelegatorDoAbilityBackground(token); + reply.WriteInt32(result); + return NO_ERROR; +} + +int AbilityManagerStub::SendANRProcessIDInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t pid = data.ReadInt32(); + bool result = SendANRProcessID(pid); + if (!reply.WriteBool(result)) { + HILOG_ERROR("reply write failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 31b20b5d7207dc2d546219bda90cb518db134a77..fc921c6b5fe6822e4b91afd2a95e051e93b435e7 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -23,7 +23,6 @@ #include "ability_scheduler_stub.h" #include "ability_util.h" #include "bytrace.h" -#include "configuration_distributor.h" #include "errors.h" #include "hilog_wrapper.h" @@ -88,6 +87,11 @@ AbilityRecord::AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &ab requestCode_(requestCode), compatibleVersion_(apiVersion) { recordId_ = abilityRecordId++; + auto abilityMgr = DelayedSingleton::GetInstance(); + if (abilityMgr) { + abilityMgr->GetMaxRestartNum(restratMax_); + } + restartCount_ = restratMax_; } AbilityRecord::~AbilityRecord() @@ -111,6 +115,7 @@ std::shared_ptr AbilityRecord::CreateAbilityRecord(const AbilityR abilityRequest.appInfo, abilityRequest.requestCode, abilityRequest.compatibleVersion); } CHECK_POINTER_AND_RETURN(abilityRecord, nullptr); + abilityRecord->SetUid(abilityRequest.uid); if (!abilityRecord->Init()) { HILOG_ERROR("failed to init new ability record"); return nullptr; @@ -119,6 +124,10 @@ std::shared_ptr AbilityRecord::CreateAbilityRecord(const AbilityR HILOG_INFO("abilityRequest.startSetting..."); abilityRecord->SetStartSetting(abilityRequest.startSetting); } + if (abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) { + HILOG_INFO("abilityRequest.callType is CALL_REQUEST_TYPE."); + abilityRecord->SetStartedByCall(true); + } return abilityRecord; } @@ -136,10 +145,20 @@ bool AbilityRecord::Init() return true; } +void AbilityRecord::SetUid(int32_t uid) +{ + uid_ = uid; +} + +int32_t AbilityRecord::GetUid() +{ + return uid_; +} + int AbilityRecord::LoadAbility() { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("%s", __func__); + HILOG_INFO("%{public}s", __func__); startTime_ = AbilityUtil::SystemTimeMillis(); CHECK_POINTER_AND_RETURN(token_, ERR_INVALID_VALUE); std::string appName = applicationInfo_.name; @@ -148,6 +167,11 @@ int AbilityRecord::LoadAbility() return ERR_INVALID_VALUE; } + if (isLauncherRoot_ && isRestarting_ && IsLauncherAbility() && (restartCount_ < 0) && IsNewVersion()) { + HILOG_ERROR("Root launcher restart is out of max count."); + return ERR_INVALID_VALUE; + } + if (abilityInfo_.type != AppExecFwk::AbilityType::DATA) { if (isKernalSystemAbility_) { SendEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, AbilityManagerService::SYSTEM_UI_TIMEOUT); @@ -284,6 +308,11 @@ AbilityState AbilityRecord::GetAbilityState() const return currentState_; } +bool AbilityRecord::IsForeground() const +{ + return currentState_ == AbilityState::FOREGROUND_NEW || currentState_ == AbilityState::FOREGROUNDING_NEW; +} + void AbilityRecord::SetAbilityState(AbilityState state) { currentState_ = state; @@ -293,6 +322,10 @@ void AbilityRecord::SetAbilityState(AbilityState state) mission->UpdateActiveTimestamp(); } } + + if (state == AbilityState::FOREGROUND_NEW) { + SetRestarting(false); + } } void AbilityRecord::SetScheduler(const sptr &scheduler) @@ -879,6 +912,51 @@ void AbilityRecord::Dump(std::vector &info) dumpInfo = " ready #" + std::to_string(isReady_) + " window attached #" + std::to_string(isWindowAttached_) + " launcher #" + std::to_string(isLauncherAbility_); info.push_back(dumpInfo); + + if (isLauncherRoot_ && IsNewVersion()) { + dumpInfo = " can restart num #" + std::to_string(restartCount_); + info.push_back(dumpInfo); + } +} + +void AbilityRecord::DumpAbilityState(std::vector &info, bool isClient) +{ + HILOG_INFO("%{public}s begin.", __func__); + std::string dumpInfo = " AbilityRecord ID #" + std::to_string(recordId_); + info.push_back(dumpInfo); + dumpInfo = " app name [" + GetAbilityInfo().applicationName + "]"; + info.push_back(dumpInfo); + dumpInfo = " main name [" + GetAbilityInfo().name + "]"; + info.push_back(dumpInfo); + dumpInfo = " bundle name [" + GetAbilityInfo().bundleName + "]"; + info.push_back(dumpInfo); + std::string typeStr; + GetAbilityTypeString(typeStr); + dumpInfo = " ability type [" + typeStr + "]"; + info.push_back(dumpInfo); + + dumpInfo = " state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + " start time [" + + std::to_string(startTime_) + "]"; + info.push_back(dumpInfo); + dumpInfo = " app state #" + AbilityRecord::ConvertAppState(appState_); + info.push_back(dumpInfo); + dumpInfo = " ready #" + std::to_string(isReady_) + " window attached #" + + std::to_string(isWindowAttached_) + " launcher #" + std::to_string(isLauncherAbility_); + info.push_back(dumpInfo); + + if (isLauncherRoot_ && IsNewVersion()) { + dumpInfo = " can restart num #" + std::to_string(restartCount_); + info.push_back(dumpInfo); + } + + // add dump client info + if (isClient && scheduler_ && isReady_) { + scheduler_->DumpAbilityInfo(info); + AppExecFwk::Configuration config; + if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { + info.emplace_back(" configuration: " + config.GetName()); + } + } } void AbilityRecord::SetStartTime() @@ -893,22 +971,30 @@ int64_t AbilityRecord::GetStartTime() const return startTime_; } -void AbilityRecord::DumpService(std::vector &info) const +void AbilityRecord::DumpService(std::vector &info, bool isClient) const { - info.emplace_back(" AbilityRecord ID #" + std::to_string(GetRecordId()) + " state #" + + info.emplace_back(" AbilityRecord ID #" + std::to_string(GetRecordId()) + " state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + " start time [" + std::to_string(GetStartTime()) + "]"); - info.emplace_back(" main name [" + GetAbilityInfo().name + "]"); - info.emplace_back(" bundle name [" + GetAbilityInfo().bundleName + "]"); - info.emplace_back(" ability type [SERVICE]"); - info.emplace_back(" app state #" + AbilityRecord::ConvertAppState(appState_)); - info.emplace_back(" Connections: " + std::to_string(connRecordList_.size())); + info.emplace_back(" main name [" + GetAbilityInfo().name + "]"); + info.emplace_back(" bundle name [" + GetAbilityInfo().bundleName + "]"); + info.emplace_back(" ability type [SERVICE]"); + info.emplace_back(" app state #" + AbilityRecord::ConvertAppState(appState_)); + info.emplace_back(" Connections: " + std::to_string(connRecordList_.size())); for (auto &&conn : connRecordList_) { if (conn) { conn->Dump(info); } } + // add dump client info + if (isClient && scheduler_ && isReady_) { + scheduler_->DumpAbilityInfo(info); + AppExecFwk::Configuration config; + if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { + info.emplace_back(" configuration: " + config.GetName()); + } + } } void AbilityRecord::GetAbilityRecordInfo(AbilityRecordInfo &recordInfo) @@ -974,6 +1060,11 @@ void AbilityRecord::OnSchedulerDied(const wptr &remote) abilityManagerService->OnAbilityDied(ability); }; handler->PostTask(task); + auto uriTask = [want = want_, ability = shared_from_this()]() { + ability->SaveResultToCallers(-1, &want); + ability->SendResultToCallers(); + }; + handler->PostTask(uriTask); } void AbilityRecord::SetConnRemoteObject(const sptr &remoteObject) @@ -1106,6 +1197,11 @@ bool AbilityRecord::GetPowerState() const void AbilityRecord::SetRestarting(const bool isRestart) { isRestarting_ = isRestart; + + if (isLauncherRoot_ && IsLauncherAbility()) { + restartCount_ = isRestart ? (--restartCount_) : restratMax_; + HILOG_INFO("root launcher restart count: %{public}d", restartCount_); + } } bool AbilityRecord::IsRestarting() const @@ -1123,21 +1219,6 @@ AppState AbilityRecord::GetAppState() const return appState_; } -void AbilityRecord::UpdateConfiguration(const AppExecFwk::Configuration &config) -{ - HILOG_INFO("%{public}s called", __FUNCTION__); - CHECK_POINTER(lifecycleDeal_); - HILOG_INFO("ability name : %{public}s | ready state : %{public}d", abilityInfo_.name.c_str(), isReady_); - if (IsReady()) { - lifecycleDeal_->UpdateConfiguration(config); - } -} - -int AbilityRecord::GetId() -{ - return GetRecordId(); -} - void AbilityRecord::ClearFlag() { isRestarting_ = false; @@ -1250,6 +1331,16 @@ int32_t AbilityRecord::GetMissionId() const return missionId_; } +void AbilityRecord::SetSpecifiedFlag(const std::string &flag) +{ + specifiedFlag_ = flag; +} + +std::string AbilityRecord::GetSpecifiedFlag() const +{ + return specifiedFlag_; +} + AbilityRecordNew::AbilityRecordNew(const Want &want, const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo, int requestCode, int32_t apiVersion) : AbilityRecord(want, abilityInfo, applicationInfo, requestCode, apiVersion) @@ -1338,6 +1429,104 @@ void AbilityRecordNew::BackgroundNew(const Closure &task) lifecycleDeal_->BackgroundNew(want_, lifeCycleStateInfo_); } +// new version --start +bool AbilityRecord::IsStartedByCall() const +{ + return isStartedByCall_; +} + +void AbilityRecord::SetStartedByCall(const bool isFlag) +{ + isStartedByCall_ = isFlag; +} + +bool AbilityRecord::IsStartToBackground() const +{ + return isStartToBackground_; +} + +void AbilityRecord::SetStartToBackground(const bool flag) +{ + isStartToBackground_ = flag; +} + +bool AbilityRecord::CallRequest() +{ + HILOG_INFO("Call Request."); + CHECK_POINTER_RETURN_BOOL(scheduler_); + CHECK_POINTER_RETURN_BOOL(callContainer_); + + // sync call request + sptr callStub = scheduler_->CallRequest(); + if (!callStub) { + HILOG_ERROR("call request failed, callstub is nullptr."); + return false; + } + + // complete call request + return callContainer_->CallRequestDone(callStub); +} + +ResolveResultType AbilityRecord::Resolve(const AbilityRequest &abilityRequest) +{ + auto callback = abilityRequest.connect; + if (abilityRequest.callType != AbilityCallType::CALL_REQUEST_TYPE || !callback) { + HILOG_ERROR("only startd by call type can create a call record."); + return ResolveResultType::NG_INNER_ERROR; + } + if (!callContainer_) { + callContainer_ = std::make_shared(); + if (!callContainer_) { + HILOG_ERROR("mark_shared error."); + return ResolveResultType::NG_INNER_ERROR; + } + } + + HILOG_DEBUG("create call record for this resolve. callerUid:%{public}d ,targetname:%{public}s", + abilityRequest.callerUid, + abilityRequest.abilityInfo.name.c_str()); + + std::shared_ptr callRecord = callContainer_->GetCallRecord(callback); + if (!callRecord) { + callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, shared_from_this(), callback, abilityRequest.callerToken); + if (!callRecord) { + HILOG_ERROR("mark_shared error."); + return ResolveResultType::NG_INNER_ERROR; + } + } + + callContainer_->AddCallRecord(callback, callRecord); + + if (callRecord->IsCallState(CallState::REQUESTED) && callRecord->GetCallStub()) { + HILOG_DEBUG("this record has requested."); + if (!callRecord->SchedulerConnectDone()) { + HILOG_DEBUG("this callrecord has requested, but callback failed."); + return ResolveResultType::NG_INNER_ERROR; + } + return ResolveResultType::OK_HAS_REMOTE_OBJ; + } + + callRecord->SetCallState(CallState::REQUESTING); + return ResolveResultType::OK_NO_REMOTE_OBJ; +} + +bool AbilityRecord::Release(const sptr & connect) +{ + HILOG_DEBUG("ability release call record by callback."); + CHECK_POINTER_RETURN_BOOL(callContainer_); + + return callContainer_->RemoveCallRecord(connect); +} + +bool AbilityRecord::IsNeedToCallRequest() const +{ + HILOG_DEBUG("ability release call record by callback."); + CHECK_POINTER_RETURN_BOOL(callContainer_); + + return callContainer_->IsNeedToCallRequest(); +} + void AbilityRecord::ContinueAbility(const std::string& deviceId) { HILOG_INFO("ContinueAbility."); @@ -1345,5 +1534,15 @@ void AbilityRecord::ContinueAbility(const std::string& deviceId) lifecycleDeal_->ContinueAbility(deviceId); } + +void AbilityRecord::SetSwitchingPause(bool state) +{ + isSwitchingPause_ = state; +} + +bool AbilityRecord::IsSwitchingPause() +{ + return isSwitchingPause_; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_running_info.cpp b/services/abilitymgr/src/ability_running_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ea5da7739c5088dfe6b3ad64009c680d5852239 --- /dev/null +++ b/services/abilitymgr/src/ability_running_info.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_running_info.h" +#include "hilog_wrapper.h" +#include "nlohmann/json.hpp" +#include "string_ex.h" + +namespace OHOS { +namespace AAFwk { +bool AbilityRunningInfo::ReadFromParcel(Parcel &parcel) +{ + std::unique_ptr abilityInfo(parcel.ReadParcelable()); + if (abilityInfo == nullptr) { + return false; + } + ability = *abilityInfo; + pid = parcel.ReadInt32(); + uid = parcel.ReadInt32(); + processName = Str16ToStr8(parcel.ReadString16()); + startTime = parcel.ReadInt64(); + abilityState = parcel.ReadInt32(); + return true; +} + +AbilityRunningInfo *AbilityRunningInfo::Unmarshalling(Parcel &parcel) +{ + AbilityRunningInfo *info = new (std::nothrow) AbilityRunningInfo(); + if (info == nullptr) { + return nullptr; + } + + if (!info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + return info; +} + +bool AbilityRunningInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(&ability)) { + return false; + } + if (!parcel.WriteInt32(pid)) { + return false; + } + if (!parcel.WriteInt32(uid)) { + return false; + } + if (!parcel.WriteString16(Str8ToStr16(processName))) { + return false; + } + if (!parcel.WriteInt64(startTime)) { + return false; + } + if (!parcel.WriteInt32(abilityState)) { + return false; + } + return true; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index b091bb8ae6ae6cb6461ed5e463b3d56ed684a48f..c95d108a3ee91392b4f3d27a6d0277e701f60079 100755 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -266,7 +266,7 @@ int AbilitySchedulerProxy::OpenFile(const Uri &uri, const std::string &mode) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_OPENFILE, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("OpenFile fail to SendRequest. err: %d", err); - return err; + return fd; } fd = reply.ReadFileDescriptor(); @@ -315,6 +315,7 @@ int AbilitySchedulerProxy::OpenRawFile(const Uri &uri, const std::string &mode) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_OPENRAWFILE, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("OpenFile fail to SendRequest. err: %d", err); + return fd; } if (!reply.ReadInt32(fd)) { @@ -358,7 +359,7 @@ int AbilitySchedulerProxy::Insert(const Uri &uri, const NativeRdb::ValuesBucket int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_INSERT, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("Insert fail to SendRequest. err: %d", err); - return err; + return index; } if (!reply.ReadInt32(index)) { @@ -408,7 +409,7 @@ int AbilitySchedulerProxy::Update(const Uri &uri, const NativeRdb::ValuesBucket int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_UPDATE, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("Update fail to SendRequest. err: %d", err); - return err; + return index; } if (!reply.ReadInt32(index)) { @@ -452,6 +453,7 @@ int AbilitySchedulerProxy::Delete(const Uri &uri, const NativeRdb::DataAbilityPr int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_DELETE, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("Delete fail to SendRequest. err: %d", err); + return index; } if (!reply.ReadInt32(index)) { @@ -533,6 +535,7 @@ std::string AbilitySchedulerProxy::GetType(const Uri &uri) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_GETTYPE, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); + return type; } type = reply.ReadString(); @@ -579,6 +582,7 @@ bool AbilitySchedulerProxy::Reload(const Uri &uri, const PacMap &extras) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_RELOAD, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); + return ret; } ret = reply.ReadBool(); @@ -631,6 +635,7 @@ int AbilitySchedulerProxy::BatchInsert(const Uri &uri, const std::vectorSendRequest(IAbilityScheduler::SCHEDULE_BATCHINSERT, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); + return ret; } if (!reply.ReadInt32(ret)) { @@ -830,6 +835,7 @@ Uri AbilitySchedulerProxy::NormalizeUri(const Uri &uri) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_NORMALIZEURI, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("NormalizeUri fail to SendRequest. err: %d", err); + return Uri(""); } std::unique_ptr info(reply.ReadParcelable()); @@ -870,6 +876,7 @@ Uri AbilitySchedulerProxy::DenormalizeUri(const Uri &uri) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_DENORMALIZEURI, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("DenormalizeUri fail to SendRequest. err: %d", err); + return Uri(""); } std::unique_ptr info(reply.ReadParcelable()); @@ -912,6 +919,7 @@ std::vector> AbilitySchedulerProx int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_EXECUTEBATCH, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("AbilitySchedulerProxy::ExecuteBatch fail to SendRequest. err: %{public}d", err); + return results; } int total = 0; @@ -972,5 +980,61 @@ void AbilitySchedulerProxy::NotifyContinuationResult(int32_t result) HILOG_ERROR("NotifyContinuationResult fail to SendRequest. err: %d", err); } } + +void AbilitySchedulerProxy::DumpAbilityInfo(std::vector &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + HILOG_ERROR("DumpAbilityRunner fail to write token"); + return; + } + + int32_t err = Remote()->SendRequest(IAbilityScheduler::DUMP_ABILITY_RUNNER_INNER, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("DumpAbilityRunner fail to SendRequest. err: %d", err); + } + + int32_t stackNum = reply.ReadInt32(); + for (int i = 0; i < stackNum; i++) { + std::string stac = Str16ToStr8(reply.ReadString16()); + info.emplace_back(stac); + } +} + +sptr AbilitySchedulerProxy::CallRequest() +{ + HILOG_INFO("AbilitySchedulerProxy::CallRequest start"); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return nullptr; + } + + int32_t err = Remote()->SendRequest(IAbilityScheduler::REQUEST_CALL_REMOTE, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("CallRequest fail to SendRequest. err: %d", err); + return nullptr; + } + + int32_t result = reply.ReadInt32(); + if (result != ERR_OK) { + HILOG_ERROR("CallRequest failed, err %{public}d", result); + return nullptr; + } + + auto call = reply.ReadParcelable(); + if (!call) { + HILOG_ERROR("CallRequest error"); + return nullptr; + } + + HILOG_INFO("AbilitySchedulerProxy::CallRequest end"); + return call; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index aa0e77742307ecbca28c90cc7e6b6ee391eab373..e72008a219afa220a12a33610a3d42095d322274 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -58,7 +58,9 @@ AbilitySchedulerStub::AbilitySchedulerStub() requestFuncMap_[SCHEDULE_EXECUTEBATCH] = &AbilitySchedulerStub::ExecuteBatchInner; requestFuncMap_[TOP_ACTIVE_ABILITY_CHANGED] = &AbilitySchedulerStub::TopActiveAbilityChangedInner; requestFuncMap_[NOTIFY_CONTINUATION_RESULT] = &AbilitySchedulerStub::NotifyContinuationResultInner; + requestFuncMap_[REQUEST_CALL_REMOTE] = &AbilitySchedulerStub::CallRequestInner; requestFuncMap_[CONTINUE_ABILITY] = &AbilitySchedulerStub::ContinueAbilityInner; + requestFuncMap_[DUMP_ABILITY_RUNNER_INNER] = &AbilitySchedulerStub::DumpAbilityInfoInner; } AbilitySchedulerStub::~AbilitySchedulerStub() @@ -203,6 +205,10 @@ int AbilitySchedulerStub::OpenFileInner(MessageParcel &data, MessageParcel &repl return ERR_INVALID_VALUE; } int fd = OpenFile(*uri, mode); + if (fd < 0) { + HILOG_ERROR("OpenFile fail, fd is %{pubilc}d", fd); + return ERR_INVALID_VALUE; + } if (!reply.WriteFileDescriptor(fd)) { HILOG_ERROR("fail to WriteFileDescriptor fd"); return ERR_INVALID_VALUE; @@ -572,6 +578,49 @@ int AbilitySchedulerStub::NotifyContinuationResultInner(MessageParcel &data, Mes return NO_ERROR; } +int AbilitySchedulerStub::DumpAbilityInfoInner(MessageParcel &data, MessageParcel &reply) +{ + + std::vector infos; + + DumpAbilityInfo(infos); + + for (const auto & infostep:infos) { + HILOG_INFO("DumpAbilityInfoInner infos = %{public}s", infostep.c_str()); + } + + reply.WriteInt32(infos.size()); + for (auto stack : infos) { + reply.WriteString16(Str8ToStr16(stack)); + } + + return NO_ERROR; +} +int AbilitySchedulerStub::CallRequestInner(MessageParcel &data, MessageParcel &reply) +{ + HILOG_INFO("AbilitySchedulerStub::CallRequestInner start"); + + sptr call = CallRequest(); + if (!call) { + HILOG_ERROR("call request return nullptr."); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteInt32(NO_ERROR)) { + HILOG_ERROR("GetAllStackInfo result error"); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteParcelable(call)) { + HILOG_ERROR("call request write failed."); + return ERR_INVALID_VALUE; + } + + HILOG_INFO("AbilitySchedulerStub::CallRequestInner end"); + + return NO_ERROR; +} + void AbilitySchedulerRecipient::OnRemoteDied(const wptr &remote) { HILOG_ERROR("recv AbilitySchedulerRecipient death notice"); diff --git a/services/abilitymgr/src/ability_stack_manager.cpp b/services/abilitymgr/src/ability_stack_manager.cpp index a40e31ddad79ecfeb6f7696516e5d07da1bcb6d8..2ffbcc83a8946f7f10bba1d7a41f24667eafd4e4 100644 --- a/services/abilitymgr/src/ability_stack_manager.cpp +++ b/services/abilitymgr/src/ability_stack_manager.cpp @@ -82,7 +82,7 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) bool result = whiteList->FindBundleNameOnWhiteList(abilityRequest.abilityInfo.bundleName, isAwakenScreen); whiteList.reset(); if (!result) { - HILOG_DEBUG("the ability is not on the white list..."); + HILOG_ERROR("the ability is not on the white list..."); return START_ABILITY_NOT_ONTHE_WHITELIST; } } @@ -90,6 +90,7 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) auto currentTopAbilityRecord = GetCurrentTopAbility(); if (!CanStartInLockMissionState(abilityRequest, currentTopAbilityRecord)) { SendUnlockMissionMessage(); + HILOG_ERROR("the ability can not start InLockMissionState"); return LOCK_MISSION_STATE_DENY_REQUEST; } @@ -103,7 +104,9 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) } if (!waittingAbilityQueue_.empty()) { - HILOG_INFO("Waiting queue is not empty, so enqueue ability for waiting."); + auto top = waittingAbilityQueue_.front().abilityInfo.name; + HILOG_INFO("Waiting queue not empty(%{public}s), enqueue(%{public}s) for waiting.", + top.c_str(), abilityRequest.abilityInfo.name.c_str()); EnqueueWaittingAbility(abilityRequest); return START_ABILITY_WAITING; } @@ -113,7 +116,8 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) HILOG_DEBUG("current top: %{public}s", element.c_str()); auto targetState = currentTopAbilityRecord->IsNewVersion() ? FOREGROUND_NEW : ACTIVE; if (currentTopAbilityRecord->GetAbilityState() != targetState) { - HILOG_INFO("Top ability is not active, so enqueue ability for waiting."); + HILOG_INFO("Top ability is not active(%{public}s), enqueue(%{public}s) for waiting.", + currentTopAbilityRecord->GetAbilityInfo().name.c_str(), abilityRequest.abilityInfo.name.c_str()); EnqueueWaittingAbility(abilityRequest); return START_ABILITY_WAITING; } @@ -134,7 +138,8 @@ int AbilityStackManager::StartAbilityLocked( } else { auto lockTopAbilityRecord = lockScreenMissionStack_->GetTopAbilityRecord(); if (lockTopAbilityRecord && lockTopAbilityRecord->GetAbilityState() != ACTIVE) { - HILOG_INFO("lock screen stack top ability is not active, so enqueue ability for waiting."); + HILOG_INFO("lock screen stack top ability not active(%{public}s), enqueue(%{public}s) for waiting.", + lockTopAbilityRecord->GetAbilityInfo().name.c_str(), abilityRequest.abilityInfo.name.c_str()); EnqueueWaittingAbility(abilityRequest); return START_ABILITY_WAITING; } @@ -145,14 +150,14 @@ int AbilityStackManager::StartAbilityLocked( if (abilityRequest.startSetting && !abilityRequest.abilityInfo.applicationInfo.isLauncherApp) { auto windowkey = static_cast( std::atoi(abilityRequest.startSetting->GetProperty(AbilityStartSetting::WINDOW_MODE_KEY).c_str())); - HILOG_DEBUG("Start ability with settings ..."); if (windowkey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING || windowkey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY || windowkey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) { + HILOG_INFO("Start ability AsMultiWindow: %{public}d", windowkey); return StartAbilityAsMultiWindowLocked(currentTopAbility, abilityRequest); } } - + HILOG_INFO("Start ability AsDefault."); return StartAbilityAsDefaultLocked(currentTopAbility, abilityRequest); } @@ -188,11 +193,11 @@ int AbilityStackManager::StartAbilityAsDefaultLocked( // 4. start processing ability lifecycle if (currentTopAbility == nullptr) { - // top ability is null, then launch the first Ability. + HILOG_INFO("top ability is null, then launch the first Ability."); targetAbilityRecord->SetLauncherRoot(); return targetAbilityRecord->LoadAbility(); } else { - // complete ability background if needed. + HILOG_INFO("top ability not null, complete ability background if needed."); return StartAbilityLifeCycle(lastTopAbility, currentTopAbility, targetAbilityRecord); } } @@ -646,7 +651,8 @@ int AbilityStackManager::TerminateAbilityLocked(std::list &t ability->SendResultToCallers(); MoveToBackgroundTask(ability); } - if (ability->IsAbilityState(AbilityState::BACKGROUND)) { + if (ability->IsAbilityState(AbilityState::BACKGROUND) || + ability->IsAbilityState(AbilityState::BACKGROUND_NEW)) { // ability on background, remove AbilityRecord out of stack and then schedule to terminate. RemoveTerminatingAbility(ability, lastActiveAbility); ability->SendResultToCallers(); @@ -1411,8 +1417,14 @@ void AbilityStackManager::OnAppStateChanged(const AppInfo &info) if (!ability) { continue; } - if (ability->GetApplicationInfo().name == info.appName && - (info.processName == ability->GetAbilityInfo().process || + auto appName = ability->GetApplicationInfo().name; + auto uid = ability->GetAbilityInfo().applicationInfo.uid; + auto isExist = [&appName, &uid](const AppData &appData) { + return appData.appName == appName && appData.uid == uid; + }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + + if (iter != info.appData.end() && (info.processName == ability->GetAbilityInfo().process || info.processName == ability->GetApplicationInfo().bundleName)) { ability->SetAppState(info.state); } @@ -1436,7 +1448,14 @@ void AbilityStackManager::OnAppStateChanged(const AppInfo &info) continue; } - if (ability->GetApplicationInfo().name == info.appName && + auto appName = ability->GetApplicationInfo().name; + auto uid = ability->GetAbilityInfo().applicationInfo.uid; + auto isExist = [&appName, &uid](const AppData &appData) { + return appData.appName == appName && appData.uid == uid; + }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + + if (iter != info.appData.end() && (info.processName == ability->GetAbilityInfo().process || info.processName == ability->GetApplicationInfo().bundleName)) { ability->SetAppState(info.state); @@ -1481,7 +1500,8 @@ void AbilityStackManager::CompleteActive(const std::shared_ptr &a DelayedSingleton::GetInstance()->NotifyBmsAbilityLifeStatus( abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name, - AbilityUtil::UTCTimeSeconds()); + AbilityUtil::UTCTimeSeconds(), + abilityRecord->GetApplicationInfo().uid); #if BINDER_IPC_32BIT HILOG_INFO("notify bms ability life status, bundle name:%{public}s, ability name:%{public}s, time:%{public}lld", abilityRecord->GetAbilityInfo().bundleName.c_str(), @@ -1629,6 +1649,12 @@ void AbilityStackManager::CompleteInactive(const std::shared_ptr HILOG_INFO("ability: %{public}s", element.c_str()); abilityRecord->SetAbilityState(AbilityState::INACTIVE); + if (abilityRecord->IsSwitchingPause()) { + MoveToBackgroundTask(abilityRecord); + abilityRecord->SetSwitchingPause(false); + return; + } + // 0. multi window moving , complete lifecycle. if (abilityRecord->GetInMovingState()) { if (abilityRecord == GetCurrentTopAbility()) { @@ -2831,7 +2857,7 @@ void AbilityStackManager::UninstallApp(const std::string &bundleName) CHECK_POINTER(abilityManagerService); auto handler = abilityManagerService->GetEventHandler(); CHECK_POINTER(handler); - auto task = [bundleName, this]() { AddUninstallTags(bundleName); }; + auto task = [bundleName, self = shared_from_this()]() { self->AddUninstallTags(bundleName); }; handler->PostTask(task); } @@ -2913,6 +2939,7 @@ void AbilityStackManager::OnTimeOut(uint32_t msgId, int64_t eventId) auto abilityRecord = GetAbilityRecordByEventId(eventId); if (abilityRecord == nullptr) { HILOG_ERROR("stack manager on time out event: ability record is nullptr."); + BackToLauncher(); return; } @@ -4418,7 +4445,7 @@ int AbilityStackManager::GetMissionSnapshot(int32_t missionId, MissionPixelMap & CHECK_POINTER_AND_RETURN_LOG(topAbilityRecord, REMOVE_MISSION_ID_NOT_EXIST, "top ability is invalid."); auto windowInfo = topAbilityRecord->GetWindowInfo(); int windowID = 0; - if(windowInfo){ + if (windowInfo) { windowID = windowInfo->windowToken_; HILOG_INFO("windowID is %{public}d", windowID); } @@ -4686,6 +4713,12 @@ void AbilityStackManager::CompleteInactiveByNewVersion(const std::shared_ptr guard(stackLock_); + if (abilityRecord->IsSwitchingPause()) { + MoveToBackgroundTask(abilityRecord); + abilityRecord->SetSwitchingPause(false); + return; + } + // 1. it may be inactive callback of terminate ability. if (abilityRecord->IsTerminating()) { abilityRecord->SendResultToCallers(); @@ -4711,6 +4744,11 @@ void AbilityStackManager::CompleteInactiveByNewVersion(const std::shared_ptrIsSwitchingPause()) { + MoveToBackgroundTask(abilityRecord); + return; + } + std::string element = abilityRecord->GetWant().GetElement().GetURI(); HILOG_INFO("ability: %{public}s", element.c_str()); @@ -4757,7 +4795,8 @@ void AbilityStackManager::CompleteForegroundNew(const std::shared_ptr::GetInstance()->NotifyBmsAbilityLifeStatus( abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name, - AbilityUtil::UTCTimeSeconds()); + AbilityUtil::UTCTimeSeconds(), + abilityRecord->GetApplicationInfo().uid); #if BINDER_IPC_32BIT HILOG_INFO("notify bms ability life status, bundle name:%{public}s, ability name:%{public}s, time:%{public}lld", abilityRecord->GetAbilityInfo().bundleName.c_str(), @@ -4897,5 +4936,37 @@ void AbilityStackManager::CompleteBackgroundNew(const std::shared_ptrTerminate(timeoutTask); } } + +bool AbilityStackManager::IsStarted() +{ + std::lock_guard guard(stackLock_); + auto lanucherRoot = GetLauncherRootAbility(); + return lanucherRoot != nullptr; +} + +void AbilityStackManager::PauseManager() +{ + HILOG_INFO("PauseManager."); + std::lock_guard guard(stackLock_); + auto currentTopAbility = GetCurrentTopAbility(); + if (!currentTopAbility) { + HILOG_WARN("get top ability failed."); + return; + } + + currentTopAbility->SetSwitchingPause(true); + if (currentTopAbility->IsAbilityState(AbilityState::ACTIVE)) { + currentTopAbility->ProcessInactivate(); + } + if (currentTopAbility->IsAbilityState(AbilityState::INACTIVE)) { + MoveToBackgroundTask(currentTopAbility); + } +} + +void AbilityStackManager::ResumeManager() +{ + HILOG_INFO("ResumeManager, back to launcher."); + BackToLauncher(); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ams_configuration_parameter.cpp b/services/abilitymgr/src/ams_configuration_parameter.cpp index 0c132a94d5ea930f254e4cc7d8b37495b732d8aa..49d1ef168c43031354791c275e77ca5aeb68b655 100644 --- a/services/abilitymgr/src/ams_configuration_parameter.cpp +++ b/services/abilitymgr/src/ams_configuration_parameter.cpp @@ -82,6 +82,21 @@ bool AmsConfigurationParameter::IsUseNewMission() const return useNewMission_; } +int AmsConfigurationParameter::GetANRTimeOutTime() const +{ + return anrTime_; +} + +int AmsConfigurationParameter::GetAMSTimeOutTime() const +{ + return amsTime_; +} + +int AmsConfigurationParameter::GetMaxRestartNum() const +{ + return maxRestartNum_; +} + int AmsConfigurationParameter::LoadAmsConfiguration(const std::string &filePath) { HILOG_DEBUG("%{public}s", __func__); @@ -142,9 +157,14 @@ int AmsConfigurationParameter::LoadAppConfigurationForStartUpService(nlohmann::j canStartContacts = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::STARTUP_CONTACTS).get(); canStartMms = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::STARTUP_MMS).get(); missionSaveTime_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::MISSION_SAVE_TIME).get(); + anrTime_ = + Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::APP_NOT_RESPONSE_PROCESS_TIMEOUT_TIME).get(); + amsTime_ = + Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::AMS_TIMEOUT_TIME).get(); if (Object.at(AmsConfig::SERVICE_ITEM_AMS).contains(AmsConfig::USE_NEW_MISSION)) { useNewMission_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::USE_NEW_MISSION).get(); } + maxRestartNum_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::ROOT_LAUNCHER_RESTART_MAX).get(); HILOG_INFO("get ams service config succes!"); ret = 0; } diff --git a/services/abilitymgr/src/app_scheduler.cpp b/services/abilitymgr/src/app_scheduler.cpp index 7a6b868ad66eaaca594474a60245f28eac17425e..e047ef049f228babb666226ec7fbb06a74221c94 100644 --- a/services/abilitymgr/src/app_scheduler.cpp +++ b/services/abilitymgr/src/app_scheduler.cpp @@ -16,6 +16,7 @@ #include "app_scheduler.h" #include "ability_manager_errors.h" +#include "ability_manager_service.h" #include "ability_record.h" #include "ability_util.h" #include "appmgr/app_mgr_constants.h" @@ -24,6 +25,15 @@ namespace OHOS { namespace AAFwk { +const std::map appStateToStrMap_ = { + std::map::value_type(AppState::BEGIN, "BEGIN"), + std::map::value_type(AppState::READY, "READY"), + std::map::value_type(AppState::FOREGROUND, "FOREGROUND"), + std::map::value_type(AppState::BACKGROUND, "BACKGROUND"), + std::map::value_type(AppState::SUSPENDED, "SUSPENDED"), + std::map::value_type(AppState::TERMINATED, "TERMINATED"), + std::map::value_type(AppState::END, "END"), +}; AppScheduler::AppScheduler() : appMgrClient_(std::make_unique()) {} @@ -35,6 +45,11 @@ bool AppScheduler::Init(const std::weak_ptr &callback) CHECK_POINTER_RETURN_BOOL(callback.lock()); CHECK_POINTER_RETURN_BOOL(appMgrClient_); + std::lock_guard guard(lock_); + if (isInit_) { + return true; + } + callback_ = callback; /* because the errcode type of AppMgr Client API will be changed to int, * so must to covert the return result */ @@ -49,7 +64,12 @@ bool AppScheduler::Init(const std::weak_ptr &callback) HILOG_ERROR("failed to RegisterAppStateCallback"); return false; } + + startSpecifiedAbilityResponse_ = new (std::nothrow) StartSpecifiedAbilityResponse(); + appMgrClient_->RegisterStartSpecifiedAbilityResponse(startSpecifiedAbilityResponse_); + HILOG_INFO("success to ConnectAppMgrService"); + isInit_ = true; return true; } @@ -113,7 +133,6 @@ void AppScheduler::UpdateExtensionState(const sptr &token, const appMgrClient_->UpdateExtensionState(token, state); } - void AppScheduler::AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) { @@ -129,6 +148,13 @@ void AppScheduler::KillProcessByAbilityToken(const sptr &token) appMgrClient_->KillProcessByAbilityToken(token); } +void AppScheduler::KillProcessesByUserId(int32_t userId) +{ + HILOG_DEBUG("Kill process by user id."); + CHECK_POINTER(appMgrClient_); + appMgrClient_->KillProcessesByUserId(userId); +} + AppAbilityState AppScheduler::ConvertToAppAbilityState(const int32_t state) { AppExecFwk::AbilityState abilityState = static_cast(state); @@ -213,9 +239,13 @@ void AppScheduler::OnAppStateChanged(const AppExecFwk::AppProcessData &appData) auto callback = callback_.lock(); CHECK_POINTER(callback); AppInfo info; - info.appName = appData.appName; + for (const auto &list : appData.appDatas) { + AppData data; + data.appName = list.appName; + data.uid = list.uid; + info.appData.push_back(data); + } info.processName = appData.processName; - info.uid = appData.uid; info.state = static_cast(appData.appState); callback->OnAppStateChanged(info); } @@ -226,10 +256,89 @@ void AppScheduler::GetSystemMemoryAttr(AppExecFwk::SystemMemoryAttr &memoryInfo, appMgrClient_->GetSystemMemoryAttr(memoryInfo, strConfig); } +void AppScheduler::GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) +{ + CHECK_POINTER(appMgrClient_); + appMgrClient_->GetRunningProcessInfoByToken(token, info); +} + void AppScheduler::StartupResidentProcess() { CHECK_POINTER(appMgrClient_); appMgrClient_->StartupResidentProcess(); } + +void AppScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +{ + CHECK_POINTER(appMgrClient_); + appMgrClient_->StartSpecifiedAbility(want, abilityInfo); +} + +void StartSpecifiedAbilityResponse::OnAcceptWantResponse( + const AAFwk::Want &want, const std::string &flag) +{ + DelayedSingleton::GetInstance()->OnAcceptWantResponse(want, flag); +} + +void StartSpecifiedAbilityResponse::OnTimeoutResponse(const AAFwk::Want &want) +{ + DelayedSingleton::GetInstance()->OnStartSpecifiedAbilityTimeoutResponse(want); +} +int AppScheduler::GetProcessRunningInfos(std::vector &info) +{ + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + return static_cast(appMgrClient_->GetAllRunningProcesses(info)); +} + +int AppScheduler::GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) +{ + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + return static_cast(appMgrClient_->GetProcessRunningInfosByUserId(info, userId)); +} + +std::string AppScheduler::ConvertAppState(const AppState &state) +{ + auto it = appStateToStrMap_.find(state); + if (it != appStateToStrMap_.end()) { + return it->second; + } + return "INVALIDSTATE"; +} + +int AppScheduler::StartUserTest(const Want &want, const sptr &observer, + const AppExecFwk::BundleInfo &bundleInfo) +{ + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + int ret = appMgrClient_->StartUserTestProcess(want, observer, bundleInfo); + if (ret != ERR_OK) { + HILOG_ERROR("Fail to start user test."); + return INNER_ERR; + } + return ERR_OK; +} + +int AppScheduler::UpdateConfiguration(const AppExecFwk::Configuration &config) +{ + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + auto ret = static_cast(appMgrClient_->UpdateConfiguration(config)); + if (ret != ERR_OK) { + HILOG_ERROR("UpdateConfiguration failed."); + return INNER_ERR; + } + + return ERR_OK; +} + +int AppScheduler::GetConfiguration(AppExecFwk::Configuration &config) +{ + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + auto ret = static_cast(appMgrClient_->GetConfiguration(config)); + if (ret != ERR_OK) { + HILOG_ERROR("GetConfiguration failed."); + return INNER_ERR; + } + + return ERR_OK; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/call_container.cpp b/services/abilitymgr/src/call_container.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5782444019f58ba715e1cc91b7ac57984e0120ad --- /dev/null +++ b/services/abilitymgr/src/call_container.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "call_container.h" + +#include "hilog_wrapper.h" +#include "ability_manager_errors.h" +#include "ability_connect_callback_stub.h" +#include "ability_util.h" +#include "ability_event_handler.h" +#include "ability_manager_service.h" + +namespace OHOS { +namespace AAFwk { +CallContainer::CallContainer() +{} + +CallContainer::~CallContainer() +{ + std::for_each(deathRecipientMap_.begin(), + deathRecipientMap_.end(), + [&](RecipientMapType::reference recipient) { + recipient.first->RemoveDeathRecipient(recipient.second); + }); + + deathRecipientMap_.clear(); + callRecordMap_.clear(); +} + +void CallContainer::AddCallRecord(const sptr & connect, + const std::shared_ptr& callRecord) +{ + CHECK_POINTER(callRecord); + CHECK_POINTER(connect); + CHECK_POINTER(connect->AsObject()); + + auto iter = callRecordMap_.find(connect->AsObject()); + if (iter != callRecordMap_.end()) { + RemoveConnectDeathRecipient(connect); + callRecordMap_.erase(callRecordMap_.find(connect->AsObject())); + } + + AddConnectDeathRecipient(connect); + callRecord->SetConCallBack(connect); + callRecordMap_.emplace(connect->AsObject(), callRecord); + + HILOG_DEBUG("Add call record to callcontainer, target: %{public}s", + callRecord->GetTargetServiceName().GetURI().c_str()); +} + +std::shared_ptr CallContainer::GetCallRecord(const sptr & connect) const +{ + CHECK_POINTER_AND_RETURN(connect, nullptr); + CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr); + + auto mapIter = callRecordMap_.find(connect->AsObject()); + if (mapIter != callRecordMap_.end()) { + return mapIter->second; + } + + return nullptr; +} + +bool CallContainer::RemoveCallRecord(const sptr & connect) +{ + HILOG_DEBUG("call container release call record by callback."); + CHECK_POINTER_AND_RETURN(connect, nullptr); + CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr); + + auto iter = callRecordMap_.find(connect->AsObject()); + if (iter != callRecordMap_.end()) { + auto callrecord = iter->second; + if (callrecord) { + callrecord->SchedulerDisConnectDone(); + } + RemoveConnectDeathRecipient(connect); + callRecordMap_.erase(callRecordMap_.find(connect->AsObject())); + HILOG_DEBUG("remove call record is success."); + return true; + } + + if (callRecordMap_.empty()) { + // notify soft resouce service. + HILOG_DEBUG("this ability has no callrecord."); + } + + HILOG_WARN("remove call record is not exist."); + return false; +} + +void CallContainer::OnConnectionDied(const wptr & remote) +{ + HILOG_WARN("Call back is died."); + auto object = remote.promote(); + CHECK_POINTER(object); + + std::shared_ptr callRecord = nullptr; + auto mapIter = callRecordMap_.find(object); + if (mapIter != callRecordMap_.end()) { + callRecord = mapIter->second; + } + + auto abilityManagerService = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityManagerService); + auto handler = abilityManagerService->GetEventHandler(); + CHECK_POINTER(handler); + auto task = [abilityManagerService, callRecord]() { + abilityManagerService->OnCallConnectDied(callRecord); + }; + handler->PostTask(task); +} + +bool CallContainer::CallRequestDone(const sptr & callStub) +{ + HILOG_INFO("Call Request Done start."); + + CHECK_POINTER_AND_RETURN(callStub, false); + + std::for_each(callRecordMap_.begin(), + callRecordMap_.end(), + [&callStub](CallMapType::reference service) { + std::shared_ptr callRecord = service.second; + if (callRecord && callRecord->IsCallState(CallState::REQUESTING)) { + callRecord->SetCallStub(callStub); + callRecord->SchedulerConnectDone(); + } + }); + + HILOG_INFO("Call Request Done end."); + return true; +} + +void CallContainer::Dump(std::vector &info, const std::string &args) const +{ + HILOG_INFO("Dump call records."); +} + +bool CallContainer::IsNeedToCallRequest() const +{ + for (auto &iter : callRecordMap_) { + auto callRecord = iter.second; + if (callRecord && !callRecord->IsCallState(CallState::REQUESTED)) { + return true; + } + } + return false; +} + +void CallContainer::AddConnectDeathRecipient(const sptr &connect) +{ + CHECK_POINTER(connect); + CHECK_POINTER(connect->AsObject()); + auto it = deathRecipientMap_.find(connect->AsObject()); + if (it != deathRecipientMap_.end()) { + HILOG_ERROR("This death recipient has been added."); + return; + } else { + sptr deathRecipient = new AbilityConnectCallbackRecipient( + std::bind(&CallContainer::OnConnectionDied, this, std::placeholders::_1)); + connect->AsObject()->AddDeathRecipient(deathRecipient); + deathRecipientMap_.emplace(connect->AsObject(), deathRecipient); + } +} + +void CallContainer::RemoveConnectDeathRecipient(const sptr &connect) +{ + CHECK_POINTER(connect); + CHECK_POINTER(connect->AsObject()); + auto it = deathRecipientMap_.find(connect->AsObject()); + if (it != deathRecipientMap_.end()) { + it->first->RemoveDeathRecipient(it->second); + deathRecipientMap_.erase(it); + return; + } +} +} // namespace AAFwk +} // namesspace OHOS diff --git a/services/abilitymgr/src/call_record.cpp b/services/abilitymgr/src/call_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59098ac815b03a8e4a2348935a3426370faea306 --- /dev/null +++ b/services/abilitymgr/src/call_record.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "call_record.h" + +#include "hilog_wrapper.h" +#include "ability_util.h" +#include "ability_event_handler.h" +#include "ability_manager_service.h" +#include "ability_record.h" +#include "element_name.h" + +namespace OHOS { +namespace AAFwk { +int64_t CallRecord::callRecordId = 0; + +CallRecord::CallRecord(const int32_t callerUid, const std::shared_ptr &targetService, + const sptr &connCallback, const sptr &callToken) + : callerUid_(callerUid), + state_(CallState::INIT), + service_(targetService), + connCallback_(connCallback), + callerToken_(callToken) +{ + recordId_ = callRecordId++; + startTime_ = AbilityUtil::SystemTimeMillis(); +} + +CallRecord::~CallRecord() +{ + if (callRemoteObject_ && callDeathRecipient_) { + callRemoteObject_->RemoveDeathRecipient(callDeathRecipient_); + } +} + +std::shared_ptr CallRecord::CreateCallRecord(const int32_t callerUid, + const std::shared_ptr &targetService, const sptr &connCallback, + const sptr &callToken) +{ + auto callRecord = std::make_shared(callerUid, targetService, connCallback, callToken); + CHECK_POINTER_AND_RETURN(callRecord, nullptr); + callRecord->SetCallState(CallState::INIT); + return callRecord; +} + +void CallRecord::SetCallStub(const sptr & call) +{ + CHECK_POINTER(call); + + callRemoteObject_ = call; + + HILOG_DEBUG("SetCallStub complete."); + + if (callDeathRecipient_ == nullptr) { + callDeathRecipient_ = + new AbilityCallRecipient(std::bind(&CallRecord::OnCallStubDied, this, std::placeholders::_1)); + } + + callRemoteObject_->AddDeathRecipient(callDeathRecipient_); +} + +sptr CallRecord::GetCallStub() +{ + return callRemoteObject_; +} + +void CallRecord::SetConCallBack(const sptr &connCallback) +{ + connCallback_ = connCallback; +} + +sptr CallRecord::GetConCallBack() const +{ + return connCallback_; +} + +AppExecFwk::ElementName CallRecord::GetTargetServiceName() const +{ + std::shared_ptr tmpService = service_.lock(); + if (tmpService) { + const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); + AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); + return element; + } + return AppExecFwk::ElementName(); +} + +sptr CallRecord::GetCallerToken() const +{ + return callerToken_; +} + +bool CallRecord::SchedulerConnectDone() +{ + HILOG_DEBUG("Scheduler Connect Done by callback. id:%{public}d", recordId_); + std::shared_ptr tmpService = service_.lock(); + if (!callRemoteObject_ || !connCallback_ || !tmpService) { + HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done."); + return false; + } + + const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); + AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); + connCallback_->OnAbilityConnectDone(element, callRemoteObject_, ERR_OK); + state_ = CallState::REQUESTED; + + HILOG_DEBUG("element: %{public}s, result: %{public}d. connectstate:%{public}d.", element.GetURI().c_str(), + ERR_OK, state_); + return true; +} + +bool CallRecord::SchedulerDisConnectDone() +{ + HILOG_DEBUG("Scheduler disconnect Done by callback. id:%{public}d", recordId_); + std::shared_ptr tmpService = service_.lock(); + if (!connCallback_ || !tmpService) { + HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done."); + return false; + } + + const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); + AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); + connCallback_->OnAbilityDisconnectDone(element, ERR_OK); + + return true; +} + +void CallRecord::OnCallStubDied(const wptr & remote) +{ + HILOG_WARN("callstub is died. id:%{public}d", recordId_); + auto object = remote.promote(); + CHECK_POINTER(object); + + auto abilityManagerService = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityManagerService); + auto handler = abilityManagerService->GetEventHandler(); + CHECK_POINTER(handler); + auto task = [abilityManagerService, callRecord = shared_from_this()]() { + abilityManagerService->OnCallConnectDied(callRecord); + }; + handler->PostTask(task); +} + +void CallRecord::Dump(std::vector &info) const +{ + HILOG_DEBUG("CallRecord::Dump is called"); +} + +int32_t CallRecord::GetCallerUid() const +{ + return callerUid_; +} + +bool CallRecord::IsCallState(const CallState& state) const +{ + return (state_ == state); +} + +void CallRecord::SetCallState(const CallState& state) +{ + state_ = state; +} + +int CallRecord::GetCallRecordId() const +{ + return recordId_; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/configuration_distributor.cpp b/services/abilitymgr/src/configuration_distributor.cpp deleted file mode 100644 index 8f0a88e8e6d6f34175a62ab2caa5f15bb9730dab..0000000000000000000000000000000000000000 --- a/services/abilitymgr/src/configuration_distributor.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "configuration_distributor.h" -#include "hilog_wrapper.h" - -namespace OHOS { -namespace AAFwk { -ConfigurationDistributor::ConfigurationDistributor() -{} - -ConfigurationDistributor::~ConfigurationDistributor() -{ - if (!observerList_.empty()) { - for (auto &iter : observerList_) { - iter.reset(); - } - } -} - -void ConfigurationDistributor::Atach(const std::weak_ptr &ob) -{ - std::lock_guard lock(configLock_); - if (ob.expired()) { - HILOG_INFO("Atach ob is null"); - return; - } - auto ability = ob.lock(); - int id = ability->GetId(); - HILOG_INFO("Atach ob id[%{public}d]", id); - observerList_.emplace_back(ob); - - // Init ability thread configurtion object - ability->UpdateConfiguration(config_); -} - -void ConfigurationDistributor::Detach(const std::weak_ptr &ob) -{ - std::lock_guard lock(configLock_); - if (ob.expired()) { - HILOG_INFO("Detach ob is null"); - return; - } - - int id = ob.lock()->GetId(); - HILOG_INFO("Detach ob id[%{public}d]", id); - - auto removeById = [id](const std::weak_ptr& ob) -> bool { - auto observer = ob.lock(); - int currentId = -1; - if (observer) { - currentId = observer->GetId(); - } - HILOG_INFO("current Compare id is [%{public}d]", currentId); - return currentId == id; - }; - observerList_.remove_if(removeById); -} - -void ConfigurationDistributor::UpdateConfiguration(const AppExecFwk::Configuration &newConfig) -{ - std::lock_guard lock(configLock_); - for (const auto &iter : observerList_) { - auto observer = iter.lock(); - if (observer) { - HILOG_INFO("UpdateConfiguration To [%{public}d]", observer->GetId()); - observer->UpdateConfiguration(newConfig); - } - } - HILOG_INFO("notify done"); -} - -void ConfigurationDistributor::InitConfiguration(const AppExecFwk::Configuration &newConfig) -{ - std::lock_guard lock(configLock_); - config_ = newConfig; -} -} // namespace AAFwk -} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/connection_record.cpp b/services/abilitymgr/src/connection_record.cpp old mode 100644 new mode 100755 index 2ccef86617b6d2d34a8dbb7dd58f56b305da5fc0..c2c7d308a287511dab7ef8db754b8161cb0ad9a8 --- a/services/abilitymgr/src/connection_record.cpp +++ b/services/abilitymgr/src/connection_record.cpp @@ -128,7 +128,7 @@ void ConnectionRecord::CompleteConnect(int resultCode) HILOG_INFO("result: %{public}d. connectstate:%{public}d.", resultCode, state_); } -void ConnectionRecord::CompleteDisconnect(int resultCode) +void ConnectionRecord::CompleteDisconnect(int resultCode, bool isDied) { if (resultCode == ERR_OK) { SetConnectState(ConnectionState::DISCONNECTED); @@ -137,7 +137,7 @@ void ConnectionRecord::CompleteDisconnect(int resultCode) const AppExecFwk::AbilityInfo &abilityInfo = targetService_->GetAbilityInfo(); AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); if (connCallback_) { - connCallback_->OnAbilityDisconnectDone(element, resultCode); + connCallback_->OnAbilityDisconnectDone(element, isDied ? (resultCode - 1) : resultCode); } HILOG_INFO("result: %{public}d. connectstate:%{public}d.", resultCode, state_); } @@ -157,7 +157,7 @@ void ConnectionRecord::ScheduleDisconnectAbilityDone() handler->RemoveTask(taskName); } - CompleteDisconnect(ERR_OK); + CompleteDisconnect(ERR_OK, false); } void ConnectionRecord::ScheduleConnectAbilityDone() @@ -205,7 +205,7 @@ std::string ConnectionRecord::ConvertConnectionState(const ConnectionState &stat void ConnectionRecord::Dump(std::vector &info) const { - info.emplace_back(" > " + GetAbilityRecord()->GetAbilityInfo().bundleName + "/" + + info.emplace_back(" > " + GetAbilityRecord()->GetAbilityInfo().bundleName + "/" + GetAbilityRecord()->GetAbilityInfo().name + " connectionState #" + ConvertConnectionState(GetConnectState())); } diff --git a/services/abilitymgr/src/data_ability_manager.cpp b/services/abilitymgr/src/data_ability_manager.cpp index 917b918db1af62c3ac709b6f7c073be83d1154db..898e3847432908a4e92934b7cc2df321dd19082e 100644 --- a/services/abilitymgr/src/data_ability_manager.cpp +++ b/services/abilitymgr/src/data_ability_manager.cpp @@ -307,19 +307,31 @@ void DataAbilityManager::OnAppStateChanged(const AppInfo &info) for (auto it = dataAbilityRecordsLoaded_.begin(); it != dataAbilityRecordsLoaded_.end(); ++it) { auto abilityRecord = it->second->GetAbilityRecord(); - if (abilityRecord && abilityRecord->GetApplicationInfo().name == info.appName && - (info.processName == abilityRecord->GetAbilityInfo().process || - info.processName == abilityRecord->GetApplicationInfo().bundleName)) { - abilityRecord->SetAppState(info.state); + if (abilityRecord && (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName)) { + auto appName = abilityRecord->GetApplicationInfo().name; + auto uid = abilityRecord->GetAbilityInfo().applicationInfo.uid; + auto isExist = [&appName, &uid]( + const AppData &appData) { return appData.appName == appName && appData.uid == uid; }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + if (iter != info.appData.end()) { + abilityRecord->SetAppState(info.state); + } } } for (auto it = dataAbilityRecordsLoading_.begin(); it != dataAbilityRecordsLoading_.end(); ++it) { auto abilityRecord = it->second->GetAbilityRecord(); - if (abilityRecord && abilityRecord->GetApplicationInfo().name == info.appName && - (info.processName == abilityRecord->GetAbilityInfo().process || - info.processName == abilityRecord->GetApplicationInfo().bundleName)) { - abilityRecord->SetAppState(info.state); + if (abilityRecord && (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName)) { + auto appName = abilityRecord->GetApplicationInfo().name; + auto uid = abilityRecord->GetAbilityInfo().applicationInfo.uid; + auto isExist = [&appName, &uid]( + const AppData &appData) { return appData.appName == appName && appData.uid == uid; }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + if (iter != info.appData.end()) { + abilityRecord->SetAppState(info.state); + } } } } @@ -482,5 +494,38 @@ void DataAbilityManager::DumpState(std::vector &info, const std::st } return; } + +void DataAbilityManager::GetAbilityRunningInfos(std::vector &info) +{ + HILOG_INFO("Get ability running infos"); + std::lock_guard locker(mutex_); + + auto queryInfo = [&info](DataAbilityRecordPtrMap::reference data) { + auto dataAbilityRecord = data.second; + if (!dataAbilityRecord) { + return; + } + + auto abilityRecord = dataAbilityRecord->GetAbilityRecord(); + if (!abilityRecord) { + return; + } + + AbilityRunningInfo runningInfo; + AppExecFwk::RunningProcessInfo processInfo; + runningInfo.ability = abilityRecord->GetWant().GetElement(); + DelayedSingleton::GetInstance()-> + GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo); + runningInfo.pid = processInfo.pid_; + runningInfo.uid = processInfo.uid_; + runningInfo.processName = processInfo.processName_; + runningInfo.startTime = abilityRecord->GetStartTime(); + runningInfo.abilityState = static_cast(abilityRecord->GetAbilityState()); + info.emplace_back(runningInfo); + }; + + std::for_each(dataAbilityRecordsLoading_.begin(), dataAbilityRecordsLoading_.end(), queryInfo); + std::for_each(dataAbilityRecordsLoaded_.begin(), dataAbilityRecordsLoaded_.end(), queryInfo); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/extension_running_info.cpp b/services/abilitymgr/src/extension_running_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..adfa99e398292ae82af1fe617e2f3373fb2db2fe --- /dev/null +++ b/services/abilitymgr/src/extension_running_info.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "extension_running_info.h" +#include "hilog_wrapper.h" +#include "nlohmann/json.hpp" +#include "string_ex.h" + +namespace OHOS { +namespace AAFwk { +bool ExtensionRunningInfo::ReadFromParcel(Parcel &parcel) +{ + std::unique_ptr readExtension(parcel.ReadParcelable()); + if (readExtension == nullptr) { + return false; + } + extension = *readExtension; + pid = parcel.ReadInt32(); + uid = parcel.ReadInt32(); + type = static_cast(parcel.ReadInt32()); + processName = Str16ToStr8(parcel.ReadString16()); + startTime = parcel.ReadInt32(); + int32_t clientPackageSize = parcel.ReadInt32(); + for (int32_t i = 0; i < clientPackageSize; i++) { + clientPackage.emplace_back(Str16ToStr8(parcel.ReadString16())); + } + return true; +} + +ExtensionRunningInfo *ExtensionRunningInfo::Unmarshalling(Parcel &parcel) +{ + ExtensionRunningInfo *info = new (std::nothrow) ExtensionRunningInfo(); + if (info == nullptr) { + return nullptr; + } + + if (!info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + return info; +} + +bool ExtensionRunningInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(&extension)) { + return false; + } + if (!parcel.WriteInt32(pid)) { + return false; + } + if (!parcel.WriteInt32(uid)) { + return false; + } + if (!parcel.WriteInt32(static_cast(type))) { + return false; + } + if (!parcel.WriteString16(Str8ToStr16(processName))) { + return false; + } + if (!parcel.WriteInt32(startTime)) { + return false; + } + int32_t clientPackageSize = static_cast(clientPackage.size()); + if (!parcel.WriteInt32(clientPackageSize)) { + return false; + } + for (std::string package : clientPackage) { + if (!parcel.WriteString16(Str8ToStr16(package))) { + return false; + } + } + return true; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/inner_mission_info.cpp b/services/abilitymgr/src/inner_mission_info.cpp index cc5fe407e52b35399ca16fcc8d38233b63c5ab35..9034ded94c0cf8eb17cae351981e4a5eb7811b4b 100644 --- a/services/abilitymgr/src/inner_mission_info.cpp +++ b/services/abilitymgr/src/inner_mission_info.cpp @@ -28,6 +28,7 @@ std::string InnerMissionInfo::ToJsonStr() const value["MissionId"] = missionInfo.id; value["RunningState"] = missionInfo.runningState; value["LockedState"] = missionInfo.lockedState; + value["Continuable"] = missionInfo.continuable; value["Time"] = missionInfo.time; value["Label"] = missionInfo.label; value["IconPath"] = missionInfo.iconPath; @@ -76,6 +77,9 @@ void InnerMissionInfo::FromJsonStr(const std::string &jsonStr) if (CheckJsonNode("LockedState", JsonType::BOOLEAN)) { missionInfo.lockedState = value["LockedState"]; } + if (CheckJsonNode("Continuable", JsonType::BOOLEAN)) { + missionInfo.continuable = value["Continuable"]; + } if (CheckJsonNode("Time", JsonType::STRING)) { missionInfo.time = value["Time"]; } @@ -102,6 +106,8 @@ void InnerMissionInfo::Dump(std::vector &info) const info.push_back(dumpInfo); dumpInfo = " lockedState [" + std::to_string(missionInfo.lockedState) + "]"; info.push_back(dumpInfo); + dumpInfo = " continuable [" + std::to_string(missionInfo.continuable) + "]"; + info.push_back(dumpInfo); dumpInfo = " timeStamp [" + missionInfo.time + "]"; info.push_back(dumpInfo); dumpInfo = " label [" + missionInfo.label + "]"; diff --git a/services/abilitymgr/src/kernal_ability_manager.cpp b/services/abilitymgr/src/kernal_ability_manager.cpp index 6e1059d2c281f7d4356c9421ca2ed69cd9505f4f..1667b8db46f95499b988c02d8de7ada0ac92dd51 100644 --- a/services/abilitymgr/src/kernal_ability_manager.cpp +++ b/services/abilitymgr/src/kernal_ability_manager.cpp @@ -116,10 +116,14 @@ void KernalAbilityManager::OnAppStateChanged(const AppInfo &info) { std::lock_guard guard(stackLock_); for (auto ability : abilities_) { - if (ability && ability->GetApplicationInfo().name == info.appName && - (info.processName == ability->GetAbilityInfo().process || - info.processName == ability->GetApplicationInfo().bundleName)) { - ability->SetAppState(info.state); + if (ability && (info.processName == ability->GetAbilityInfo().process || + info.processName == ability->GetApplicationInfo().bundleName)) { + auto appName = ability->GetApplicationInfo().name; + auto isExist = [&appName](const AppData &appData) { return appData.appName == appName; }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + if (iter != info.appData.end()) { + ability->SetAppState(info.state); + } } } } @@ -183,14 +187,14 @@ void KernalAbilityManager::CompleteForeground(const std::shared_ptr &targetAbility) { - std::string abilityFlag = KernalAbilityManager::GetFlagOfAbility( - abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name); + std::string abilityFlag = + KernalAbilityManager::GetFlagOfAbility(abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name); auto isExist = [targetFlag = abilityFlag](const std::shared_ptr &ability) { if (ability == nullptr) { return false; } - return KernalAbilityManager::GetFlagOfAbility( - ability->GetAbilityInfo().bundleName, ability->GetAbilityInfo().name) == targetFlag; + return KernalAbilityManager::GetFlagOfAbility(ability->GetAbilityInfo().bundleName, + ability->GetAbilityInfo().name) == targetFlag; }; auto iter = std::find_if(abilities_.begin(), abilities_.end(), isExist); if (iter != abilities_.end()) { @@ -371,6 +375,32 @@ void KernalAbilityManager::OnTimeOut(uint32_t msgId, int64_t eventId) } } +void KernalAbilityManager::GetAbilityRunningInfos(std::vector &info) +{ + HILOG_DEBUG("Get ability running infos"); + std::lock_guard guard(stackLock_); + + for (auto &ability : abilities_) { + if (!ability) { + HILOG_DEBUG("ability is nullptr."); + continue; + } + + AbilityRunningInfo runningInfo; + AppExecFwk::RunningProcessInfo processInfo; + runningInfo.ability = ability->GetWant().GetElement(); + DelayedSingleton::GetInstance()-> + GetRunningProcessInfoByToken(ability->GetToken(), processInfo); + runningInfo.pid = processInfo.pid_; + runningInfo.uid = processInfo.uid_; + runningInfo.processName = processInfo.processName_; + runningInfo.startTime = ability->GetStartTime(); + runningInfo.abilityState = static_cast(ability->GetAbilityState()); + info.emplace_back(runningInfo); + } +} + + void KernalAbilityManager::RestartAbility(const std::shared_ptr abilityRecord) { CHECK_POINTER(abilityRecord); diff --git a/services/abilitymgr/src/kernal_system_app_manager.cpp b/services/abilitymgr/src/kernal_system_app_manager.cpp index fca9ab857553ceda4c0a141bb1f9eab3e3bea6a1..a785eb6aca9cde04e0da1b527a0f54d4fe745c54 100644 --- a/services/abilitymgr/src/kernal_system_app_manager.cpp +++ b/services/abilitymgr/src/kernal_system_app_manager.cpp @@ -118,10 +118,16 @@ void KernalSystemAppManager::OnAppStateChanged(const AppInfo &info) { std::lock_guard guard(stackLock_); for (auto ability : abilities_) { - if (ability && ability->GetApplicationInfo().name == info.appName && - (info.processName == ability->GetAbilityInfo().process || + if (ability && (info.processName == ability->GetAbilityInfo().process || info.processName == ability->GetApplicationInfo().bundleName)) { - ability->SetAppState(info.state); + auto appName = ability->GetApplicationInfo().name; + auto isExist = [&appName](const AppData &appData) { + return appData.appName == appName; + }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + if (iter != info.appData.end()) { + ability->SetAppState(info.state); + } } } } @@ -162,7 +168,14 @@ int KernalSystemAppManager::DispatchActive(const std::shared_ptr } handler->RemoveEvent(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecord->GetEventId()); - auto task = [kernalManager = shared_from_this(), abilityRecord]() { kernalManager->CompleteActive(abilityRecord); }; + auto task = [weak = weak_from_this(), abilityRecord]() { + auto kernalManager = weak.lock(); + if (kernalManager == nullptr) { + HILOG_ERROR("kernalManager is null, CompleteActive failed"); + return; + } + kernalManager->CompleteActive(abilityRecord); + }; handler->PostTask(task); return ERR_OK; } @@ -176,7 +189,14 @@ void KernalSystemAppManager::CompleteActive(const std::shared_ptr auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); CHECK_POINTER(handler); - auto task = [kernalManager = shared_from_this()]() { kernalManager->DequeueWaittingAbility(); }; + auto task = [weak = weak_from_this()]() { + auto kernalManager = weak.lock(); + if (kernalManager == nullptr) { + HILOG_ERROR("kernalManager is null, DequeueWaittingAbility failed"); + return; + } + kernalManager->DequeueWaittingAbility(); + }; handler->PostTask(task, "DequeueWaittingAbility"); } @@ -342,10 +362,10 @@ void KernalSystemAppManager::OnTimeOut(uint32_t msgId, int64_t eventId) auto abilityRecord = GetAbilityRecordByEventId(eventId); CHECK_POINTER(abilityRecord); - auto ams = DelayedSingleton::GetInstance(); - CHECK_POINTER(ams); + auto abilityMS = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityMS); - auto handler = ams->GetEventHandler(); + auto handler = abilityMS->GetEventHandler(); CHECK_POINTER(handler); switch (msgId) { @@ -354,13 +374,13 @@ void KernalSystemAppManager::OnTimeOut(uint32_t msgId, int64_t eventId) std::string bundleName = abilityRecord->GetAbilityInfo().bundleName; std::string name = abilityRecord->GetAbilityInfo().name; RemoveAbilityRecord(abilityRecord); - auto task = [ams, bundleName]() { - ams->KillProcess(bundleName); + auto task = [abilityMS, bundleName]() { + abilityMS->KillProcess(bundleName); HILOG_ERROR("System UI on time out event: KillProcess:%{public}s", bundleName.c_str()); }; handler->PostTask(task); - auto timeoutTask = [ams, name]() { - ams->StartSystemUi(name); + auto timeoutTask = [abilityMS, name]() { + abilityMS->StartSystemUi(name); HILOG_ERROR("System UI on time out event: restart:%{public}s", name.c_str()); }; handler->PostTask(timeoutTask, "SystemUi_Timeout_" + name, AbilityManagerService::RESTART_TIMEOUT); diff --git a/services/abilitymgr/src/lock_screen_event_subscriber.cpp b/services/abilitymgr/src/lock_screen_event_subscriber.cpp index 9ce09a1f8f5d36a492906b5df8f18c36e32426a4..d7744af077a8e6511999057d07b1c1f9944be702 100644 --- a/services/abilitymgr/src/lock_screen_event_subscriber.cpp +++ b/services/abilitymgr/src/lock_screen_event_subscriber.cpp @@ -29,7 +29,7 @@ void LockScreenEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData & std::string eventName = data.GetWant().GetAction(); if (eventName == AbilityConfig::LOCK_SCREEN_EVENT_NAME) { bool isLockScreen = static_cast(data.GetCode()); - auto task = [this, isLockScreen]() { + auto task = [isLockScreen]() { auto service = DelayedSingleton::GetInstance(); service->UpdateLockScreenState(isLockScreen); }; diff --git a/services/abilitymgr/src/mission_data_storage.cpp b/services/abilitymgr/src/mission_data_storage.cpp index 99a0e658b38db9f69cef19aedc9ba57e156c961d..828ab061a7864306e7b83d38c5efb0008033ad2e 100644 --- a/services/abilitymgr/src/mission_data_storage.cpp +++ b/services/abilitymgr/src/mission_data_storage.cpp @@ -19,6 +19,9 @@ #include "file_util.h" #include "hilog_wrapper.h" +#include "image_source.h" +#include "media_errors.h" +#include "png.h" namespace OHOS { namespace AAFwk { @@ -86,7 +89,9 @@ void MissionDataStorage::DeleteMissionInfo(int missionId) bool removeMissionFile = OHOS::HiviewDFX::FileUtil::RemoveFile(filePath); if (!removeMissionFile) { HILOG_ERROR("remove mission file %{public}s failed.", filePath.c_str()); + return; } + DeleteMissionSnapshot(missionId); } std::string MissionDataStorage::GetMissionDataDirPath() @@ -125,5 +130,113 @@ bool MissionDataStorage::CheckFileNameValid(const std::string &fileName) return true; } + +void MissionDataStorage::SaveMissionSnapshot(int32_t missionId, const MissionSnapshot& missionSnapshot) +{ + std::string filePath = GetMissionSnapshotPath(missionId); + std::string dirPath = OHOS::HiviewDFX::FileUtil::ExtractFilePath(filePath); + if (!OHOS::HiviewDFX::FileUtil::FileExists(dirPath)) { + bool createDir = OHOS::HiviewDFX::FileUtil::ForceCreateDirectory(dirPath); + if (!createDir) { + HILOG_ERROR("snapshot: create dir %{public}s failed.", dirPath.c_str()); + return; + } + } + const uint8_t* data = missionSnapshot.snapshot->GetPixels(); + bool saveMissionFile = WriteToPng(filePath.c_str(), missionSnapshot.snapshot->GetWidth(), + missionSnapshot.snapshot->GetHeight(), data); + if (!saveMissionFile) { + HILOG_ERROR("snapshot: save mission snapshot failed, path = %{public}s.", filePath.c_str()); + } +} + +void MissionDataStorage::DeleteMissionSnapshot(int32_t missionId) +{ + std::string filePath = GetMissionSnapshotPath(missionId); + std::string dirPath = OHOS::HiviewDFX::FileUtil::ExtractFilePath(filePath); + if (!OHOS::HiviewDFX::FileUtil::FileExists(filePath)) { + HILOG_WARN("snapshot: remove snapshot file %{public}s failed, file not exists", filePath.c_str()); + return; + } + bool removeResult = OHOS::HiviewDFX::FileUtil::RemoveFile(filePath); + if (!removeResult) { + HILOG_ERROR("snapshot: remove snapshot file %{public}s failed.", filePath.c_str()); + } +} + +bool MissionDataStorage::GetMissionSnapshot(int missionId, MissionSnapshot& missionSnapshot) +{ + std::string filePath = GetMissionSnapshotPath(missionId); + if (!OHOS::HiviewDFX::FileUtil::FileExists(filePath)) { + HILOG_INFO("snapshot: storage snapshot not exists, missionId = %{public}d", missionId); + return false; + } + uint32_t errCode = 0; + Media::SourceOptions sourceOptions; + auto imageSource = Media::ImageSource::CreateImageSource(filePath, sourceOptions, errCode); + if (errCode != OHOS::Media::SUCCESS) { + HILOG_ERROR("snapshot: CreateImageSource failed, errCode = %{public}d", errCode); + return false; + } + Media::DecodeOptions decodeOptions; + auto pixelMap = imageSource->CreatePixelMap(decodeOptions, errCode); + if (errCode != OHOS::Media::SUCCESS) { + HILOG_ERROR("snapshot: CreatePixelMap failed, errCode = %{public}d", errCode); + return false; + } + missionSnapshot.snapshot = std::move(pixelMap); + return true; +} + +std::string MissionDataStorage::GetMissionSnapshotPath(int missionId) +{ + return GetMissionDataDirPath() + "/" + + MISSION_JSON_FILE_PREFIX + "_" + std::to_string(missionId) + PNG_FILE_SUFFIX; +} + +bool MissionDataStorage::WriteToPng(const char* fileName, uint32_t width, uint32_t height, const uint8_t* data) +{ + const int BITMAP_DEPTH = 8; // color depth + const int BPP = 4; // bytes per pixel + png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + if (png_ptr == nullptr) { + HILOG_ERROR("snapshot: png_create_write_struct error, nullptr!\n"); + return false; + } + png_infop info_ptr = png_create_info_struct(png_ptr); + if (png_ptr == nullptr) { + HILOG_ERROR("snapshot: png_create_info_struct error, nullptr!\n"); + png_destroy_write_struct(&png_ptr, nullptr); + return false; + } + FILE *fp = fopen(fileName, "wb"); + if (fp == nullptr) { + HILOG_ERROR("snapshot: open file [%s] error, nullptr!\n", fileName); + png_destroy_write_struct(&png_ptr, &info_ptr); + return false; + } + png_init_io(png_ptr, fp); + + // set png header + png_set_IHDR(png_ptr, info_ptr, + width, height, + BITMAP_DEPTH, + PNG_COLOR_TYPE_RGBA, + PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, + PNG_FILTER_TYPE_BASE); + png_set_packing(png_ptr); + png_write_info(png_ptr, info_ptr); + + for (uint32_t i = 0; i < height; i++) { + png_write_row(png_ptr, data + (i * width * BPP)); + } + png_write_end(png_ptr, info_ptr); + + // free memory + png_destroy_write_struct(&png_ptr, &info_ptr); + (void)fclose(fp); + return true; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/mission_info.cpp b/services/abilitymgr/src/mission_info.cpp index 89a4ee14e81e3486b15cd64131b2949df206d568..1ce8816e8eee7303ebeafddd5995cc2e3f194c6e 100644 --- a/services/abilitymgr/src/mission_info.cpp +++ b/services/abilitymgr/src/mission_info.cpp @@ -22,6 +22,7 @@ bool MissionInfo::ReadFromParcel(Parcel &parcel) id = parcel.ReadInt32(); runningState = parcel.ReadInt32(); lockedState = parcel.ReadBool(); + continuable = parcel.ReadBool(); time = Str16ToStr8(parcel.ReadString16()); label = Str16ToStr8(parcel.ReadString16()); iconPath = Str16ToStr8(parcel.ReadString16()); @@ -57,6 +58,10 @@ bool MissionInfo::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteBool(continuable)) { + return false; + } + if (!parcel.WriteString16(Str8ToStr16(time))) { return false; } diff --git a/services/abilitymgr/src/mission_info_mgr.cpp b/services/abilitymgr/src/mission_info_mgr.cpp index e3282cc3ac2a107277d442b1078ac868e4939feb..5dbb0d3d63b06bbd12c3ef3101e008614d01b0c0 100644 --- a/services/abilitymgr/src/mission_info_mgr.cpp +++ b/services/abilitymgr/src/mission_info_mgr.cpp @@ -57,6 +57,8 @@ bool MissionInfoMgr::Init(int userId) return false; } + missionInfoList_.clear(); + missionIdMap_.clear(); if (!LoadAllMissionInfo()) { return false; } @@ -162,14 +164,16 @@ bool MissionInfoMgr::DeleteAllMissionInfos(const std::shared_ptrmissionInfo.lockedState)) { missionIdMap_.erase(listIter->missionInfo.id); - missionInfoList_.erase(listIter); taskDataPersistenceMgr_->DeleteMissionInfo(listIter->missionInfo.id); if (listenerController) { listenerController->NotifyMissionDestroyed(listIter->missionInfo.id); } + missionInfoList_.erase(listIter++); + } else { + ++listIter; } } return true; @@ -177,6 +181,7 @@ bool MissionInfoMgr::DeleteAllMissionInfos(const std::shared_ptr &missionInfos) { + HILOG_INFO("GetMissionInfos, numMax:%{public}d", numMax); if (numMax < 0) { return -1; } @@ -194,6 +199,7 @@ int MissionInfoMgr::GetMissionInfos(int32_t numMax, std::vector &mi int MissionInfoMgr::GetMissionInfoById(int32_t missionId, MissionInfo &missionInfo) { + HILOG_INFO("GetMissionInfoById, missionId:%{public}d", missionId); if (missionIdMap_.find(missionId) == missionIdMap_.end()) { HILOG_ERROR("missionId %{public}d not exists, get mission info failed", missionId); return -1; @@ -209,6 +215,7 @@ int MissionInfoMgr::GetMissionInfoById(int32_t missionId, MissionInfo &missionIn HILOG_ERROR("no such mission:%{public}d", missionId); return -1; } + HILOG_INFO("GetMissionInfoById, find missionId missionId:%{public}d", missionId); missionInfo = (*it).missionInfo; return 0; } @@ -275,6 +282,30 @@ void MissionInfoMgr::UpdateMissionTimeStamp(int32_t missionId, const std::string (void)AddMissionInfo(updateInfo); } +int MissionInfoMgr::UpdateMissionLabel(int32_t missionId, const std::string& label) +{ + if (!taskDataPersistenceMgr_) { + HILOG_ERROR("task data persist not init."); + return -1; + } + auto it = find_if(missionInfoList_.begin(), missionInfoList_.end(), [missionId](const InnerMissionInfo &info) { + return missionId == info.missionInfo.id; + }); + if (it == missionInfoList_.end()) { + HILOG_ERROR("UpdateMissionLabel failed, missionId %{public}d not exists", missionId); + return -1; + } + + InnerMissionInfo updateInfo = *it; + updateInfo.missionInfo.label = label; + + if (!taskDataPersistenceMgr_->SaveMissionInfo(updateInfo)) { + HILOG_ERROR("save mission info failed."); + return -1; + } + return 0; +} + bool MissionInfoMgr::LoadAllMissionInfo() { if (!taskDataPersistenceMgr_) { @@ -305,5 +336,69 @@ void MissionInfoMgr::Dump(std::vector &info) innerMissionInfo.Dump(info); } } + +void MissionInfoMgr::RegisterSnapshotHandler(const sptr& handler) +{ + snapshotHandler_ = handler; +} + +bool MissionInfoMgr::UpdateMissionSnapshot(int32_t missionId, const sptr& abilityToken, + MissionSnapshot& missionSnapshot) const +{ + HILOG_ERROR("snapshot: UpdateMissionSnapshot, missionId:%{public}d", missionId); + auto it = find_if(missionInfoList_.begin(), missionInfoList_.end(), [missionId](const InnerMissionInfo &info) { + return missionId == info.missionInfo.id; + }); + if (it == missionInfoList_.end()) { + HILOG_ERROR("snapshot: get mission failed, missionId %{public}d not exists", missionId); + return false; + } + if (!snapshotHandler_) { + HILOG_ERROR("snapshot: snapshotHandler_ is nullptr"); + return false; + } + Snapshot snapshot; + int32_t result = snapshotHandler_->GetSnapshot(abilityToken, snapshot); + if (result != 0) { + HILOG_ERROR("snapshot: get WMS snapshot failed, result = %{public}d", result); + return false; + } + if (!taskDataPersistenceMgr_) { + HILOG_ERROR("snapshot: taskDataPersistenceMgr_ is nullptr"); + return false; + } + missionSnapshot.snapshot = snapshot.GetPixelMap(); + missionSnapshot.topAbility = it->missionInfo.want.GetElement(); + if (!taskDataPersistenceMgr_->SaveMissionSnapshot(missionId, missionSnapshot)) { + HILOG_ERROR("snapshot: save mission snapshot failed"); + return false; + } + HILOG_INFO("snapshot: update mission snapshot success"); + return true; +} + +bool MissionInfoMgr::GetMissionSnapshot(int32_t missionId, const sptr& abilityToken, + MissionSnapshot& missionSnapshot) const +{ + HILOG_ERROR("mission_list_info GetMissionSnapshot, missionId:%{public}d", missionId); + auto it = find_if(missionInfoList_.begin(), missionInfoList_.end(), [missionId](const InnerMissionInfo &info) { + return missionId == info.missionInfo.id; + }); + if (it == missionInfoList_.end()) { + HILOG_ERROR("snapshot: get mission failed, missionId %{public}d not exists", missionId); + return false; + } + if (!taskDataPersistenceMgr_) { + HILOG_ERROR("snapshot: taskDataPersistenceMgr_ is nullptr"); + return false; + } + if (taskDataPersistenceMgr_->GetMissionSnapshot(missionId, missionSnapshot)) { + missionSnapshot.topAbility = it->missionInfo.want.GetElement(); + HILOG_ERROR("mission_list_info GetMissionSnapshot, find snapshot OK, missionId:%{public}d", missionId); + return true; + } + HILOG_INFO("snapshot: storage mission snapshot not exists, create new snapshot"); + return UpdateMissionSnapshot(missionId, abilityToken, missionSnapshot); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/mission_list.cpp b/services/abilitymgr/src/mission_list.cpp index ca91a02d3d7ec2c5461739d00586298c97c74e12..439df45cef9005ed2e283c1f95802acfcdfc8682 100644 --- a/services/abilitymgr/src/mission_list.cpp +++ b/services/abilitymgr/src/mission_list.cpp @@ -113,6 +113,26 @@ std::shared_ptr MissionList::GetMissionById(int missionId) const return nullptr; } +std::shared_ptr MissionList::GetMissionBySpecifiedFlag(const std::string &flag) const +{ + for (auto mission : missions_) { + if (!mission) { + return nullptr; + } + + auto ability = mission->GetAbilityRecord(); + if (!ability) { + return nullptr; + } + + if (ability->GetSpecifiedFlag() == flag) { + return mission; + } + } + + return nullptr; +} + bool MissionList::IsEmpty() { return missions_.empty(); @@ -131,7 +151,7 @@ std::shared_ptr MissionList::GetTopAbility() const return nullptr; } -std::list> MissionList::GetAllMissions() const +std::list>& MissionList::GetAllMissions() { return missions_; } @@ -184,6 +204,20 @@ std::shared_ptr MissionList::GetAbilityRecordByCaller( return nullptr; } +std::shared_ptr MissionList::GetAbilityRecordByName(const AppExecFwk::ElementName &element) +{ + for (auto mission : missions_) { + if (mission) { + const AppExecFwk::AbilityInfo &abilityInfo = mission->GetAbilityRecord()->GetAbilityInfo(); + AppExecFwk::ElementName localElement(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); + if (localElement == element) { + return mission->GetAbilityRecord(); + } + } + } + return nullptr; +} + sptr MissionList::GetAbilityTokenByMissionId(int32_t missionId) { for (auto mission : missions_) { @@ -219,7 +253,7 @@ std::string MissionList::GetTypeName() } } -void MissionList::Dump(std::vector &info) +void MissionList::Dump(std::vector& info) { std::string dumpInfo = " MissionList Type #" + GetTypeName(); info.push_back(dumpInfo); @@ -230,20 +264,40 @@ void MissionList::Dump(std::vector &info) } } -void MissionList::DumpList(std::vector &info) +void MissionList::DumpStateByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId) +{ + for (const auto& mission : missions_) { + if (mission) { + auto abilityRecord = mission->GetAbilityRecord(); + if (abilityRecord) { + if (abilityRecord->GetRecordId() == abilityRecordId) { + HILOG_INFO("record begain to call DumpAbilityState %{public}s", __func__); + abilityRecord->DumpAbilityState(info, isClient); + return; + } + } + } + } +} +void MissionList::DumpList(std::vector &info, bool isClient) { std::string dumpInfo = " MissionList Type #" + GetTypeName(); info.push_back(dumpInfo); - dumpInfo = " Mission IDs ["; + for (const auto& mission : missions_) { if (mission) { - dumpInfo += " "; - dumpInfo += "#"; - dumpInfo += std::to_string(mission->GetMissionId()); + dumpInfo = " Mission ID #" + std::to_string(mission->GetMissionId()); + dumpInfo += " mission name #[" + mission->GetMissionName() + "]" + + " lockedState #" + std::to_string(mission->IsLockedState()); + info.push_back(dumpInfo); + + auto abilityRecord = mission->GetAbilityRecord(); + if (abilityRecord) { + HILOG_INFO("record begain to call DumpAbilityState %{public}s", __func__); + abilityRecord->DumpAbilityState(info, isClient); + } } } - dumpInfo += " ]"; - info.push_back(dumpInfo); } } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index c934493732e873220a6fd281aee0fd0d352fba87..48f7dfc62f33b3ad94c996ddca9259a229d16acc 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -62,8 +62,8 @@ int MissionListManager::StartAbility(const AbilityRequest &abilityRequest) auto state = currentTopAbility->GetAbilityState(); HILOG_DEBUG("current top: %{public}s, state: %{public}s", element.c_str(), AbilityRecord::ConvertAbilityState(state).c_str()); - if (state != FOREGROUND_NEW) { - HILOG_INFO("Top ability is not foreground, so enqueue ability for waiting."); + if (state == FOREGROUNDING_NEW) { + HILOG_INFO("Top ability is foregrounding, so enqueue ability for waiting."); EnqueueWaittingAbility(abilityRequest); return START_ABILITY_WAITING; } @@ -82,6 +82,20 @@ int MissionListManager::StartAbility(const AbilityRequest &abilityRequest) } } + return StartAbility(currentTopAbility, callerAbility, abilityRequest); +} + +int MissionListManager::StartAbility(const std::shared_ptr ¤tTopAbility, + const std::shared_ptr &callerAbility, const AbilityRequest &abilityRequest) +{ + auto isSpecified = (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED); + if (isSpecified) { + EnqueueWaittingAbility(abilityRequest); + DelayedSingleton::GetInstance()->StartSpecifiedAbility( + abilityRequest.want, abilityRequest.abilityInfo); + return 0; + } + return StartAbilityLocked(currentTopAbility, callerAbility, abilityRequest); } @@ -137,6 +151,12 @@ int MissionListManager::GetMissionInfo(int32_t missionId, MissionInfo &missionIn } int MissionListManager::MoveMissionToFront(int32_t missionId) +{ + std::lock_guard guard(managerLock_); + return MoveMissionToFront(missionId, true); +} + +int MissionListManager::MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher) { HILOG_INFO("move mission to front:%{public}d.", missionId); std::lock_guard guard(managerLock_); @@ -147,7 +167,7 @@ int MissionListManager::MoveMissionToFront(int32_t missionId) return MOVE_MISSION_FAILED; } - MoveMissionToTargetList(true, targetMissionList, mission); + MoveMissionToTargetList(isCallerFromLauncher, targetMissionList, mission); MoveMissionListToTop(targetMissionList); // update inner mission info time @@ -190,7 +210,7 @@ void MissionListManager::StartWaittingAbility() AbilityRequest abilityRequest = waittingAbilityQueue_.front(); waittingAbilityQueue_.pop(); auto callerAbility = GetAbilityRecordByToken(abilityRequest.callerToken); - StartAbilityLocked(topAbility, callerAbility, abilityRequest); + StartAbility(topAbility, callerAbility, abilityRequest); return; } } @@ -225,9 +245,11 @@ int MissionListManager::StartAbilityLocked(const std::shared_ptr // 4. move target list to top MoveMissionListToTop(targetList); - // ability is already foreground, process next ability. - if (targetAbilityRecord->IsAbilityState(AbilityState::FOREGROUND_NEW) || - targetAbilityRecord->IsAbilityState(AbilityState::FOREGROUNDING_NEW)) { + // ability is already foreground, process next ability, excepting for launcher's MainAbility. + if ((abilityRequest.abilityInfo.bundleName != AbilityConfig::LAUNCHER_BUNDLE_NAME || + abilityRequest.abilityInfo.name != AbilityConfig::LAUNCHER_ABILITY_NAME) && + (targetAbilityRecord->IsAbilityState(AbilityState::FOREGROUND_NEW) || + targetAbilityRecord->IsAbilityState(AbilityState::FOREGROUNDING_NEW))) { PostStartWaittingAbility(); return 0; } @@ -278,12 +300,13 @@ void MissionListManager::GetTargetMissionAndAbility(const AbilityRequest &abilit info.missionName = missionName; info.isSingletonMode = isSingleton; info.missionInfo.runningState = 0; + info.missionInfo.continuable = abilityRequest.abilityInfo.continuable; info.missionInfo.time = Time2str(time(0)); - info.missionInfo.label = abilityRequest.appInfo.label; info.missionInfo.iconPath = abilityRequest.appInfo.iconPath; info.missionInfo.want = abilityRequest.want; if (!findReusedMissionInfo) { + info.missionInfo.label = abilityRequest.appInfo.label; if (!DelayedSingleton::GetInstance()->GenerateMissionId(info.missionInfo.id)) { HILOG_DEBUG("failed to generate mission id."); return; @@ -294,6 +317,10 @@ void MissionListManager::GetTargetMissionAndAbility(const AbilityRequest &abilit targetRecord->SetUseNewMission(); targetRecord->SetMission(targetMission); + if (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) { + targetRecord->SetSpecifiedFlag(abilityRequest.specifiedFlag); + } + if (abilityRequest.abilityInfo.applicationInfo.isLauncherApp) { return; } @@ -532,6 +559,18 @@ int MissionListManager::AttachAbilityThread(const sptr &sched handler->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetEventId()); abilityRecord->SetScheduler(scheduler); + + if (abilityRecord->IsStartedByCall()) { + // started by callability, directly move to background. + abilityRecord->SetStartToBackground(true); + MoveToBackgroundTask(abilityRecord); + return ERR_OK; + } + + if (abilityRecord->IsNeedToCallRequest()) { + abilityRecord->CallRequest(); + } + DelayedSingleton::GetInstance()->MoveToForground(token); return ERR_OK; @@ -676,7 +715,8 @@ void MissionListManager::CompleteForegroundNew(const std::shared_ptr::GetInstance()->NotifyBmsAbilityLifeStatus( abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name, - AbilityUtil::UTCTimeSeconds()); + AbilityUtil::UTCTimeSeconds(), + abilityRecord->GetApplicationInfo().uid); #if BINDER_IPC_32BIT HILOG_INFO("notify bms ability life status, bundle name:%{public}s, ability name:%{public}s, time:%{public}lld", abilityRecord->GetAbilityInfo().bundleName.c_str(), @@ -739,6 +779,12 @@ void MissionListManager::CompleteBackground(const std::shared_ptr // send application state to AppMS. // notify AppMS to update application state. DelayedSingleton::GetInstance()->MoveToBackground(abilityRecord->GetToken()); + + if (abilityRecord->IsSwitchingPause()) { + abilityRecord->SetSwitchingPause(false); + return; + } + // Abilities ahead of the one started with SingleTask mode were put in terminate list, we need to terminate // them. auto self(shared_from_this()); @@ -751,6 +797,25 @@ void MissionListManager::CompleteBackground(const std::shared_ptr terminateAbility->Terminate(timeoutTask); } } + + // new version. started by caller, sdheduler call request + if (abilityRecord->IsStartedByCall() && abilityRecord->IsStartToBackground() && abilityRecord->IsReady()) { + HILOG_DEBUG("call request after completing backgroud state"); + abilityRecord->CallRequest(); + abilityRecord->SetStartToBackground(false); + } + + auto mission = abilityRecord->GetMission(); + if (!mission) { + HILOG_ERROR("snapshot: GetMission failed"); + return; + } + MissionSnapshot snapshot; + DelayedSingleton::GetInstance()->UpdateMissionSnapshot(mission->GetMissionId(), + abilityRecord->GetToken(), snapshot); + if (listenerController_) { + listenerController_->NotifyMissionSnapshotChanged(mission->GetMissionId()); + } } int MissionListManager::TerminateAbility(const std::shared_ptr &abilityRecord, @@ -834,8 +899,8 @@ int MissionListManager::TerminateAbilityLocked(const std::shared_ptrGetAbilityState()); return; } - // 3. if the launcher is foreground, just background - std::shared_ptr launcherRoot = launcherList_->GetLauncherRoot(); - if (launcherRoot - && (launcherRoot->IsAbilityState(FOREGROUND_NEW) || launcherRoot->IsAbilityState(FOREGROUNDING_NEW))) { - HILOG_DEBUG("launcherRoot state is %{public}d, no need to schedule next", launcherRoot->GetAbilityState()); + // 3. if run on a laptop, noting to do + if (IsPC()) { + HILOG_DEBUG("Run on a laptop, no need to schedule next ability."); return; } // 4. the ability should find the next ability to foreground + std::shared_ptr needTopAbility; if (missionList->IsEmpty()) { HILOG_DEBUG("missionList is empty, next is launcher"); - abilityRecord->SetNextAbilityRecord(GetCurrentTopAbilityLocked()); + needTopAbility = GetCurrentTopAbilityLocked(); } else { - std::shared_ptr needTopAbility = missionList->GetTopAbility(); + needTopAbility = missionList->GetTopAbility(); + } + + if (!needTopAbility) { + HILOG_DEBUG("needTopAbility is null"); + return; + } + element = needTopAbility->GetWant().GetElement().GetURI(); + HILOG_DEBUG("next top ability is %{public}s", element.c_str()); + + if (!needTopAbility->IsForeground()) { + HILOG_DEBUG("%{public}s is need to foreground", element.c_str()); abilityRecord->SetNextAbilityRecord(needTopAbility); - std::string element = needTopAbility->GetWant().GetElement().GetURI(); - HILOG_DEBUG("next top ability is %{public}s", element.c_str()); } } @@ -973,6 +1046,10 @@ int MissionListManager::ClearMission(int missionId) } std::lock_guard guard(managerLock_); auto mission = GetMissionById(missionId); + if (mission && mission->GetMissionList() && mission->GetMissionList()->GetType() == MissionListType::LAUNCHER) { + HILOG_ERROR("Mission id is launcher, can not clear."); + return ERR_INVALID_VALUE; + } return ClearMissionLocked(missionId, mission); } @@ -1009,41 +1086,39 @@ int MissionListManager::ClearAllMissions() { std::lock_guard guard(managerLock_); DelayedSingleton::GetInstance()->DeleteAllMissionInfos(listenerController_); - for (auto mission : defaultStandardList_->GetAllMissions()) { - if (mission && !mission->IsLockedState()) { - ClearMissionLocked(-1, mission); - } - } - - for (auto mission : defaultSingleList_->GetAllMissions()) { - if (mission && !mission->IsLockedState()) { - ClearMissionLocked(-1, mission); - } - } - std::list> foregroundAbilities; - for (auto missionList : currentMissionLists_) { + ClearAllMissionsLocked(defaultStandardList_->GetAllMissions(), foregroundAbilities, false); + ClearAllMissionsLocked(defaultSingleList_->GetAllMissions(), foregroundAbilities, false); + + for (auto listIter = currentMissionLists_.begin(); listIter != currentMissionLists_.end();) { + auto missionList = (*listIter); + listIter++; if (!missionList || missionList->GetType() == MissionListType::LAUNCHER) { continue; } - for (auto mission : missionList->GetAllMissions()) { - if (!mission || !mission->GetAbilityRecord() || mission->IsLockedState()) { - continue; - } + ClearAllMissionsLocked(missionList->GetAllMissions(), foregroundAbilities, true); + } - if (mission->GetAbilityRecord()->IsActiveState()) { - foregroundAbilities.push_front(mission); - continue; - } + ClearAllMissionsLocked(foregroundAbilities, foregroundAbilities, false); + return ERR_OK; +} - ClearMissionLocked(-1, mission); +void MissionListManager::ClearAllMissionsLocked(std::list> &missionList, + std::list> &foregroundAbilities, bool searchActive) +{ + for (auto listIter = missionList.begin(); listIter != missionList.end();) { + auto mission = (*listIter); + listIter++; + if (!mission || mission->IsLockedState()) { + continue; } - } - for (auto mission : foregroundAbilities) { + if (searchActive && mission->GetAbilityRecord() && mission->GetAbilityRecord()->IsActiveState()) { + foregroundAbilities.push_front(mission); + continue; + } ClearMissionLocked(-1, mission); } - return ERR_OK; } int MissionListManager::SetMissionLockedState(int missionId, bool lockedState) @@ -1056,17 +1131,19 @@ int MissionListManager::SetMissionLockedState(int missionId, bool lockedState) std::shared_ptr mission = GetMissionById(missionId); if (mission) { mission->SetLockedState(lockedState); - // update inner mission info time - InnerMissionInfo innerMissionInfo; - DelayedSingleton::GetInstance()->GetInnerMissionInfoById(mission->GetMissionId(), - innerMissionInfo); - innerMissionInfo.missionInfo.time = Time2str(time(0)); - innerMissionInfo.missionInfo.lockedState = lockedState; - DelayedSingleton::GetInstance()->UpdateMissionInfo(innerMissionInfo); - return ERR_OK; } - HILOG_ERROR("mission is not exist, missionId %{public}d", missionId); - return MISSION_NOT_FOUND; + + // update inner mission info time + InnerMissionInfo innerMissionInfo; + auto ret = DelayedSingleton::GetInstance()->GetInnerMissionInfoById(missionId, innerMissionInfo); + if (ret != 0) { + HILOG_ERROR("mission is not exist, missionId %{public}d", missionId); + return MISSION_NOT_FOUND; + } + innerMissionInfo.missionInfo.time = Time2str(time(0)); + innerMissionInfo.missionInfo.lockedState = lockedState; + DelayedSingleton::GetInstance()->UpdateMissionInfo(innerMissionInfo); + return ERR_OK; } void MissionListManager::MoveToBackgroundTask(const std::shared_ptr &abilityRecord) @@ -1096,20 +1173,59 @@ void MissionListManager::OnTimeOut(uint32_t msgId, int64_t eventId) switch (msgId) { case AbilityManagerService::LOAD_TIMEOUT_MSG: + HandleLoadTimeout(abilityRecord); break; case AbilityManagerService::ACTIVE_TIMEOUT_MSG: break; case AbilityManagerService::INACTIVE_TIMEOUT_MSG: case AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG: - if (abilityRecord->GetMission()) { - abilityRecord->GetMission()->SetMovingState(false); - } + HandleForgroundNewTimeout(abilityRecord); break; default: break; } } +void MissionListManager::HandleLoadTimeout(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + HILOG_ERROR("MissionListManager on time out event: ability record is nullptr."); + return; + } + // root launcher load timeout, notify appMs force terminate the ability and restart immediately. + if (ability->IsLauncherAbility() && ability->IsLauncherRoot()) { + ability->SetRestarting(true); + DelayedSingleton::GetInstance()->AttachTimeOut(ability->GetToken()); + HILOG_INFO("Launcher root load timeout, restart."); + DelayedStartLauncher(); + return; + } + + // other +} + +void MissionListManager::HandleForgroundNewTimeout(const std::shared_ptr &ability) +{ + if (ability == nullptr) { + HILOG_ERROR("MissionListManager on time out event: ability record is nullptr."); + return; + } + + if (ability->GetMission()) { + ability->GetMission()->SetMovingState(false); + } + + // root launcher load timeout, notify appMs force terminate the ability and restart immediately. + if (ability->IsLauncherAbility() && ability->IsLauncherRoot()) { + DelayedSingleton::GetInstance()->AttachTimeOut(ability->GetToken()); + HILOG_INFO("Launcher root load timeout, restart."); + DelayedStartLauncher(); + return; + } + + // other +} + std::shared_ptr MissionListManager::GetAbilityRecordByCaller( const std::shared_ptr &caller, int requestCode) { @@ -1147,7 +1263,7 @@ std::shared_ptr MissionListManager::GetAbilityRecordByEventId(int return defaultStandardList_->GetAbilityRecordById(eventId); } -void MissionListManager::OnAbilityDied(std::shared_ptr abilityRecord) +void MissionListManager::OnAbilityDied(std::shared_ptr abilityRecord, int32_t currentUserId) { HILOG_INFO("On ability died."); if (!abilityRecord) { @@ -1160,7 +1276,17 @@ void MissionListManager::OnAbilityDied(std::shared_ptr abilityRec HILOG_ERROR("Ability type is not page."); return; } + std::lock_guard guard(managerLock_); + + if (abilityRecord->IsLauncherRoot() && currentUserId != userId_) { + HILOG_WARN("delay restart root launcher when start user."); + HILOG_INFO("launcher root Ability died, state: INITIAL, %{public}d", __LINE__); + abilityRecord->SetAbilityState(AbilityState::INITIAL); + abilityRecord->SetRestarting(true); + return; + } + HandleAbilityDied(abilityRecord); } @@ -1210,8 +1336,9 @@ std::shared_ptr MissionListManager::GetTargetMissionList(int missio // generate a new mission and missionList AbilityRequest abilityRequest; + auto userId = abilityRequest.appInfo.uid / BASE_USER_RANGE; int generateAbility = DelayedSingleton::GetInstance()->GenerateAbilityRequest( - innerMissionInfo.missionInfo.want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr); + innerMissionInfo.missionInfo.want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, userId); if (generateAbility != ERR_OK) { HILOG_ERROR("cannot find generate ability request, missionId: %{public}d", missionId); return nullptr; @@ -1282,10 +1409,17 @@ void MissionListManager::HandleAbilityDied(std::shared_ptr abilit { HILOG_INFO("Handle Ability Died."); CHECK_POINTER(abilityRecord); + + if (abilityRecord->GetAbilityInfo().type != AbilityType::PAGE) { + HILOG_ERROR("Ability type is not page."); + return; + } + if (abilityRecord->IsLauncherAbility()) { HandleLauncherDied(abilityRecord); return; } + HandleAbilityDiedByDefault(abilityRecord); } @@ -1304,6 +1438,7 @@ void MissionListManager::HandleLauncherDied(std::shared_ptr abili if (ability->IsLauncherRoot()) { HILOG_INFO("launcher root Ability died, state: INITIAL, %{public}d", __LINE__); ability->SetAbilityState(AbilityState::INITIAL); + ability->SetRestarting(true); } else { HILOG_INFO("launcher Ability died, remove, %{public}d", __LINE__); missionList->RemoveMission(mission); @@ -1349,9 +1484,9 @@ void MissionListManager::HandleAbilityDiedByDefault(std::shared_ptr::GetInstance(); - CHECK_POINTER(ams); - auto handler = ams->GetEventHandler(); + auto abilityManagerService = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityManagerService); + auto handler = abilityManagerService->GetEventHandler(); CHECK_POINTER(handler); std::weak_ptr wpListMgr = shared_from_this(); auto timeoutTask = [wpListMgr]() { @@ -1370,22 +1505,11 @@ void MissionListManager::BackToLauncher() std::lock_guard guard(managerLock_); CHECK_POINTER(launcherList_); - auto currentTop = GetCurrentTopAbilityLocked(); - if (currentTop && (currentTop->IsAbilityState(AbilityState::FOREGROUND_NEW) || - currentTop->IsAbilityState(AbilityState::FOREGROUNDING_NEW))) { - HILOG_WARN("Current top ability is already foreground, no need to start launcher."); - return; - } - auto launcherRootAbility = launcherList_->GetLauncherRoot(); CHECK_POINTER_LOG(launcherRootAbility, "There is no root launcher ability, back to launcher failed."); auto launcherRootMission = launcherRootAbility->GetMission(); CHECK_POINTER_LOG(launcherRootMission, "There is no root launcher mission, back to launcher failed."); - if (launcherRootAbility->IsAbilityState(AbilityState::FOREGROUND_NEW) || - launcherRootAbility->IsAbilityState(AbilityState::FOREGROUNDING_NEW)) { - HILOG_WARN("launcher is already foreground, no need to start launcher."); - return; - } + std::queue emptyQueue; std::swap(waittingAbilityQueue_, emptyQueue); @@ -1394,6 +1518,23 @@ void MissionListManager::BackToLauncher() launcherRootAbility->ProcessForegroundAbility(); } +int MissionListManager::SetMissionLabel(const sptr &token, const std::string &label) +{ + if (!token) { + HILOG_INFO("SetMissionLabel token is nullptr."); + return -1; + } + + std::lock_guard guard(managerLock_); + auto missionId = GetMissionIdByAbilityToken(token); + if (missionId <= 0) { + HILOG_INFO("SetMissionLabel find mission failed."); + return -1; + } + + return DelayedSingleton::GetInstance()->UpdateMissionLabel(missionId, label); +} + void MissionListManager::Dump(std::vector &info) { std::lock_guard guard(managerLock_); @@ -1434,44 +1575,79 @@ void MissionListManager::Dump(std::vector &info) info.push_back(dumpInfo); } -void MissionListManager::DumpMissionList(std::vector &info) +void MissionListManager::DumpMissionListByRecordId( + std::vector &info, bool isClient, int32_t abilityRecordId) { std::lock_guard guard(managerLock_); std::string dumpInfo = "User ID #" + std::to_string(userId_); info.push_back(dumpInfo); - dumpInfo = " current mission lists:{"; - info.push_back(dumpInfo); for (const auto& missionList : currentMissionLists_) { - if (missionList) { - missionList->DumpList(info); + if (missionList && missionList != launcherList_) { + HILOG_INFO("missionList begain to call DumpMissionListByRecordId %{public}s", __func__); + missionList->DumpStateByRecordId(info, isClient, abilityRecordId); } } - dumpInfo = " }"; - info.push_back(dumpInfo); - dumpInfo = " default stand mission list:{"; - info.push_back(dumpInfo); if (defaultStandardList_) { - defaultStandardList_->DumpList(info); + HILOG_INFO("defaultStandardList begain to call DumpMissionListByRecordId %{public}s", __func__); + defaultStandardList_->DumpStateByRecordId(info, isClient, abilityRecordId); } - dumpInfo = " }"; - info.push_back(dumpInfo); - dumpInfo = " default single mission list:{"; - info.push_back(dumpInfo); if (defaultSingleList_) { - defaultSingleList_->DumpList(info); + HILOG_INFO("defaultSingleList begain to call DumpMissionListByRecordId %{public}s", __func__); + defaultSingleList_->DumpStateByRecordId(info, isClient, abilityRecordId); } - dumpInfo = " }"; - info.push_back(dumpInfo); - dumpInfo = " launcher mission list:{"; - info.push_back(dumpInfo); if (launcherList_) { - launcherList_->DumpList(info); + HILOG_INFO("launcherList begain to call DumpMissionListByRecordId %{public}s", __func__); + launcherList_->DumpStateByRecordId(info, isClient, abilityRecordId); } - dumpInfo = " }"; +} +void MissionListManager::DumpMissionList(std::vector &info, bool isClient, const std::string &args) +{ + std::lock_guard guard(managerLock_); + std::string dumpInfo = "User ID #" + std::to_string(userId_); info.push_back(dumpInfo); + if (args.size() == 0 || args == "NORMAL") { + dumpInfo = " current mission lists:{"; + info.push_back(dumpInfo); + for (const auto& missionList : currentMissionLists_) { + if (missionList) { + missionList->DumpList(info, isClient); + } + } + dumpInfo = " }"; + info.push_back(dumpInfo); + } + + if (args.size() == 0 || args == "DEFAULT_STANDARD") { + dumpInfo = " default stand mission list:{"; + info.push_back(dumpInfo); + if (defaultStandardList_) { + defaultStandardList_->DumpList(info, isClient); + } + dumpInfo = " }"; + info.push_back(dumpInfo); + } + + if (args.size() == 0 || args == "DEFAULT_SINGLE") { + dumpInfo = " default single mission list:{"; + info.push_back(dumpInfo); + if (defaultSingleList_) { + defaultSingleList_->DumpList(info, isClient); + } + dumpInfo = " }"; + info.push_back(dumpInfo); + } + if (args.size() == 0 || args == "LAUNCHER") { + dumpInfo = " launcher mission list:{"; + info.push_back(dumpInfo); + if (launcherList_) { + launcherList_->DumpList(info, isClient); + } + dumpInfo = " }"; + info.push_back(dumpInfo); + } } void MissionListManager::DumpMissionInfos(std::vector &info) @@ -1494,5 +1670,376 @@ void MissionListManager::DumpMission(int missionId, std::vector &in } innerMissionInfo.Dump(info); } + +int MissionListManager::ResolveLocked(const AbilityRequest &abilityRequest) +{ + HILOG_INFO("%{public}s, resolve ability_name:%{public}s", + __func__, + abilityRequest.want.GetElement().GetURI().c_str()); + + if (!abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) { + HILOG_ERROR("%{public}s, resolve ability_name:", __func__); + return RESOLVE_CALL_ABILITY_INNER_ERR; + } + + return CallAbilityLocked(abilityRequest); +} + +int MissionListManager::CallAbilityLocked(const AbilityRequest &abilityRequest) +{ + HILOG_INFO("call ability."); + std::lock_guard guard(managerLock_); + + // allow to start ability by called type without loading ui. + if (!abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) { + HILOG_ERROR("start ability not by call."); + return ERR_INVALID_VALUE; + } + + // Get target mission and ability record. + std::shared_ptr targetAbilityRecord; + std::shared_ptr targetMission; + GetTargetMissionAndAbility(abilityRequest, targetMission, targetAbilityRecord); + if (!targetMission || !targetAbilityRecord) { + HILOG_ERROR("Failed to get mission or record."); + return ERR_INVALID_VALUE; + } + + targetAbilityRecord->AddCallerRecord(abilityRequest.callerToken, abilityRequest.requestCode); + targetAbilityRecord->SetLaunchReason(LaunchReason::LAUNCHREASON_CALL); + + // mission is first created, add mission to default call mission list. + // other keep in current mission list. + if (!targetMission->GetMissionList()) { + defaultSingleList_->AddMissionToTop(targetMission); + } + + // new version started by call type + auto ret = ResolveAbility(targetAbilityRecord, abilityRequest); + if (ret == ResolveResultType::OK_HAS_REMOTE_OBJ) { + HILOG_DEBUG("target ability has been resolved."); + return ERR_OK; + } else if (ret == ResolveResultType::NG_INNER_ERROR) { + HILOG_ERROR("resolve failed, error: %{public}d.", RESOLVE_CALL_ABILITY_INNER_ERR); + return RESOLVE_CALL_ABILITY_INNER_ERR; + } + + // schedule target ability + std::string element = targetAbilityRecord->GetWant().GetElement().GetURI(); + HILOG_DEBUG("load ability record: %{public}s", element.c_str()); + + // flag the first ability. + auto currentTopAbility = GetCurrentTopAbilityLocked(); + if (!currentTopAbility) { + targetAbilityRecord->SetLauncherRoot(); + } + + return targetAbilityRecord->LoadAbility(); +} + +int MissionListManager::ReleaseLocked(const sptr &connect, const AppExecFwk::ElementName &element) +{ + HILOG_DEBUG("release ability."); + + CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE); + + std::lock_guard guard(managerLock_); + + std::shared_ptr abilityRecord = GetAbilityRecordByName(element); + CHECK_POINTER_AND_RETURN(abilityRecord, RELEASE_CALL_ABILITY_INNER_ERR); + + if (!abilityRecord->Release(connect)) { + HILOG_ERROR("ability release call record failed."); + return RELEASE_CALL_ABILITY_INNER_ERR; + } + return ERR_OK; +} + +int MissionListManager::ResolveAbility( + const std::shared_ptr &targetAbility, const AbilityRequest &abilityRequest) +{ + HILOG_DEBUG("targetAbilityRecord resolve call record."); + CHECK_POINTER_AND_RETURN(targetAbility, ResolveResultType::NG_INNER_ERROR); + + ResolveResultType result = targetAbility->Resolve(abilityRequest); + switch (result) { + case ResolveResultType::NG_INNER_ERROR: + case ResolveResultType::OK_HAS_REMOTE_OBJ: + return result; + default: + break; + } + + if (targetAbility->IsReady()) { + HILOG_DEBUG("targetAbility is ready, directly scheduler call request."); + if (targetAbility->CallRequest()) { + return ResolveResultType::OK_HAS_REMOTE_OBJ; + } + } + + HILOG_DEBUG("targetAbility need to call request after lifecycle."); + return result; +} + +std::shared_ptr MissionListManager::GetAbilityRecordByName(const AppExecFwk::ElementName &element) +{ + // find in currentMissionLists_ + for (auto missionList : currentMissionLists_) { + if (missionList != nullptr) { + auto ability = missionList->GetAbilityRecordByName(element); + if (ability != nullptr) { + return ability; + } + } + } + + // find in lanucheMissionList_ + auto ability = launcherList_->GetAbilityRecordByName(element); + if (ability != nullptr) { + return ability; + } + + // find in default singlelist_ + return defaultSingleList_->GetAbilityRecordByName(element); +} + +void MissionListManager::OnCallConnectDied(const std::shared_ptr &callRecord) +{ + HILOG_INFO("On callConnect died."); + CHECK_POINTER(callRecord); + std::lock_guard guard(managerLock_); + + AppExecFwk::ElementName element = callRecord->GetTargetServiceName(); + auto abilityRecord = GetAbilityRecordByName(element); + CHECK_POINTER(abilityRecord); + abilityRecord->Release(callRecord->GetConCallBack()); +} +void MissionListManager::OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) +{ + std::lock_guard guard(managerLock_); + if (waittingAbilityQueue_.empty()) { + return; + } + + AbilityRequest abilityRequest = waittingAbilityQueue_.front(); + waittingAbilityQueue_.pop(); + + auto currentTopAbility = GetCurrentTopAbilityLocked(); + auto callerAbility = GetAbilityRecordByToken(abilityRequest.callerToken); + + auto mission = GetMissionBySpecifiedFlag(flag); + if (mission) { + auto ability = mission->GetAbilityRecord(); + if (!ability) { + return; + } + ability->SetWant(abilityRequest.want); + ability->SetIsNewWant(true); + + auto isCallerFromLauncher = (callerAbility && callerAbility->IsLauncherAbility()); + MoveMissionToFront(mission->GetMissionId(), isCallerFromLauncher); + return; + } + + abilityRequest.specifiedFlag = flag; + StartAbilityLocked(currentTopAbility, callerAbility, abilityRequest); +} + +std::shared_ptr MissionListManager::GetMissionBySpecifiedFlag(const std::string &flag) const +{ + std::shared_ptr mission = nullptr; + for (auto missionList : currentMissionLists_) { + if (missionList && (mission = missionList->GetMissionBySpecifiedFlag(flag)) != nullptr) { + return mission; + } + } + + if ((mission = defaultSingleList_->GetMissionBySpecifiedFlag(flag)) != nullptr) { + return mission; + } + + if ((mission = launcherList_->GetMissionBySpecifiedFlag(flag)) != nullptr) { + return mission; + } + + return defaultStandardList_->GetMissionBySpecifiedFlag(flag); +} + +bool MissionListManager::IsPC() +{ + if (MissionDmInitCallback::isInit_) { + return isPC_; + } + std::string pkgName = "ohos.aafwk.aafwk_standard"; + auto callback = std::make_shared(); + int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(pkgName, callback); + if (ret != ERR_OK) { + HILOG_WARN("DeviceManager initialization failed."); + return false; + } + DistributedHardware::DmDeviceInfo deviceInfo; + ret = DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo(pkgName, deviceInfo); + if (ret != ERR_OK) { + HILOG_WARN("Failed to get local device info."); + return false; + } + MissionDmInitCallback::isInit_ = true; + if (deviceInfo.deviceTypeId != DistributedHardware::DmDeviceType::DEVICE_TYPE_PC) { + HILOG_WARN("The device is not a laptop."); + return false; + } + isPC_ = true; + return isPC_; +} + +bool MissionListManager::MissionDmInitCallback::isInit_ = false; +void MissionListManager::MissionDmInitCallback::OnRemoteDied() +{ + isInit_ = false; + HILOG_WARN("DeviceManager died."); +} + +void MissionListManager::RegisterSnapshotHandler(const sptr& handler) +{ + DelayedSingleton::GetInstance()->RegisterSnapshotHandler(handler); +} + +bool MissionListManager::GetMissionSnapshot(int32_t missionId, const sptr& abilityToken, + MissionSnapshot& missionSnapshot) +{ + HILOG_INFO("snapshot: Start get mission snapshot."); + return DelayedSingleton::GetInstance()->GetMissionSnapshot( + missionId, abilityToken, missionSnapshot); +} + +void MissionListManager::GetAbilityRunningInfos(std::vector &info) +{ + std::lock_guard guard(managerLock_); + + auto func = [&info](const std::shared_ptr &mission) { + if (!mission) { + return; + } + + auto ability = mission->GetAbilityRecord(); + if (!ability) { + return; + } + + AbilityRunningInfo runningInfo; + AppExecFwk::RunningProcessInfo processInfo; + + runningInfo.ability = ability->GetWant().GetElement(); + runningInfo.startTime = ability->GetStartTime(); + runningInfo.abilityState = static_cast(ability->GetAbilityState()); + + DelayedSingleton::GetInstance()-> + GetRunningProcessInfoByToken(ability->GetToken(), processInfo); + runningInfo.pid = processInfo.pid_; + runningInfo.uid = processInfo.uid_; + runningInfo.processName = processInfo.processName_; + info.emplace_back(runningInfo); + }; + if (!(defaultStandardList_->GetAllMissions().empty())) { + auto list = defaultStandardList_->GetAllMissions(); + std::for_each(list.begin(), list.end(), func); + } + if (!(defaultSingleList_->GetAllMissions().empty())) { + auto list = defaultSingleList_->GetAllMissions(); + std::for_each(list.begin(), list.end(), func); + } + for (auto missionList : currentMissionLists_) { + if (!(missionList->GetAllMissions().empty())) { + auto list = missionList->GetAllMissions(); + std::for_each(list.begin(), list.end(), func); + } + } +} + +std::shared_ptr MissionListManager::GetCurrentTopAbility(const std::string &bundleName) +{ + for (auto &missionList : currentMissionLists_) { + if (!missionList) { + HILOG_WARN("Invalid missionList."); + continue; + } + + auto abilityRecord = missionList->GetLauncherRoot(); + if (!abilityRecord) { + HILOG_ERROR("Invalid ability record."); + return {}; + } + + auto appInfo = abilityRecord->GetApplicationInfo(); + if (bundleName.compare(appInfo.bundleName)) { + return abilityRecord; + } + } + + return {}; +} + +bool MissionListManager::IsStarted() +{ + std::lock_guard guard(managerLock_); + auto launcherRoot = launcherList_->GetLauncherRoot(); + return launcherRoot != nullptr; +} + +void MissionListManager::PauseManager() +{ + HILOG_INFO("MissionListManager PauseManager. move foreground to background."); + std::lock_guard guard(managerLock_); + std::list> foregroundAbilities; + GetAllForegroundAbilities(foregroundAbilities); + + for (auto& abilityRecord : foregroundAbilities) { + if (!abilityRecord) { + continue; + } + abilityRecord->SetSwitchingPause(true); + MoveToBackgroundTask(abilityRecord); + } +} + +void MissionListManager::ResumeManager() +{ + HILOG_INFO("ResumeManager, back to launcher."); + BackToLauncher(); +} + +void MissionListManager::GetAllForegroundAbilities(std::list>& foregroundList) +{ + std::shared_ptr abilityRecord = nullptr; + for (auto& missionList : currentMissionLists_) { + GetForegroundAbilities(missionList, foregroundList); + } + GetForegroundAbilities(defaultSingleList_, foregroundList); + GetForegroundAbilities(defaultStandardList_, foregroundList); +} + +void MissionListManager::GetForegroundAbilities(const std::shared_ptr& missionList, + std::list>& foregroundList) +{ + if (!missionList || missionList->IsEmpty()) { + return; + } + + for (auto& mission : missionList->GetAllMissions()) { + if (!mission) { + continue; + } + + auto abilityRecord = mission->GetAbilityRecord(); + if (!abilityRecord) { + continue; + } + + if (abilityRecord->IsActiveState()) { + foregroundList.emplace_back(abilityRecord); + } + } +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/mission_listener_controller.cpp b/services/abilitymgr/src/mission_listener_controller.cpp index e544c3fbbaad05162e062b0724305165b9c1ce94..ecf9de4e8758e35d4de48e3e6e2d7565b08965f1 100644 --- a/services/abilitymgr/src/mission_listener_controller.cpp +++ b/services/abilitymgr/src/mission_listener_controller.cpp @@ -100,9 +100,14 @@ void MissionListenerController::NotifyMissionCreated(int32_t missionId) HILOG_ERROR("handler not init"); return; } - - auto self(shared_from_this()); - auto task = [self, missionId]() { self->NotifyListeners(missionId, Cmd::ON_MISSION_CREATED); }; + auto task = [weak = weak_from_this(), missionId]() { + auto self = weak.lock(); + if (self == nullptr) { + HILOG_ERROR("self is nullptr, NotifyMissionCreated failed."); + return; + } + self->NotifyListeners(missionId, Cmd::ON_MISSION_CREATED); + }; handler_->PostTask(task); } @@ -112,9 +117,14 @@ void MissionListenerController::NotifyMissionDestroyed(int32_t missionId) HILOG_ERROR("handler not init"); return; } - - auto self(shared_from_this()); - auto task = [self, missionId]() { self->NotifyListeners(missionId, Cmd::ON_MISSION_DESTROYED); }; + auto task = [weak = weak_from_this(), missionId]() { + auto self = weak.lock(); + if (self == nullptr) { + HILOG_ERROR("self is nullptr, NotifyMissionDestroyed failed."); + return; + } + self->NotifyListeners(missionId, Cmd::ON_MISSION_DESTROYED); + }; handler_->PostTask(task); } @@ -125,8 +135,14 @@ void MissionListenerController::NotifyMissionSnapshotChanged(int32_t missionId) return; } - auto self(shared_from_this()); - auto task = [self, missionId]() { self->NotifyListeners(missionId, Cmd::ON_MISSION_SNAPSHOT_CHANGED); }; + auto task = [weak = weak_from_this(), missionId]() { + auto self = weak.lock(); + if (self == nullptr) { + HILOG_ERROR("self is nullptr, NotifyMissionSnapshotChanged failed."); + return; + } + self->NotifyListeners(missionId, Cmd::ON_MISSION_SNAPSHOT_CHANGED); + }; handler_->PostTask(task); } @@ -137,8 +153,14 @@ void MissionListenerController::NotifyMissionMovedToFront(int32_t missionId) return; } - auto self(shared_from_this()); - auto task = [self, missionId]() { self->NotifyListeners(missionId, Cmd::ON_MISSION_MOVED_TO_FRONT); }; + auto task = [weak = weak_from_this(), missionId]() { + auto self = weak.lock(); + if (self == nullptr) { + HILOG_ERROR("self is nullptr, NotifyMissionSnapshotChanged failed."); + return; + } + self->NotifyListeners(missionId, Cmd::ON_MISSION_MOVED_TO_FRONT); + }; handler_->PostTask(task); } diff --git a/services/abilitymgr/src/mission_snapshot.cpp b/services/abilitymgr/src/mission_snapshot.cpp index 1cb4cc918853ecf2dd85dfd87832c577220c1424..05caf6b6fa11132b679cb54ce288184493da5403 100644 --- a/services/abilitymgr/src/mission_snapshot.cpp +++ b/services/abilitymgr/src/mission_snapshot.cpp @@ -60,5 +60,45 @@ bool MissionPixelMap::Marshalling(Parcel &parcel) const } return true; } + +bool MissionSnapshot::ReadFromParcel(Parcel &parcel) +{ + std::unique_ptr ability(parcel.ReadParcelable()); + if (ability == nullptr) { + return false; + } + topAbility = *ability; + std::shared_ptr pixelMap(parcel.ReadParcelable()); + if (ability == nullptr) { + return false; + } + snapshot = pixelMap; + return true; +} + +MissionSnapshot *MissionSnapshot::Unmarshalling(Parcel &parcel) +{ + MissionSnapshot *info = new (std::nothrow) MissionSnapshot(); + if (info == nullptr) { + return nullptr; + } + + if (!info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + return info; +} + +bool MissionSnapshot::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(&topAbility)) { + return false; + } + if (!parcel.WriteParcelable(snapshot.get())) { + return false; + } + return true; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index 256e8684f09d8b01c8adedb9fb2a211533481084..f7461d333c9aec19453050c2e60d7df1ea15c303 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -21,6 +21,7 @@ #include "ability_manager_service.h" #include "ability_util.h" +#include "distributed_client.h" #include "hilog_wrapper.h" namespace OHOS { @@ -213,28 +214,53 @@ void PendingWantManager::CancelWantSenderLocked(PendingWantRecord &record, bool wantRecords_.erase(record.GetKey()); } } +int32_t PendingWantManager::DeviceIdDetermine( + const Want &want, const sptr &callerToken, int32_t requestCode, const int32_t callerUid) +{ + int32_t result = ERR_OK; + if (want.GetElement().GetDeviceID() == "") { + result = DelayedSingleton::GetInstance()->StartAbility( + want, callerToken, requestCode, callerUid); + if (result != ERR_OK && result != START_ABILITY_WAITING) { + HILOG_ERROR("%{public}s:result != ERR_OK && result != START_ABILITY_WAITING.", __func__); + } + return result; + } + + sptr remoteObject = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); + if (remoteObject == nullptr) { + HILOG_ERROR("failed to get distributed schedule manager service"); + result = ERR_INVALID_VALUE; + return result; + } + DistributedClient dmsClient; + result = dmsClient.StartRemoteAbility(want, callerUid, requestCode); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s: StartRemoteAbility Error! result = %{public}d", __func__, result); + } + + return result; +} int32_t PendingWantManager::PendingWantStartAbility( - const Want &want, const sptr &callerToken, int32_t requestCode, int32_t callerUid) + const Want &want, const sptr &callerToken, int32_t requestCode, const int32_t callerUid) { HILOG_INFO("%{public}s:begin.", __func__); - return DelayedSingleton::GetInstance()->StartAbility( - want, callerToken, requestCode, callerUid); + int32_t result = DeviceIdDetermine(want, callerToken, requestCode, callerUid); + return result; } int32_t PendingWantManager::PendingWantStartAbilitys(const std::vector wantsInfo, - const sptr &callerToken, int32_t requestCode, int32_t callerUid) + const sptr &callerToken, int32_t requestCode, const int32_t callerUid) { HILOG_INFO("%{public}s:begin.", __func__); int32_t result = ERR_OK; for (const auto &item : wantsInfo) { - const auto &want = item.want; - result = DelayedSingleton::GetInstance()->StartAbility( - want, callerToken, requestCode, callerUid); - if (result != ERR_OK && result != START_ABILITY_WAITING) { - HILOG_ERROR("%{public}s:result != ERR_OK && result != START_ABILITY_WAITING.", __func__); - return result; + auto res = DeviceIdDetermine(item.want, callerToken, requestCode, callerUid); + if (res != ERR_OK && res != START_ABILITY_WAITING) { + result = res; } } return result; @@ -458,7 +484,7 @@ void PendingWantManager::ClearPendingWantRecord(const std::string &bundleName) CHECK_POINTER(abilityManagerService); auto handler = abilityManagerService->GetEventHandler(); CHECK_POINTER(handler); - auto task = [bundleName, this]() { ClearPendingWantRecordTask(bundleName); }; + auto task = [bundleName, self = shared_from_this()]() { self->ClearPendingWantRecordTask(bundleName); }; handler->PostTask(task); } @@ -489,5 +515,37 @@ void PendingWantManager::ClearPendingWantRecordTask(const std::string &bundleNam } } } + +void PendingWantManager::Dump(std::vector &info) +{ + std::string dumpInfo = " PendingWantRecords:"; + info.push_back(dumpInfo); + + for (const auto &item : wantRecords_) { + const auto &pendingKey = item.first; + dumpInfo = " PendWantRecord ID #" + std::to_string(pendingKey->GetUserId()) + + " type #" + std::to_string(pendingKey->GetType()); + info.push_back(dumpInfo); + dumpInfo = " bundle name [" + pendingKey->GetBundleName() + "]"; + info.push_back(dumpInfo); + dumpInfo = " result who [" + pendingKey->GetRequestWho() + "]"; + info.push_back(dumpInfo); + dumpInfo = " request code #" + std::to_string(pendingKey->GetRequestCode()) + + " flags #" + std::to_string(pendingKey->GetFlags()); + info.push_back(dumpInfo); + dumpInfo = " resolved type [" + pendingKey->GetRequestResolvedType() + "]"; + info.push_back(dumpInfo); + dumpInfo = " Wants:"; + info.push_back(dumpInfo); + auto Wants = pendingKey->GetAllWantsInfos(); + for (const auto &Want : Wants) { + dumpInfo = " uri [" + Want.want.GetElement().GetDeviceID() + "//" + + Want.want.GetElement().GetBundleName() + "/" + Want.want.GetElement().GetAbilityName() + "]"; + info.push_back(dumpInfo); + dumpInfo = " resolved types [" + Want.resolvedTypes + "]"; + info.push_back(dumpInfo); + } + } +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/start_options.cpp b/services/abilitymgr/src/start_options.cpp index 737cc87316449b6e74fc0162555f25f0e8f0a4da..20eb4bfd33af410f4bf68d5d27c14aa979080452 100644 --- a/services/abilitymgr/src/start_options.cpp +++ b/services/abilitymgr/src/start_options.cpp @@ -18,11 +18,12 @@ namespace OHOS { namespace AAFwk { -const std::string StartOptions::STRING_WINDOW_MODE = "ohos.aafwk.windowMode"; +const std::string StartOptions::STRING_DISPLAY_ID = "ohos.aafwk.displayId"; bool StartOptions::ReadFromParcel(Parcel &parcel) { SetWindowMode(parcel.ReadInt32()); + SetDisplayID(parcel.ReadInt32()); return true; } @@ -44,6 +45,7 @@ StartOptions *StartOptions::Unmarshalling(Parcel &parcel) bool StartOptions::Marshalling(Parcel &parcel) const { parcel.WriteInt32(GetWindowMode()); + parcel.WriteInt32(GetDisplayID()); return true; } @@ -56,5 +58,15 @@ int32_t StartOptions::GetWindowMode() const { return windowMode_; } + +void StartOptions::SetDisplayID(int32_t id) +{ + displayId_ = id; +} + +int32_t StartOptions::GetDisplayID() const +{ + return displayId_; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/task_data_persistence_mgr.cpp b/services/abilitymgr/src/task_data_persistence_mgr.cpp index 440e91df768381ee0920275bad36987825c7053c..382259f0a90e9c96def42d125ad58f545ba570f9 100644 --- a/services/abilitymgr/src/task_data_persistence_mgr.cpp +++ b/services/abilitymgr/src/task_data_persistence_mgr.cpp @@ -15,6 +15,7 @@ #include "task_data_persistence_mgr.h" #include "ability_util.h" +#include "file_util.h" #include "hilog_wrapper.h" namespace OHOS { @@ -49,6 +50,7 @@ bool TaskDataPersistenceMgr::Init(int userId) } else { currentMissionDataStorage_ = missionDataStorageMgr_[userId]; } + currentUserId_ = userId; CHECK_POINTER_RETURN_BOOL(currentMissionDataStorage_); HILOG_INFO("Init success."); @@ -88,5 +90,40 @@ bool TaskDataPersistenceMgr::DeleteMissionInfo(int missionId) currentMissionDataStorage_, missionId); return handler_->PostTask(DeleteMissionInfoFunc, DELETE_MISSION_INFO); } + +bool TaskDataPersistenceMgr::RemoveUserDir(int32_t userId) +{ + if (currentUserId_ == userId) { + HILOG_ERROR("can not removed current user dir"); + return false; + } + std::string userDir = TASK_DATA_FILE_BASE_PATH + "/" + std::to_string(userId); + bool ret = OHOS::HiviewDFX::FileUtil::ForceRemoveDirectory(userDir); + if (!ret) { + HILOG_ERROR("remove user dir %{public}s failed.", userDir.c_str()); + return false; + } + return true; +} + +bool TaskDataPersistenceMgr::SaveMissionSnapshot(int missionId, const MissionSnapshot& snapshot) +{ + if (!handler_ || !currentMissionDataStorage_) { + HILOG_ERROR("snapshot: handler_ or currentMissionDataStorage_ is nullptr"); + return false; + } + std::function SaveMissionSnapshotFunc = std::bind(&MissionDataStorage::SaveMissionSnapshot, + currentMissionDataStorage_, missionId, snapshot); + return handler_->PostTask(SaveMissionSnapshotFunc, SAVE_MISSION_SNAPSHOT); +} + +bool TaskDataPersistenceMgr::GetMissionSnapshot(int missionId, MissionSnapshot& snapshot) +{ + if (!currentMissionDataStorage_) { + HILOG_ERROR("snapshot: currentMissionDataStorage_ is nullptr"); + return false; + } + return currentMissionDataStorage_->GetMissionSnapshot(missionId, snapshot); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/user_controller.cpp b/services/abilitymgr/src/user_controller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97a45404ad15c799f1553bb079763307f8662248 --- /dev/null +++ b/services/abilitymgr/src/user_controller.cpp @@ -0,0 +1,478 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "user_controller.h" + +#include "ability_manager_service.h" +#include "hilog_wrapper.h" +#include "ipc_skeleton.h" +#include "os_account_manager.h" +#include "task_data_persistence_mgr.h" + +namespace OHOS { +namespace AAFwk { +using namespace OHOS::AppExecFwk; +namespace { +const int64_t USER_SWITCH_TIMEOUT = 3 * 1000; // 3s +} + +UserItem::UserItem(int32_t id) : userId_(id) +{} + +UserItem::~UserItem() {} + +int32_t UserItem::GetUserId() +{ + return userId_; +} + +void UserItem::SetState(const UserState &state) +{ + if (curState_ == state) { + return; + } + lastState_ = curState_; + curState_ = state; +} + +UserState UserItem::GetState() +{ + return curState_; +} + +UserController::UserController() +{ +} + +UserController::~UserController() +{ +} + +void UserController::Init() +{ + auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + if (!handler) { + return; + } + + auto runner = handler->GetEventRunner(); + if (!runner) { + return; + } + + if (eventHandler_) { + return; + } + eventHandler_ = std::make_shared(runner, shared_from_this()); +} + +int32_t UserController::StartUser(int32_t userId, bool isForeground) +{ + if (userId < 0 || userId == USER_ID_NO_HEAD) { + HILOG_ERROR("StartUser userId is invalid:%{public}d", userId); + return -1; + } + + if (IsCurrentUser(userId)) { + HILOG_WARN("StartUser user is already current:%{public}d", userId); + return 0; + } + + if (!IsExistOsAccount(userId)) { + HILOG_ERROR("StartUser not exist such account:%{public}d", userId); + return -1; + } + + if (isForeground) { + // start freezing screen + DelayedSingleton::GetInstance()->StartFreezingScreen(); + } + + auto oldUserId = GetCurrentUserId(); + auto userItem = GetOrCreateUserItem(userId); + auto state = userItem->GetState(); + if (state == STATE_STOPPING || state == STATE_SHUTDOWN) { + HILOG_ERROR("StartUser user is stop now, userId:%{public}d", userId); + return -1; + } + + if (isForeground) { + SetCurrentUserId(userId); + // todo : notify wms switching now + } + + bool needStart = false; + if (state == STATE_BOOTING) { + needStart = true; + // send user start msg. + SendSystemUserStart(userId); + } + + if (isForeground) { + SendSystemUserCurrent(oldUserId, userId); + SendReportUserSwitch(oldUserId, userId, userItem); + SendUserSwitchTimeout(oldUserId, userId, userItem); + } + + if (needStart) { + BroadcastUserStarted(userId); + } + + UserBootDone(userItem); + if (isForeground) { + MoveUserToForeground(oldUserId, userId); + } + + return 0; +} + +int32_t UserController::StopUser(int32_t userId) +{ + if (userId < 0 || userId == USER_ID_NO_HEAD || userId == USER_ID_DEFAULT) { + HILOG_ERROR("userId is invalid:%{public}d", userId); + return -1; + } + + if (IsCurrentUser(userId)) { + HILOG_WARN("user is already current:%{public}d", userId); + return 0; + } + + if (!IsExistOsAccount(userId)) { + HILOG_ERROR("not exist such account:%{public}d", userId); + return -1; + } + + BroadcastUserStopping(userId); + + auto appScheduler = DelayedSingleton::GetInstance(); + if (!appScheduler) { + HILOG_ERROR("appScheduler is null"); + return -1; + } + appScheduler->KillProcessesByUserId(userId); + + auto taskDataPersistenceMgr = DelayedSingleton::GetInstance(); + if (!taskDataPersistenceMgr) { + HILOG_ERROR("taskDataPersistenceMgr is null"); + return -1; + } + taskDataPersistenceMgr->RemoveUserDir(userId); + + auto abilityManagerService = DelayedSingleton::GetInstance(); + if (!abilityManagerService) { + HILOG_ERROR("abilityManagerService is null"); + return -1; + } + abilityManagerService->ClearUserData(userId); + + BroadcastUserStopped(userId); + return 0; +} + +int32_t UserController::GetCurrentUserId() +{ + std::lock_guard guard(userLock_); + return currentUserId_; +} + +std::shared_ptr UserController::GetUserItem(int32_t userId) +{ + std::lock_guard guard(userLock_); + auto it = userItems_.find(userId); + if (it != userItems_.end()) { + return it->second; + } + + return nullptr; +} + +bool UserController::IsCurrentUser(int32_t userId) +{ + int32_t oldUserId = GetCurrentUserId(); + if (oldUserId == userId) { + auto userItem = GetUserItem(userId); + if (userItem) { + HILOG_WARN("IsCurrentUser userId is already current:%{public}d", userId); + return true; + } + } + return false; +} + +bool UserController::IsExistOsAccount(int32_t userId) +{ + bool isExist = false; + auto errCode = AccountSA::OsAccountManager::IsOsAccountExists(userId, isExist); + return (errCode == 0) && isExist; +} + +std::shared_ptr UserController::GetOrCreateUserItem(int32_t userId) +{ + std::lock_guard guard(userLock_); + auto it = userItems_.find(userId); + if (it != userItems_.end()) { + return it->second; + } + + auto userItem = std::make_shared(userId); + userItems_.emplace(userId, userItem); + return userItem; +} + +void UserController::SetCurrentUserId(int32_t userId) +{ + std::lock_guard guard(userLock_); + currentUserId_ = userId; +} + +void UserController::MoveUserToForeground(int32_t oldUserId, int32_t newUserId) +{ + auto manager = DelayedSingleton::GetInstance(); + if (!manager) { + return; + } + manager->SwitchToUser(oldUserId, newUserId); + BroadcastUserBackground(oldUserId); + BroadcastUserForeground(newUserId); +} + +void UserController::UserBootDone(std::shared_ptr &item) +{ + if (!item) { + return; + } + int32_t userId = item->GetUserId(); + + std::lock_guard guard(userLock_); + auto it = userItems_.find(userId); + if (it != userItems_.end()) { + return; + } + + if (item != it->second) { + return; + } + item->SetState(UserState::STATE_STARTED); + auto manager = DelayedSingleton::GetInstance(); + if (!manager) { + return; + } + manager->UserStarted(userId); +} + +void UserController::BroadcastUserStarted(int32_t userId) +{ + // todo: broadcast event user start. +} + +void UserController::BroadcastUserBackground(int32_t userId) +{ + // todo: broadcast event user switch to bg. +} + +void UserController::BroadcastUserForeground(int32_t userId) +{ + // todo: broadcast event user switch to fg. +} + +void UserController::BroadcastUserStopping(int32_t userId) +{ + // todo +} + +void UserController::BroadcastUserStopped(int32_t userId) +{ + // todo +} + +void UserController::SendSystemUserStart(int32_t userId) +{ + auto handler = eventHandler_; + if (!handler) { + return; + } + + std::shared_ptr eventData = std::make_shared(); + eventData->newUserId = userId; + auto event = InnerEvent::Get(UserEventHandler::EVENT_SYSTEM_USER_START, eventData); + handler->SendEvent(event); +} + +void UserController::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) +{ + if (!event) { + return; + } + + auto eventId = event->GetInnerEventId(); + auto eventData = event->GetSharedObject(); + if (!eventData) { + HILOG_DEBUG("no event data, event id: %{public}u.", eventId); + return; + } + + HILOG_DEBUG("Event id obtained: %{public}u.", eventId); + switch (eventId) { + case UserEventHandler::EVENT_SYSTEM_USER_START: { + HandleSystemUserStart(eventData->newUserId); + break; + } + case UserEventHandler::EVENT_SYSTEM_USER_CURRENT: { + HandleSystemUserCurrent(eventData->oldUserId, eventData->newUserId); + break; + } + case UserEventHandler::EVENT_REPORT_USER_SWITCH: { + HandleReportUserSwitch(eventData->oldUserId, eventData->newUserId, eventData->userItem); + break; + } + case UserEventHandler::EVENT_CONTINUE_USER_SWITCH: { + HandleContinueUserSwitch(eventData->oldUserId, eventData->newUserId, eventData->userItem); + break; + } + case UserEventHandler::EVENT_USER_SWITCH_TIMEOUT: { + HandleUserSwitchTimeout(eventData->oldUserId, eventData->newUserId, eventData->userItem); + break; + } + case UserEventHandler::EVENT_REPORT_USER_SWITCH_DONE: { + HandleUserSwitchDone(eventData->newUserId); + break; + } + default: { + HILOG_WARN("Unsupported event."); + break; + } + } +} + +void UserController::SendSystemUserCurrent(int32_t oldUserId, int32_t newUserId) +{ + auto handler = eventHandler_; + if (!handler) { + return; + } + + std::shared_ptr eventData = std::make_shared(); + eventData->oldUserId = oldUserId; + eventData->newUserId = newUserId; + auto event = InnerEvent::Get(UserEventHandler::EVENT_SYSTEM_USER_CURRENT, eventData); + handler->SendEvent(event); +} + +void UserController::SendReportUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem) +{ + auto handler = eventHandler_; + if (!handler) { + return; + } + + handler->RemoveEvent(UserEventHandler::EVENT_REPORT_USER_SWITCH); + std::shared_ptr eventData = std::make_shared(); + eventData->oldUserId = oldUserId; + eventData->newUserId = newUserId; + eventData->userItem = usrItem; + auto event = InnerEvent::Get(UserEventHandler::EVENT_REPORT_USER_SWITCH, eventData); + handler->SendEvent(event); +} + +void UserController::SendUserSwitchTimeout(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem) +{ + auto handler = eventHandler_; + if (!handler) { + return; + } + + handler->RemoveEvent(UserEventHandler::EVENT_USER_SWITCH_TIMEOUT); + std::shared_ptr eventData = std::make_shared(); + eventData->oldUserId = oldUserId; + eventData->newUserId = newUserId; + eventData->userItem = usrItem; + auto event = InnerEvent::Get(UserEventHandler::EVENT_USER_SWITCH_TIMEOUT, eventData); + handler->SendEvent(event, USER_SWITCH_TIMEOUT); +} + +void UserController::SendContinueUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem) +{ + auto handler = eventHandler_; + if (!handler) { + return; + } + + handler->RemoveEvent(UserEventHandler::EVENT_USER_SWITCH_TIMEOUT); + std::shared_ptr eventData = std::make_shared(); + eventData->oldUserId = oldUserId; + eventData->newUserId = newUserId; + eventData->userItem = usrItem; + auto event = InnerEvent::Get(UserEventHandler::EVENT_CONTINUE_USER_SWITCH, eventData); + handler->SendEvent(event); +} + +void UserController::SendUserSwitchDone(int32_t userId) +{ + auto handler = eventHandler_; + if (!handler) { + return; + } + + handler->RemoveEvent(UserEventHandler::EVENT_REPORT_USER_SWITCH_DONE); + std::shared_ptr eventData = std::make_shared(); + eventData->newUserId = userId; + auto event = InnerEvent::Get(UserEventHandler::EVENT_REPORT_USER_SWITCH_DONE, eventData); + handler->SendEvent(event); +} + +void UserController::HandleSystemUserStart(int32_t userId) +{ + // todo : notify system mgr user start. +} + +void UserController::HandleSystemUserCurrent(int32_t oldUserId, int32_t newUserId) +{ + // todo : notify system mgr user switch to new. +} + +void UserController::HandleReportUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem) +{ + // todo : notify user switch observers, not support yet. +} + +void UserController::HandleUserSwitchTimeout(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem) +{ + // todo : other observers + SendContinueUserSwitch(oldUserId, newUserId, usrItem); +} + +void UserController::HandleContinueUserSwitch(int32_t oldUserId, int32_t newUserId, + std::shared_ptr &usrItem) +{ + auto manager = DelayedSingleton::GetInstance(); + if (manager) { + manager->StopFreezingScreen(); + } + SendUserSwitchDone(newUserId); +} + +void UserController::HandleUserSwitchDone(int32_t userId) +{ + // todo : notify wms switching done. + // todo : notify user switch observers. +} +} +} diff --git a/services/abilitymgr/src/user_event_handler.cpp b/services/abilitymgr/src/user_event_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c701713518f37bacd1f78b781517579498be8aeb --- /dev/null +++ b/services/abilitymgr/src/user_event_handler.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "user_event_handler.h" + +#include "user_controller.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +UserEventHandler::UserEventHandler( + const std::shared_ptr &runner, const std::weak_ptr &owner) + : AppExecFwk::EventHandler(runner), controller_(owner) +{ +} + +void UserEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) +{ + if (!event) { + HILOG_ERROR("invalid event"); + return; + } + + auto owner = controller_.lock(); + if (owner) { + owner->ProcessEvent(event); + } +} +} // namespace AAFwk +} // namespace OHOS diff --git a/services/abilitymgr/test/BUILD.gn b/services/abilitymgr/test/BUILD.gn index 46829a95314287cb071885847e84712d715320b7..f131c140d4d413a6285d26b83525370122839498 100644 --- a/services/abilitymgr/test/BUILD.gn +++ b/services/abilitymgr/test/BUILD.gn @@ -34,8 +34,9 @@ ohos_source_set("abilityms_test_source") { "${services_path}/abilitymgr/src/ability_start_setting.cpp", "${services_path}/abilitymgr/src/ability_token_stub.cpp", "${services_path}/abilitymgr/src/ams_configuration_parameter.cpp", + "${services_path}/abilitymgr/src/call_container.cpp", + "${services_path}/abilitymgr/src/call_record.cpp", "${services_path}/abilitymgr/src/caller_info.cpp", - "${services_path}/abilitymgr/src/configuration_distributor.cpp", "${services_path}/abilitymgr/src/connection_record.cpp", "${services_path}/abilitymgr/src/data_ability_caller_recipient.cpp", "${services_path}/abilitymgr/src/data_ability_manager.cpp", @@ -82,6 +83,8 @@ ohos_source_set("abilityms_test_source") { "${services_path}/abilitymgr/src/stack_info.cpp", "${services_path}/abilitymgr/src/stack_setting.cpp", "${services_path}/abilitymgr/src/task_data_persistence_mgr.cpp", + "${services_path}/abilitymgr/src/user_controller.cpp", + "${services_path}/abilitymgr/src/user_event_handler.cpp", "${services_path}/abilitymgr/src/want_receiver_proxy.cpp", "${services_path}/abilitymgr/src/want_receiver_stub.cpp", "${services_path}/abilitymgr/src/want_sender_info.cpp", @@ -97,8 +100,14 @@ ohos_source_set("abilityms_test_source") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager/include", + "//base/account/os_account/frameworks/common/account_error/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/log/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "//base/hiviewdfx/hicollie/interfaces/native/innerkits/include/xcollie", ] external_dependent_files = [ @@ -119,11 +128,14 @@ ohos_source_set("abilityms_test_source") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${innerkits_path}/base:base", "${innerkits_path}/want:want", "${services_path}/abilitymgr/test/mock/libs/sa_mgr:sa_mgr_mock", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/hiviewdfx/hiview/adapter/utility:hiview_adapter_utility", + "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", @@ -137,11 +149,13 @@ ohos_source_set("abilityms_test_source") { "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", "dsoftbus_standard:softbus_client", + "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", "native_appdatamgr:native_dataability", "native_appdatamgr:native_rdb", + "resmgr_standard:global_resmgr", ] } diff --git a/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn b/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn index 41fdf972e0b2230af415ef2f0d879bf11ba6a257..3d751c3e92058a880bf3aeab19e45fb9ec412ed7 100644 --- a/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn +++ b/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn @@ -20,7 +20,7 @@ config("appmgr_test_service_config") { "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/services/common/include", "//base/notification/ces_standard/frameworks/core/include", @@ -45,6 +45,7 @@ ohos_source_set("appmgr_test_service") { } deps = [ "${innerkits_path}/want:want", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", diff --git a/services/abilitymgr/test/mock/include/mock_app_manager_client.h b/services/abilitymgr/test/mock/include/mock_app_manager_client.h index b05c3802034f2f8292a662a4e6c95f7b69172f3b..ffd8d4d331b55915a26c01d3e4b9ef3e94152951 100644 --- a/services/abilitymgr/test/mock/include/mock_app_manager_client.h +++ b/services/abilitymgr/test/mock/include/mock_app_manager_client.h @@ -40,6 +40,7 @@ public: AppMgrResultCode(const sptr &token, const sptr &preToken, const int32_t visibility, const int32_t perceptibility, const int32_t connectionState)); MOCK_METHOD1(KillProcessByAbilityToken, AppMgrResultCode(const sptr &token)); + MOCK_METHOD1(KillProcessesByUserId, AppMgrResultCode(int32_t userId)); MOCK_METHOD4(CompelVerifyPermission, int(const std::string &permission, int pid, int uid, std::string &message)); }; } // namespace AppExecFwk diff --git a/services/abilitymgr/test/mock/libs/aakit/BUILD.gn b/services/abilitymgr/test/mock/libs/aakit/BUILD.gn index 46187c7163e698955e425921ff3ae1a4323185b1..cb0d6c799903cb6224518d9443bda343bf8ac5bf 100644 --- a/services/abilitymgr/test/mock/libs/aakit/BUILD.gn +++ b/services/abilitymgr/test/mock/libs/aakit/BUILD.gn @@ -21,6 +21,7 @@ config("aakit_mock_config") { "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/", "include/", "//third_party/jsoncpp/include", @@ -42,6 +43,7 @@ ohos_source_set("aakit_mock") { } deps = [ "${innerkits_path}/want:want", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", diff --git a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h index 53d3ee13b37bf38ce381b82038f85ec0af56b7e8..03bb8e5c183f9a09b5bf7320e82f049387619487 100755 --- a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h +++ b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h @@ -101,6 +101,12 @@ public: {}; virtual void ContinueAbility(const std::string& deviceId) override {}; + virtual void DumpAbilityInfo(std::vector &info) override + {}; + virtual sptr CallRequest() override + { + return sptr(nullptr); + }; private: AbilityResult result_; }; diff --git a/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h b/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h index 3d9b8a8f2c7ba4329c3eed3c50ff57a8bd195c11..34bcf6228f5ab4af557b514bdd3d538270aa7c60 100755 --- a/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h +++ b/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h @@ -43,6 +43,7 @@ public: MOCK_METHOD2(NotifyMultiWinModeChanged, void(int32_t winModeKey, bool flag)); MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); int InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -141,6 +142,11 @@ public: return std::vector>(); } + virtual sptr CallRequest() + { + return sptr(nullptr); + } + int code_ = 0; }; } // namespace AAFwk diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn b/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn index e8c19894c2ada0116b0e9a2872072a1bf6ecc5c5..4fd28ea4ce44b1a6ba5f431d264ad1404c3daa4e 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn @@ -22,7 +22,7 @@ config("appexecfwk_core_mock_config") { "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/", "//base/telephony/core_service/sim/include/", "//base/notification/ces_standard/frameworks/core/include/", @@ -43,6 +43,7 @@ ohos_source_set("appexecfwk_appmgr_mock") { } deps = [ "${innerkits_path}/want:want", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h index 2688800e3b015151122c8006e5e9949f2c5ffb20..607c1fbf4d23bdc73ebfd6aee66594426065f213 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h @@ -107,6 +107,15 @@ public: */ virtual AppMgrResultCode KillProcessByAbilityToken(const sptr &token); + /** + * KillProcessesByUserId, call KillProcessesByUserId() through proxy object, + * kill the processes by user id. + * + * @param userId, the user id. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode KillProcessesByUserId(int32_t userId); + /** * KillApplication, call KillApplication() through proxy object, kill the application. * diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h index adcaa9c71fdecab169652e42bc39d075a6677390..d911ef15d0a2bf06c273b82d61e9c62f15542fc3 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h @@ -31,6 +31,7 @@ #include "common_event_info.h" #include "on_permission_changed_callback_interface.h" #include "ohos/aafwk/content/want.h" +#include "distributed_bundle_info.h" namespace OHOS { namespace AppExecFwk { @@ -441,6 +442,9 @@ public: virtual bool RemoveClonedBundle(const std::string &bundleName, const int32_t uid) = 0; virtual bool BundleClone(const std::string &bundleName) = 0; virtual bool CheckBundleNameInAllowList(const std::string &bundleName) = 0; + virtual bool GetDistributedBundleInfo( + const std::string &networkId, int32_t userId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) = 0; enum class Message { GET_APPLICATION_INFO, @@ -491,7 +495,7 @@ public: GET_ALL_FORMS_INFO, GET_FORMS_INFO_BY_APP, GET_FORMS_INFO_BY_MODULE, - GET_MODULE_USAGE_RECORD, + GET_MODULE_USAGE_RECORD, GET_SHORTCUT_INFO, GET_ALL_COMMON_EVENT_INFO, GET_BUNDLE_INSTALLER, diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h index 2eea64e49543ac8c01469ed0bc0a64ed703831ae..e7b572911db278d4503fdbc1bb3641f614e464df 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h @@ -36,6 +36,7 @@ const std::string COM_IX_HIRADIO = "com.ix.hiRadio"; const std::string COM_IX_HISERVICE = "com.ix.hiService"; const std::string COM_IX_MUSICSERVICE = "com.ix.musicService"; const std::string COM_IX_HIDATA = "com.ix.hiData"; +const std::string COM_IX_HIEXTENSION = "com.ix.hiExtension"; constexpr int32_t MAX_SYS_UID = 2899; constexpr int32_t ROOT_UID = 0; @@ -123,6 +124,16 @@ auto HiDataInfo = [](std::string bundleName, AbilityInfo &abilityInfo, ElementNa abilityInfo.process = "p6"; return true; }; + +auto HiExtensionInfo = [](std::string bundleName, AbilityInfo &abilityInfo, ElementName &elementTemp) { + abilityInfo.name = elementTemp.GetAbilityName(); + abilityInfo.bundleName = elementTemp.GetBundleName(); + abilityInfo.applicationInfo.bundleName = elementTemp.GetBundleName(); + abilityInfo.applicationName = "hiExtension"; + abilityInfo.applicationInfo.name = "hiExtension"; + abilityInfo.type = AbilityType::EXTENSION; + return true; +}; } // namespace class BundleMgrProxy : public IRemoteProxy { public: @@ -143,7 +154,8 @@ public: const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) override; + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) + override; virtual bool CheckIsSystemAppByUid(const int uid) override; MOCK_METHOD3(GetApplicationInfos, bool(const ApplicationFlag flag, const int userId, std::vector &appInfos)); @@ -227,7 +239,8 @@ public: bool CheckWantEntity(const AAFwk::Want &, AbilityInfo &); virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) override; + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) + override; MOCK_METHOD2(QueryWantAbility, int(const AAFwk::Want &want, std::vector &abilityInfos)); MOCK_METHOD3(GetApplicationInfos, bool(const ApplicationFlag flag, const int userId, std::vector &appInfos)); @@ -315,6 +328,12 @@ public: { return true; } + virtual bool GetDistributedBundleInfo( + const std::string &networkId, int32_t userId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) override + { + return true; + } public: using QueryAbilityInfoFunType = diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp index 6fc4637e10607fc4bc8438308ee4d0270da5d383..c5ad1856b2816ffaa29c3f8718678662ad29d556 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp @@ -72,6 +72,11 @@ AppMgrResultCode AppMgrClient::KillProcessByAbilityToken(const sptr &token) HILOG_INFO("Test AppScheduler::KillProcessByAbilityToken()"); } +void AppScheduler::KillProcessesByUserId(int32_t userId) +{ + HILOG_INFO("Test AppScheduler::KillProcessesByUserId()"); +} + AppAbilityState AppScheduler::ConvertToAppAbilityState(const int32_t state) { AppExecFwk::AbilityState abilityState = static_cast(state); @@ -159,5 +164,30 @@ void AppScheduler::StartupResidentProcess() { HILOG_INFO("Test AppScheduler::StartupResidentProcess()"); } + +int AppScheduler::GetProcessRunningInfos(std::vector &info) +{ + HILOG_INFO("Test AppScheduler::GetProcessRunningInfos()"); + return 0; +} + +void AppScheduler::GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) +{ + HILOG_INFO("Test AppScheduler::GetRunningProcessInfoByToken()"); +} + +void AppScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +{} + +int AppScheduler::StartUserTest(const Want &want, const sptr &observer, + const AppExecFwk::BundleInfo &bundleInfo) +{ + return 0; +} + +int AppScheduler::UpdateConfiguration(const AppExecFwk::Configuration &) +{ + return 0; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp index 989dfbfbef47e1d92fa2e55057dbf46b176c7d9f..2b08969a3bfbdf7f61da222f16c35b759ead9c23 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp @@ -88,6 +88,7 @@ BundleMgrService::BundleMgrService() abilityInfoMap_.emplace(COM_IX_HISERVICE, HiServiceInfo); abilityInfoMap_.emplace(COM_IX_MUSICSERVICE, MusicServiceInfo); abilityInfoMap_.emplace(COM_IX_HIDATA, HiDataInfo); + abilityInfoMap_.emplace(COM_IX_HIEXTENSION, HiExtensionInfo); GTEST_LOG_(INFO) << "BundleMgrService()"; } diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn old mode 100644 new mode 100755 index 94aa03013e1aed0899e866a9d444402dd74c2fbe..77e68597de69685eb5ea452d0016eabd3fc82fb3 --- a/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_connect_callback_proxy_test") { module_out_path = module_output_path @@ -51,10 +51,12 @@ ohos_unittest("ability_connect_callback_proxy_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn old mode 100644 new mode 100755 index fd1cd1f9e76814dde76cc135e2eaa5965aadab6b..ca6e8b98f5fa7e65ef1b29cd5a92aba3c7ca3347 --- a/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_connect_callback_stub_test") { module_out_path = module_output_path @@ -52,10 +52,13 @@ ohos_unittest("ability_connect_callback_stub_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn old mode 100644 new mode 100755 index ba350b68f5a7645e7b08c1cc8a085b9013bf541d..91f93684ba2dee7bcfa431b7ba06296b8e2408a5 --- a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_connect_manage_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("ability_connect_manage_test") { "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn old mode 100644 new mode 100755 index 498cebb9e6f0861ae4e4eb12eaae95bbc0c03a61..ad2f1c7fb4fdae859303cf0efd5e95c122974e70 --- a/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_dump_test") { module_out_path = module_output_path @@ -54,10 +54,12 @@ ohos_unittest("ability_dump_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp b/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp index e711dfd8d7b1f72a48f77e09189d336d5f51541b..7acebdee358998dac4bf73e64c6d7982a61a87a8 100644 --- a/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp @@ -118,13 +118,14 @@ void AbilityDumpTest::OnStartAms() if (g_abilityMs->state_ == ServiceRunningState::STATE_RUNNING) { return; } - + g_abilityMs->state_ = ServiceRunningState::STATE_RUNNING; - + g_abilityMs->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(g_abilityMs->eventLoop_); g_abilityMs->handler_ = std::make_shared(g_abilityMs->eventLoop_, g_abilityMs); + g_abilityMs->connectManager_ = std::make_shared(); EXPECT_TRUE(g_abilityMs->handler_); EXPECT_TRUE(g_abilityMs->connectManager_); @@ -139,9 +140,9 @@ void AbilityDumpTest::OnStartAms() g_abilityMs->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(g_abilityMs->pendingWantManager_); - + int userId = g_abilityMs->GetUserId(); - g_abilityMs->SetStackManager(userId); + g_abilityMs->SetStackManager(userId, true); g_abilityMs->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(g_abilityMs->systemAppManager_); @@ -189,7 +190,7 @@ void AbilityDumpTest::StartAbilityes() if (currentTopAbilityRecord) { currentTopAbilityRecord->SetAbilityState(AbilityState::ACTIVE); } - + startAbility6(); startAbility1(); startAbility2(); diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn old mode 100644 new mode 100755 index c9544c35af733640f3e26751a660681b94403f79..1e1f40c6691ba2d18f67d31000e28625a347553b --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_manager_proxy_test") { module_out_path = module_output_path @@ -53,10 +53,12 @@ ohos_unittest("ability_manager_proxy_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h old mode 100755 new mode 100644 index 5f1bfccf16942f8b1d25295d1a2aba20f04b456a..d2f2f50f272e0c61202559cf6bf64af3d7e1f0c8 --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h @@ -73,13 +73,26 @@ public: int code_ = 0; - virtual int StartAbility(const Want &want, int requestCode = -1) + virtual int StartAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) { return 0; } - int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) + virtual int StartAbility(const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + + virtual int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) { return 0; } @@ -95,7 +108,10 @@ public: } virtual int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) { return 0; } @@ -147,12 +163,16 @@ public: virtual void DumpState(const std::string &args, std::vector &state) {} + virtual void DumpSysState( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int UserID) + {} + virtual int TerminateAbilityResult(const sptr &token, int startId) { return 0; } - virtual int StopServiceAbility(const Want &want) + virtual int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) { return 0; } @@ -326,8 +346,39 @@ public: { return 0; } + virtual int ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) override + { + return 0; + } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + + virtual bool SendANRProcessID(int pid) override + { + return true; + } + MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); - MOCK_METHOD3(StartAbility, int(const Want &want, const sptr &callerToken, int requestCode)); + MOCK_METHOD4(StartAbility, int(const Want &want, const sptr &callerToken, + int32_t userId, int requestCode)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); @@ -358,7 +409,38 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr &, const sptr &)); + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn old mode 100644 new mode 100755 index 4c94d19bef9daadb266d85ff173ae888a1c7c4fa..4b9d017fdf97b555276036cd131918471e420295 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_manager_service_test") { module_out_path = module_output_path @@ -23,7 +23,7 @@ ohos_unittest("ability_manager_service_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", ] @@ -46,16 +46,19 @@ ohos_unittest("ability_manager_service_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "dsoftbus_standard:softbus_client", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp old mode 100755 new mode 100644 index d85093bf6fc0d6fe4176a9a3f0517da5b8ed07fa..cbf4ca0753cd84a8c30b579a5f5b93ab36c5acb8 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp @@ -127,6 +127,7 @@ void AbilityManagerServiceTest::OnStartAms() EXPECT_TRUE(abilityMs_->eventLoop_); abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); + abilityMs_->connectManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); @@ -142,12 +143,8 @@ void AbilityManagerServiceTest::OnStartAms() abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); - abilityMs_->configuration_ = std::make_shared(); - EXPECT_TRUE(abilityMs_->configuration_); - abilityMs_->GetGlobalConfiguration(); - int userId = abilityMs_->GetUserId(); - abilityMs_->SetStackManager(userId); + abilityMs_->SetStackManager(userId, true); abilityMs_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs_->systemAppManager_); @@ -615,7 +612,7 @@ HWTEST_F(AbilityManagerServiceTest, Interface_012, TestSize.Level1) */ HWTEST_F(AbilityManagerServiceTest, Interface_013, TestSize.Level1) { - abilityMs_->SetStackManager(0); + abilityMs_->SetStackManager(0, true); EXPECT_NE(nullptr, abilityMs_->GetStackManager()); } @@ -3071,60 +3068,6 @@ HWTEST_F(AbilityManagerServiceTest, AmsConfigurationParameter_003, TestSize.Leve EXPECT_EQ(ref, 1); } -/* - * Feature: AbilityManagerService - * Function: UpdateConfiguration - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: NA - * MoveMissionToEnd NA - */ -HWTEST_F(AbilityManagerServiceTest, UpdateConfiguration_001, TestSize.Level1) -{ - auto confiuration = abilityMs_->GetConfiguration(); - EXPECT_TRUE(confiuration); - - AppExecFwk::Configuration config; - int displayId = 1001; - std::string val {"中文"}; - config.AddItem(displayId, GlobalConfigurationKey::SYSTEM_LANGUAGE, val); - auto ref = abilityMs_->UpdateConfiguration(config); - EXPECT_EQ(ref, 0); - - AppExecFwk::Configuration config2; - int displayId2 = 1001; - std::string val2 {"德语"}; - config2.AddItem(displayId2, GlobalConfigurationKey::SYSTEM_LANGUAGE, val2); - ref = abilityMs_->UpdateConfiguration(config2); - EXPECT_EQ(ref, 0); -} - -/* - * Feature: AbilityManagerService - * Function: UpdateConfiguration - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: NA - * MoveMissionToEnd NA - */ -HWTEST_F(AbilityManagerServiceTest, UpdateConfiguration_002, TestSize.Level1) -{ - auto confiuration = abilityMs_->GetConfiguration(); - EXPECT_TRUE(confiuration); - - AppExecFwk::Configuration config; - std::string val {"中文"}; - config.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, val); - auto ref = abilityMs_->UpdateConfiguration(config); - EXPECT_EQ(ref, 0); - - // Because the original will be updated, no new ones will be added. - ref = abilityMs_->UpdateConfiguration(config); - EXPECT_EQ(ref, ERR_INVALID_VALUE); -} - /* * Function: AmsGetSystemMemoryAttr * SubFunction: NA diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn old mode 100644 new mode 100755 index 60c946931fbbdc25292ae7289e1256195c3f4914..f73cc0fb17c55031a63ebfc517c78e77a50f01ba --- a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_manager_stub_test") { module_out_path = module_output_path @@ -53,10 +53,12 @@ ohos_unittest("ability_manager_stub_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h index 5e8cc3294470a8f72d73b66e4e9b6ec13fcfa11a..0ba52448e63f8917c36e2ce0c5e6501ad6492b88 100755 --- a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h @@ -31,7 +31,8 @@ public: {} MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); - MOCK_METHOD3(StartAbility, int(const Want &want, const sptr &callerToken, int requestCode)); + MOCK_METHOD4(StartAbility, int(const Want &want, const sptr &callerToken, + int32_t userId, int requestCode)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); @@ -46,13 +47,17 @@ public: MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); - + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); MOCK_METHOD3(NotifyCompleteContinuation, void(const std::string &deviceId, int32_t sessionId, bool isSuccess)); + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr &, const sptr &)); int InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -68,13 +73,26 @@ public: int code_ = 0; - virtual int StartAbility(const Want &want, int requestCode = -1) + virtual int StartAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) { return 0; } - int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) + int StartAbility(const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + + int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) { return 0; } @@ -90,7 +108,10 @@ public: } virtual int ConnectAbility( - const Want &want, const sptr &connect, const sptr &callerToken) + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) { return 0; } @@ -142,12 +163,16 @@ public: virtual void DumpState(const std::string &args, std::vector &state) {} + virtual void DumpSysState( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int UserID) + {} + virtual int TerminateAbilityResult(const sptr &token, int startId) { return 0; } - virtual int StopServiceAbility(const Want &want) + virtual int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) { return 0; } @@ -368,6 +393,61 @@ public: { return 0; } + + virtual int ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) override + { + return 0; + } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + virtual bool SendANRProcessID(int pid) override + { + return true; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h old mode 100755 new mode 100644 index d7240704c88d2aaef438c65d4215ace8617b7779..569f5dee3a433bd1d8ef550122d8e9fc0369e049 --- a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h @@ -98,6 +98,12 @@ public: MOCK_METHOD1(TerminateAbilityTest, void(int id)); MOCK_METHOD1(MoveMissionToEnd, int(int id)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); + + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + virtual int StartUser(int userId) override { return 0; @@ -130,6 +136,25 @@ public: { return 0; } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn old mode 100644 new mode 100755 index 247113d0853a0e8482c9c252bd41feeeda6391c6..e0cb1722d0ad8240224fc38e9d0a465fda78e97d --- a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_record_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("ability_record_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn old mode 100644 new mode 100755 index 5de3fc977c2293da59dfa7b8b23f1be1a8ffcd65..5eceb53bb068c0d5a70b3c961487be2e6b8de96f --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_scheduler_proxy_test") { module_out_path = module_output_path @@ -53,10 +53,12 @@ ohos_unittest("ability_scheduler_proxy_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn old mode 100644 new mode 100755 index c2f31b6f33de0442fb5140716da1ecc111aec26f..758834f27cbab224cafb260e2d1e7e134201ad67 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_scheduler_stub_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("ability_scheduler_stub_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h index 1237f1c8ec86b36a8c46dc9c5405dacd818f9d00..a1a4ef18a9813e5b80d0881985e723586171e0d7 100755 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h @@ -133,6 +133,12 @@ public: {} virtual void ContinueAbility(const std::string& deviceId) override {} + virtual void DumpAbilityInfo(std::vector &info) override + {} + virtual sptr CallRequest() override + { + return sptr(nullptr); + } }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn old mode 100644 new mode 100755 index 2bf3808316fe0f34273cd78d1b4c8dce28384f21..a54263041ee26362a06d70f4dabe83ae5c9a469b --- a/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_service_start_test") { module_out_path = module_output_path @@ -52,10 +52,12 @@ ohos_unittest("ability_service_start_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn old mode 100644 new mode 100755 index e070ffda7ab99d8a4e80cf2fb0751668fd155515..c8cc259ba14c79ee6e8f0271fa3dbdc9e8fff7c0 --- a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_stack_manager_test") { module_out_path = module_output_path @@ -23,7 +23,7 @@ ohos_unittest("ability_stack_manager_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", ] sources = [ @@ -47,6 +47,7 @@ ohos_unittest("ability_stack_manager_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", @@ -54,10 +55,12 @@ ohos_unittest("ability_stack_manager_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp index 7c8547bc4e84f88ade17e8d142cf640581a1c308..e22a8cce45b35fa0cd90c1f87ad2364cdd988aef 100644 --- a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp @@ -79,11 +79,12 @@ void AbilityStackManagerTest::OnStartabilityMs() } abilityMs_->state_ = ServiceRunningState::STATE_RUNNING; - + abilityMs_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(abilityMs_->eventLoop_); abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); + abilityMs_->connectManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); @@ -98,9 +99,9 @@ void AbilityStackManagerTest::OnStartabilityMs() abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); - + int userId = abilityMs_->GetUserId(); - abilityMs_->SetStackManager(userId); + abilityMs_->SetStackManager(userId, true); abilityMs_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs_->systemAppManager_); @@ -1502,7 +1503,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_042, TestSize. stackManager_->UninstallApp("com.ix.hiMusic"); // process died stackManager_->OnAbilityDied(thirdTopAbility); - + auto topAbility = stackManager_->GetCurrentTopAbility(); EXPECT_TRUE(topAbility); EXPECT_EQ("MusicAbility", topAbility->GetAbilityInfo().name); @@ -2487,7 +2488,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_067, TestSize. MissionOption missionOption; missionOption.missionId = musicMissionRecord->GetMissionRecordId(); missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; - + auto ref = stackManager_->MoveMissionToFloatingStack(missionOption); EXPECT_EQ(ref, ERR_NONE); @@ -3240,7 +3241,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_087, TestSize. auto ref = stackManager_->GenerateMissinOptionsOfSplitScreen(primary, secondary, options); EXPECT_EQ(ERR_INVALID_DATA, ref); } - + /* * Feature: AbilityStackManager * Function: GenerateMissinOptionsOfSplitScreen @@ -3353,12 +3354,12 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_091, TestSize. EXPECT_EQ(0, result); auto firstTopAbility = stackManager_->GetCurrentTopAbility(); firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); - + result = stackManager_->StartAbility(musicAbilityRequest_); EXPECT_EQ(0, result); auto musicAbility = stackManager_->GetCurrentTopAbility(); musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); - + // start split screen auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); // Set floating window identification @@ -3904,7 +3905,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_0108, TestSize TerminatingAbility musicTerminateAbility; musicTerminateAbility.abilityRecord = musicAbilityRecord; - + TerminatingAbility musicSaTerminateAbility; musicSaTerminateAbility.abilityRecord = musicSaAbilityRecord; @@ -4077,7 +4078,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_0112, TestSize TerminatingAbility musicTerminateAbility; musicTerminateAbility.abilityRecord = musicAbilityRecord; - + TerminatingAbility radioSaTerminateAbility; radioSaTerminateAbility.abilityRecord = radioAbilityRecord; @@ -4281,7 +4282,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_0117, TestSize EXPECT_TRUE(abilityStartSetting); radioAbilityRequest_.startSetting = abilityStartSetting; - + result = stackManager_->StartAbility(radioTonAbilityRequest_); EXPECT_EQ(0, result); auto radioAbility = stackManager_->GetCurrentTopAbility(); @@ -4542,7 +4543,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_0125, TestSize option.missionId = 2; option.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; targetMissionRecord->SetMissionOption(option); - + stackManager_->MoveMissionAndAbility(currentAbility, targetAbility, targetMissionRecord); auto ability = targetMissionRecord->GetTopAbilityRecord(); @@ -4695,7 +4696,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_0129, TestSize EXPECT_TRUE(ability); ability->SetMovingBackgroundFlag(true); - + stackManager_->CompleteActive(ability); EXPECT_EQ(ability->GetAbilityState(), AbilityState::ACTIVE); } @@ -4723,7 +4724,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_0130, TestSize EXPECT_TRUE(ability); ability->SetMovingBackgroundFlag(true); - + stackManager_->CompleteInactive(ability); EXPECT_EQ(ability->GetAbilityState(), AbilityState::MOVING_BACKGROUND); @@ -4755,9 +4756,9 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_0131, TestSize ability->SetAbilityState(AbilityState::MOVING_BACKGROUND); ability->SetMovingBackgroundFlag(true); - + stackManager_->CompleteBackground(ability); - + EXPECT_EQ(ability->GetAbilityState(), AbilityState::BACKGROUND); } diff --git a/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn old mode 100644 new mode 100755 index 320add42c3312439bbc91b31c4e13b380d177d90..061ce0d99e71aa45b5c006b40593a27b5f435658 --- a/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_token_proxy_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("ability_token_proxy_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn old mode 100644 new mode 100755 index 4d1e01ba33e329f00ca675ce1b7de7714bae6e19..d53822f375ea259f7a92c6735eae526973eac5cd --- a/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_token_stub_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("ability_token_stub_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn old mode 100644 new mode 100755 index 408f698d25981ae0ec66ee2ef0895a093917de4b..73bb5e52da816c12a7949a30902c32d5aa0c4368 --- a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_with_applications_test") { module_out_path = module_output_path @@ -22,7 +22,7 @@ ohos_unittest("ability_with_applications_test") { include_dirs = [ "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", ] sources = [ @@ -47,16 +47,19 @@ ohos_unittest("ability_with_applications_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp index d59933c3acc018ad8277ba1ecd7fcdda5663faed..9a2aeefe2427af3bb5552b58823c78e13c411815 100644 --- a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp @@ -89,11 +89,12 @@ void AbilityWithApplicationsTest::OnStartabilityAms() } abilityMs_->state_ = ServiceRunningState::STATE_RUNNING; - + abilityMs_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(abilityMs_->eventLoop_); abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); + abilityMs_->connectManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); @@ -108,9 +109,9 @@ void AbilityWithApplicationsTest::OnStartabilityAms() abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); - + int userId = abilityMs_->GetUserId(); - abilityMs_->SetStackManager(userId); + abilityMs_->SetStackManager(userId, true); abilityMs_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs_->systemAppManager_); diff --git a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn old mode 100644 new mode 100755 index 7bcd6966c88723297f90c90e235fc208904bd207..b4a5ce8c0868b3df0cc8e9a38e746f724d666218 --- a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("abilityms_appms_test") { module_out_path = module_output_path @@ -23,7 +23,7 @@ ohos_unittest("abilityms_appms_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/test/mock/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", ] sources = [ @@ -47,16 +47,19 @@ ohos_unittest("abilityms_appms_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp index b3214d77cbf4519e52d8ebd33a91ffe117dd09b0..98adb3ee6cd145301c7010e5d71a46afb592f50c 100644 --- a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp +++ b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp @@ -98,11 +98,12 @@ void AbilityMsAppmsTest::OnStartabilityAms() } abilityMs_->state_ = ServiceRunningState::STATE_RUNNING; - + abilityMs_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(abilityMs_->eventLoop_); abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); + abilityMs_->connectManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); @@ -117,9 +118,9 @@ void AbilityMsAppmsTest::OnStartabilityAms() abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); - + int userId = abilityMs_->GetUserId(); - abilityMs_->SetStackManager(userId); + abilityMs_->SetStackManager(userId, true); abilityMs_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs_->systemAppManager_); diff --git a/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn old mode 100644 new mode 100755 index f843d15dbe84ac40b9bf1a4dc8515f9df01df21f..da1442f77bd8bbfd0e8f4eb12a806a72a9d51404 --- a/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn @@ -15,7 +15,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") import("//foundation/aafwk/standard/services/abilitymgr/abilitymgr.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("app_scheduler_test") { module_out_path = module_output_path @@ -52,11 +52,13 @@ ohos_unittest("app_scheduler_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ "bytrace_standard:bytrace_core", + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp index 01ce62816282bbc9869c892f8315e66fb4ae8def..1dcc730a1d08da2f582af98aa30a05e3e95716f3 100644 --- a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp +++ b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp @@ -253,7 +253,7 @@ HWTEST_F(AppSchedulerTest, AppScheduler_oprator_008, TestSize.Level1) HWTEST_F(AppSchedulerTest, AppScheduler_oprator_009, TestSize.Level1) { DelayedSingleton::GetInstance()->appMgrClient_ = std::make_unique(); - + std::string deviceName = "device"; std::string abilityName = "FirstAbility"; std::string appName = "FirstApp"; diff --git a/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn old mode 100644 new mode 100755 index 29157e5b794881fbc078e754826a04ef2b4cee1e..021e20e46aff767077954385a431f21fcf39c31f --- a/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("configuration_test") { module_out_path = module_output_path @@ -54,10 +54,12 @@ ohos_unittest("configuration_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/configuration_test/configuration_test.cpp b/services/abilitymgr/test/unittest/phone/configuration_test/configuration_test.cpp index e7bfc803fa03cd09d492de1ada02b3f2c6632f03..4ebd631129f3ed0a29060a2dcebbcbdb5aa817c6 100644 --- a/services/abilitymgr/test/unittest/phone/configuration_test/configuration_test.cpp +++ b/services/abilitymgr/test/unittest/phone/configuration_test/configuration_test.cpp @@ -350,9 +350,7 @@ HWTEST_F(ConfigurationTest, Merge_001, TestSize.Level1) int size = changeKeyV.size(); EXPECT_EQ(size, 1); - for (const auto &s : changeKeyV) { - config.Merge(s, config2); - } + config.Merge(changeKeyV, config2); auto item = config.GetItem(displayId2, GlobalConfigurationKey::SYSTEM_LANGUAGE); EXPECT_EQ(item, English); @@ -384,9 +382,7 @@ HWTEST_F(ConfigurationTest, Merge_002, TestSize.Level1) int size = changeKeyV.size(); EXPECT_EQ(size, 1); - for (const auto &s : changeKeyV) { - config.Merge(s, config2); - } + config.Merge(changeKeyV, config2); auto item = config.GetItem(displayId, GlobalConfigurationKey::SYSTEM_LANGUAGE); EXPECT_EQ(item, english); diff --git a/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn old mode 100644 new mode 100755 index 66529649fc93fa49587d5aa23566b9bdb7700bae..66275bc45a17ad141e37aa025ddd08977ef8f6c0 --- a/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("connection_record_test") { module_out_path = module_output_path @@ -51,10 +51,12 @@ ohos_unittest("connection_record_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp b/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp old mode 100644 new mode 100755 index f9dbb791c34d61d099b28b2ca37d97d8bf87acff..8b0f157a10c268c2b645a4580379602cff7e35f9 --- a/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp +++ b/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp @@ -213,7 +213,7 @@ HWTEST_F(ConnectionRecordTest, AaFwk_ConnectionRecord_007, TestSize.Level1) { EXPECT_CALL(*callback_, OnAbilityDisconnectDone(::testing::_, ::testing::_)).Times(1); - connectionRecord_->CompleteDisconnect(ERR_OK); + connectionRecord_->CompleteDisconnect(ERR_OK, false); EXPECT_EQ(connectionRecord_->GetConnectState(), ConnectionState::DISCONNECTED); } diff --git a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn old mode 100644 new mode 100755 index 10ae2540c82ab1e64a91b5fe345a112158aac010..b8da729debb40bbb530d652a63cc5972263ffe50 --- a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("data_ability_manager_test") { module_out_path = module_output_path @@ -60,11 +60,13 @@ ohos_unittest("data_ability_manager_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ "bytrace_standard:bytrace_core", + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn old mode 100644 new mode 100755 index 70c3105f017f00f54bbc62310b997541b2b2dda5..77926dfa97633f49618992d4161c7da0facaa328 --- a/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("data_ability_record_test") { module_out_path = module_output_path @@ -58,10 +58,12 @@ ohos_unittest("data_ability_record_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn old mode 100644 new mode 100755 index 41dbdd2586e7466d75baf28b1ea9a61a7f00dec2..2a7115df103db6659c53351d6b0c1cf2bedece5d --- a/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("info_test") { module_out_path = module_output_path @@ -52,10 +52,12 @@ ohos_unittest("info_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn old mode 100644 new mode 100755 index 4e172d30e5fc55c08fefe3e56987747d50a778d0..0346377ea1df2b3b465a001279d459bfe076112f --- a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("kernal_system_app_mgr_test") { module_out_path = module_output_path @@ -54,9 +54,11 @@ ohos_unittest("kernal_system_app_mgr_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn old mode 100644 new mode 100755 index 8edba73096b0a9de29723792f1c408dae29a80b6..d0996dfc3301af0d641ee7cdeebbdee9a063c6b3 --- a/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("lifecycle_deal_test") { module_out_path = module_output_path @@ -52,11 +52,14 @@ ohos_unittest("lifecycle_deal_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ - "appexecfwk_standard:appexecfwk_core", + "ability_runtime:app_manager", + "bundle_framework:appexecfwk_core", + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn old mode 100644 new mode 100755 index 2c7297675cbe1b6aa6e43183425911325935e6f7..ac8cf6512bc67ecc6a6e3824ecc9b54504b685f2 --- a/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("lifecycle_test") { module_out_path = module_output_path @@ -52,10 +52,12 @@ ohos_unittest("lifecycle_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp b/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp index d516a84db4d08c20e162294469f8bb609a455e26..1d88e6e649867432d8f28ddd1bfbbc251321a231 100644 --- a/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp +++ b/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp @@ -98,11 +98,12 @@ void LifecycleTest::OnStartabilityAms() } abilityMs_->state_ = ServiceRunningState::STATE_RUNNING; - + abilityMs_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(abilityMs_->eventLoop_); abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); + abilityMs_->connectManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); @@ -117,9 +118,9 @@ void LifecycleTest::OnStartabilityAms() abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); - + int userId = abilityMs_->GetUserId(); - abilityMs_->SetStackManager(userId); + abilityMs_->SetStackManager(userId, true); abilityMs_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs_->systemAppManager_); diff --git a/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn old mode 100644 new mode 100755 index 80a2dc77c963742205df81b5207242022e76a898..dc01b5da9b34824ee6ec8eb35739791a6b29dadb --- a/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("lock_screen_white_list_test") { module_out_path = module_output_path @@ -23,7 +23,7 @@ ohos_unittest("lock_screen_white_list_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", ] sources = [ @@ -48,16 +48,20 @@ ohos_unittest("lock_screen_white_list_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn old mode 100644 new mode 100755 index 454dab4eda115436ca31ec73d052b9cd6623e169..b78161b10091c2f178bb1f699c46a7c6fedac66d --- a/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("mission_list_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("mission_list_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn old mode 100644 new mode 100755 index 6c37b041dd437123b817bf91b1d30dc3fc4ba8fe..7efb097b7810fb33ef77cb91b051719273663823 --- a/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("mission_record_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("mission_record_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn old mode 100644 new mode 100755 index 13a234b25d506a4681849cf70125d2a4ba62e709..cfd41f71d6496a3b0ecf8b7e0bd3cfb69ffa3bfc --- a/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("mission_stack_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("mission_stack_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp b/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp index b9885ce96be3f50b546d62ee2767fe9508ae23e6..7723987fb75dca0a2116aa0679fc79206fe5a37e 100644 --- a/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp +++ b/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp @@ -468,7 +468,7 @@ HWTEST_F(MissionStackTest, MS_oprator_019, TestSize.Level1) auto missionRecordOne = std::make_shared("test_one"); auto missionRecordTwo = std::make_shared("test_two"); - + MissionOption option; option.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; missionRecordOne->SetMissionOption(option); @@ -500,7 +500,7 @@ HWTEST_F(MissionStackTest, MS_oprator_020, TestSize.Level1) auto missionRecordOne = std::make_shared("test_one"); auto missionRecordTwo = std::make_shared("test_two"); - + EXPECT_EQ(0, (int)missionStack_->missions_.size()); missionStack_->AddMissionRecordToEnd(missionRecordOne); @@ -527,7 +527,7 @@ HWTEST_F(MissionStackTest, MS_oprator_021, TestSize.Level1) auto missionRecordOne = std::make_shared("test_one"); auto missionRecordTwo = std::make_shared("test_two"); - + MissionOption option; option.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; missionRecordOne->SetMissionOption(option); diff --git a/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn old mode 100644 new mode 100755 index 489cfdde2bd558f05b868dc095b882b43c7c4399..8328c8302c0aad486a9370e4750936f35c88ca5d --- a/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("mission_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("mission_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn old mode 100644 new mode 100755 index 3191ad1751c6e9207128f55990f09282e86c91be..c85962e2f376e90d5c5635bf591a5cda7121d4d0 --- a/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("pending_want_key_test") { module_out_path = module_output_path @@ -45,10 +45,12 @@ ohos_unittest("pending_want_key_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn old mode 100644 new mode 100755 index e29d3b5d95f38b98d3134029a4982c51cacb8756..bdcf01bfa947918bcc552a93bf8e14e87f23575f --- a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("pending_want_manager_test") { module_out_path = module_output_path @@ -49,10 +49,12 @@ ohos_unittest("pending_want_manager_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn old mode 100644 new mode 100755 index 114ee6fe3d62a5fe84522d8c39164f6da7ec178a..9d1098d667b7e809ef7cc4e6c2dc37c93c5a8af5 --- a/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("pending_want_record_test") { module_out_path = module_output_path @@ -49,10 +49,12 @@ ohos_unittest("pending_want_record_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn old mode 100644 new mode 100755 index c4c685ffc5cf5e9fc9c4db6fd84d150639100a44..c6e2f72cca915c002edd8028f314a42687f63350 --- a/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("resume_mission_container_test") { module_out_path = module_output_path @@ -48,10 +48,12 @@ ohos_unittest("resume_mission_container_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn old mode 100644 new mode 100755 index c4c5034a2b0e45855ad54ae3880108780763270d..7f9b0ab38a9fa60fba138b17abf7ebcef510d3ef --- a/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_screenshot_handler_test") { module_out_path = module_output_path @@ -23,7 +23,7 @@ ohos_unittest("ability_screenshot_handler_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", ] sources = [ @@ -48,16 +48,20 @@ ohos_unittest("ability_screenshot_handler_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn old mode 100644 new mode 100755 index 0bfa842aa6701cab6c022295209ac60f31c61bc6..8250b307c92901da02520a39ccc21b44ff15950a --- a/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("sender_info_test") { module_out_path = module_output_path @@ -49,10 +49,12 @@ ohos_unittest("sender_info_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn old mode 100644 new mode 100755 index 18b4afcebafb3629a8decd33bc058626cb2882bb..76af6acb6262be54f7113348de36ac48fcc7fddd --- a/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("terminate_ability_test") { module_out_path = module_output_path @@ -54,10 +54,12 @@ ohos_unittest("terminate_ability_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp b/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp index c03c2818c39cd8b97ab540d21b83d973ee972921..da3c9d8ca3baf5f48fe9bb4d66e8d1a377c2e215 100644 --- a/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp +++ b/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp @@ -130,13 +130,14 @@ void TerminateAbilityTest::OnStartAms() if (g_aams->state_ == ServiceRunningState::STATE_RUNNING) { return; } - + g_aams->state_ = ServiceRunningState::STATE_RUNNING; - + g_aams->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(g_aams->eventLoop_); g_aams->handler_ = std::make_shared(g_aams->eventLoop_, g_aams); + g_aams->connectManager_ = std::make_shared(); EXPECT_TRUE(g_aams->handler_); EXPECT_TRUE(g_aams->connectManager_); @@ -151,9 +152,9 @@ void TerminateAbilityTest::OnStartAms() g_aams->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(g_aams->pendingWantManager_); - + int userId = g_aams->GetUserId(); - g_aams->SetStackManager(userId); + g_aams->SetStackManager(userId, true); g_aams->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(g_aams->systemAppManager_); @@ -224,7 +225,7 @@ bool TerminateAbilityTest::StartAbility( GTEST_LOG_(ERROR) << "new token is nullptr"; return false; } - + abilityScheduler = new AbilityScheduler(); if (g_aams->AttachAbilityThread(abilityScheduler, token) != 0) { GTEST_LOG_(ERROR) << "fail to AttachAbilityThread"; @@ -772,7 +773,7 @@ HWTEST_F(TerminateAbilityTest, AAFWK_g_aamsTerminateAbility_014, TestSize.Level1 std::shared_ptr testAbilityRecordB = stackManager->GetCurrentTopAbility(); EXPECT_EQ(g_aams->AttachAbilityThread(new AbilityScheduler(), tokenB), 0); - + testAbilityRecordA->SetAbilityState(OHOS::AAFwk::AbilityState::INACTIVE); testAbilityRecordB->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); diff --git a/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn old mode 100644 new mode 100755 index 86e08792cf6f3d0800c348781290a4c3e3dd4a3d..0f6d0fa0ec4ab54cb9ea78b0227bb2da68a60c12 --- a/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_receiver_proxy_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("want_receiver_proxy_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn old mode 100644 new mode 100755 index 5cbc3bd8ff3973488c1b350b01806fe07164f605..f4d265e82f543ac939b036e53d52d8079204d154 --- a/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_receiver_stub_test") { module_out_path = module_output_path @@ -51,10 +51,12 @@ ohos_unittest("want_receiver_stub_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn old mode 100644 new mode 100755 index 19c4dfb8ae604f2a02468bf86b961ad9eeb828ae..fb571a29d88c5dc7c0326141731327e71f323453 --- a/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_sender_info_test") { module_out_path = module_output_path @@ -49,10 +49,12 @@ ohos_unittest("want_sender_info_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn old mode 100644 new mode 100755 index ea4c4fb58c388ef81791454f2d0d84e7a2a25333..f1edbed31c88a496cf4b41191ca75de0149e1df2 --- a/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_sender_proxy_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("want_sender_proxy_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn old mode 100644 new mode 100755 index ad4e608abb33f1628bb2949b3b42b16561a28abf..ae59d37bc736828f0ea132b97d3e7c17469e2a48 --- a/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_sender_stub_test") { module_out_path = module_output_path @@ -51,10 +51,12 @@ ohos_unittest("want_sender_stub_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn old mode 100644 new mode 100755 index 8ce4376366cb4ba38847705192d5b63cd50de6ee..4f5d38f4623849ea9b1e30608d73d25976427bef --- a/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("wants_info_test") { module_out_path = module_output_path @@ -50,10 +50,12 @@ ohos_unittest("wants_info_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn old mode 100644 new mode 100755 index ce5cbf6dbfd12a1200d1c8b4e7ea173c7e9cf5c6..31e81a792421a90d40508071223306f7fe0c37f9 --- a/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/abilitymgr" +module_output_path = "ability_runtime/abilitymgr" ohos_unittest("window_info_test") { module_out_path = module_output_path @@ -42,9 +42,14 @@ ohos_unittest("window_info_test") { "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "device_manager_base:devicemanagersdk", + "hiviewdfx_hilog_native:libhilog", + ] } group("unittest") { diff --git a/services/appmgr/BUILD.gn b/services/appmgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..84cb63309ee5b40f0fbfd83a77ea6c3cf6a99dab --- /dev/null +++ b/services/appmgr/BUILD.gn @@ -0,0 +1,138 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("appmgr_config") { + include_dirs = [ + "include", + "//base/startup/appspawn_standard/interfaces/innerkits/include", + "//utils/system/safwk/native/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "//base/notification/ces_standard/frameworks/core/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//base/global/i18n_standard/frameworks/intl/include", + ] +} + +group("ams_target") { + deps = [ + ":libams", + ":lmks", + ":lmks.rc", + "examples:appmgrserviceregtest", + "examples:appspawnclienttest", + ] +} + +ohos_executable("lmks") { + include_dirs = [ + "include/lmks", + "//utils/native/base/include", + ] + + sources = [ + "src/lmks/lmks_main.cpp", + "src/lmks/lmks_server.cpp", + "src/lmks/lmks_utils.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ "//utils/native/base:utils" ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + install_enable = true + subsystem_name = "aafwk" + part_name = "ability_runtime" +} + +ohos_prebuilt_etc("lmks.rc") { + source = "lmks.cfg" + relative_install_dir = "init" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} + +ohos_shared_library("libams") { + sources = [ + "src/ability_running_record.cpp", + "src/ams_mgr_scheduler.cpp", + "src/app_death_recipient.cpp", + "src/app_lifecycle_deal.cpp", + "src/app_mgr_service.cpp", + "src/app_mgr_service_event_handler.cpp", + "src/app_mgr_service_inner.cpp", + "src/app_process_manager.cpp", + "src/app_running_manager.cpp", + "src/app_running_record.cpp", + "src/app_spawn_client.cpp", + "src/app_spawn_msg_wrapper.cpp", + "src/app_spawn_socket.cpp", + "src/cgroup_manager.cpp", + "src/lmks_client.cpp", + "src/module_running_record.cpp", + "src/process_optimizer.cpp", + "src/process_optimizer_uba.cpp", + "src/remote_client_manager.cpp", + "src/system_environment_information.cpp", + ] + + defines = [ + "APP_LOG_TAG = \"AppMgrService\"", + "LOG_DOMAIN = 0xD001110", + ] + + configs = [ + ":appmgr_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + "${aafwk_path}/interfaces/innerkits/app_manager:appmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//base/global/i18n_standard/frameworks/intl:intl_util", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/services/appmgr/examples/BUILD.gn b/services/appmgr/examples/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8c977918bf77c917015542a261a7a560d76f0fd8 --- /dev/null +++ b/services/appmgr/examples/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_executable("appspawnclienttest") { + sources = [ "app_spawn_client_test/main.cpp" ] + + configs = [ + ":test_config", + "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_config", + ] + + deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/appmgr:libams", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + ] + external_deps = [ "appspawn:appspawn_socket_client" ] +} + +ohos_executable("appmgrserviceregtest") { + sources = [ "app_mgr_service_register_test/main_client.cpp" ] + + configs = [ + ":test_config", + "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_config", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:appmgr_sdk_config", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base_sdk_config", + "//utils/native/base:utils_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/appmgr:libams", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + + #"startup:appspawn_jni", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +config("test_config") { + # header file path + include_dirs = [ + "//foundation/appexecfwk/standard/interfaces", + "//foundation/aafwk/standard/services/appmgr/include", + "//foundation/appexecfwk/standard/services/common/include", + ] + + # enable exception + + configs = [ "//foundation/aafwk/standard/services/appmgr:appmgr_config" ] +} diff --git a/services/appmgr/examples/app_mgr_service_register_test/main_client.cpp b/services/appmgr/examples/app_mgr_service_register_test/main_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3837b6dceedc9c93117c8818a552a1d4c83eb08e --- /dev/null +++ b/services/appmgr/examples/app_mgr_service_register_test/main_client.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_interface.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +int main() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + printf("fail to get systemAbilityMgr!"); + return -1; + } + sptr object = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); + if (!object) { + printf("fail to get service: AppMgrService!"); + return -1; + } + sptr appMgr = iface_cast(object); + appMgr->ApplicationForegrounded(0); + + IPCSkeleton::JoinWorkThread(); +} \ No newline at end of file diff --git a/services/appmgr/examples/app_spawn_client_test/main.cpp b/services/appmgr/examples/app_spawn_client_test/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b3dfb86a4ba5cf7feb964c0a9fb18d42f1600254 --- /dev/null +++ b/services/appmgr/examples/app_spawn_client_test/main.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_spawn_client.h" + +using OHOS::AppExecFwk::AppSpawnClient; +using OHOS::AppExecFwk::AppSpawnStartMsg; + +int main() +{ + std::shared_ptr service = std::make_shared(); + AppSpawnStartMsg startMsg = {0, 0, {0}, "test", "test"}; + pid_t pid = 0; + service->StartProcess(startMsg, pid); + printf("AppSpawnClientTest end with new PID : %d", pid); + return 0; +} diff --git a/services/appmgr/include/ability_running_record.h b/services/appmgr/include/ability_running_record.h new file mode 100644 index 0000000000000000000000000000000000000000..eee811ed0a08cfc6fa4fb92640dbf233afbba475 --- /dev/null +++ b/services/appmgr/include/ability_running_record.h @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_ABILITY_RUNNING_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_ABILITY_RUNNING_RECORD_H + +#include + +#include "iremote_object.h" + +#include "ability_info.h" +#include "application_info.h" +#include "app_mgr_constants.h" + +namespace OHOS { +namespace AppExecFwk { +class AbilityRunningRecord { +public: + AbilityRunningRecord(const std::shared_ptr &info, const sptr &token); + virtual ~AbilityRunningRecord(); + + /** + * @brief Obtains the name of the ability. + * + * @return Returns the ability name. + */ + const std::string &GetName() const; + + /** + * @brief Obtains the info of the ability. + * + * @return Returns the ability info. + */ + const std::shared_ptr &GetAbilityInfo() const; + + /** + * @brief Obtains the token of the ability. + * + * @return Returns the ability token. + */ + const sptr &GetToken() const; + + /** + * @brief Setting id for ability record. + * + * @param appId, the ability record id. + */ + void SetAppRunningRecordId(const int32_t appId); + + /** + * @brief Setting state for ability record. + * + * @param state, the ability record state. + */ + void SetState(const AbilityState state); + + /** + * @brief Obtains the state of the ability. + * + * @return Returns the ability state. + */ + AbilityState GetState() const; + + /** + * @brief Judge whether the ability status is the same. + * + * @param state, the ability state. + * + * @return Returns If true is returned, the ID will be the same, otherwise it fails. + */ + bool IsSameState(const AbilityState state) const; + + /** + * @brief Obtains the last launch time of the ability record. + * + * @return Returns the last launch time. + */ + int32_t GetLastLaunchTime() const; + + /** + * @brief Setting the unique identification to call the ability. + * + * @param preToken, the unique identification to call the ability. + */ + void SetPreToken(const sptr &preToken); + + /** + * @brief Obtains the unique identification to call the ability. + * + * @return Returns the unique identification to call the ability. + */ + const sptr GetPreToken() const; + + /** + * @brief Setting the visibility to ability. + * + * @param preToken, the visibility to ability. + */ + void SetVisibility(const int32_t visibility); + + /** + * @brief Obtains the visibility to ability. + * + * @return Returns the visibility to ability. + */ + int32_t GetVisibility() const; + + /** + * @brief Setting the perceptibility to ability. + * + * @param preToken, the perceptibility to ability. + */ + void SetPerceptibility(const int32_t perceptibility); + + /** + * @brief Obtains the perceptibility to ability. + * + * @return Returns the perceptibility to ability. + */ + int32_t GetPerceptibility() const; + + /** + * @brief Setting the connection state to service ability. + * + * @param preToken, the connection state to service ability. + */ + void SetConnectionState(const int32_t connectionState); + + /** + * @brief Obtains the connection state to service ability. + * + * @return Returnsthe connection state to service ability. + */ + int32_t GetConnectionState() const; + + /** + * @brief Set the Terminating object. + */ + void SetTerminating(); + + /** + * @brief Whether the ability is terminating. + * + * @return Returns whether the ability is terminating. + */ + bool IsTerminating() const; + + void SetEventId(const int64_t eventId); + int64_t GetEventId() const; + +private: + int32_t lastLaunchTime_ = 0; + int32_t visibility_ = 0; + int32_t perceptibility_ = 0; + int32_t connectionState_ = 0; + int64_t eventId_ = 0; + bool isTerminating_ = false; + AbilityState state_ = AbilityState::ABILITY_STATE_BEGIN; + std::shared_ptr info_; + sptr token_; + sptr preToken_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_ABILITY_RUNNING_RECORD_H diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..64d6b1d34cd00b341d9b96a7683886f1829b57c3 --- /dev/null +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_SCHEDULER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_SCHEDULER_H + +#include "if_system_ability_manager.h" +#include "nocopyable.h" + +#include "system_ability.h" +#include "ability_info.h" +#include "ability_running_record.h" +#include "appexecfwk_errors.h" +#include "application_info.h" +#include "app_mgr_constants.h" +#include "ams_mgr_stub.h" +#include "app_mgr_service_event_handler.h" +#include "app_mgr_service_inner.h" +#include "app_record_id.h" +#include "app_running_record.h" +#include "app_scheduler_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +class Configuration; +class AmsMgrScheduler : public AmsMgrStub { +public: + AmsMgrScheduler( + const std::shared_ptr &MgrServiceInner_, const std::shared_ptr &Handler_); + virtual ~AmsMgrScheduler() override; + + /** + * LoadAbility, call LoadAbility() through proxy project, load the ability that needed to be started. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param abilityInfo, the ability information. + * @param appInfo, the app information. + * @return + */ + virtual void LoadAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) override; + + /** + * TerminateAbility, call TerminateAbility() through the proxy object, terminate the token ability. + * + * @param token, token, he unique identification to terminate the ability. + * @return + */ + virtual void TerminateAbility(const sptr &token) override; + + /** + * UpdateAbilityState, call UpdateAbilityState() through the proxy object, update the ability status. + * + * @param token, the unique identification to update the ability. + * @param state, ability status that needs to be updated. + * @return + */ + virtual void UpdateAbilityState(const sptr &token, const AbilityState state) override; + + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + * @return + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state) override; + + /** + * RegisterAppStateCallback, call RegisterAppStateCallback() through the proxy object, register the callback. + * + * @param callback, Ams register the callback. + * @return + */ + virtual void RegisterAppStateCallback(const sptr &callback) override; + + /** + * Reset,call Reset() through the proxy object, reset DFX of AppMgr. + * + * @return + */ + virtual void Reset() override; + + /** + * AbilityBehaviorAnalysis, ability behavior analysis assistant process optimization. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param visibility, the visibility information about windows info. + * @param perceptibility, the Perceptibility information about windows info. + * @param connectionState, the service ability connection state. + * @return + */ + virtual void AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) override; + + /** + * KillProcessByAbilityToken, call KillProcessByAbilityToken() through proxy object, + * kill the process by ability token. + * + * @param token, the unique identification to the ability. + * @return + */ + virtual void KillProcessByAbilityToken(const sptr &token) override; + + /** + * KillProcessesByUserId, call KillProcessesByUserId() through proxy object, + * kill the processes by userId. + * + * @param userId, the user id. + * @return + */ + virtual void KillProcessesByUserId(int32_t userId) override; + + /** + * KillProcessWithAccount, call KillProcessWithAccount() through proxy object, kill the + * process. + * + * @param bundleName, bundle name in Application record. + * @param accountId, account ID. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillProcessWithAccount(const std::string &bundleName, const int accountId) override; + + /** + * KillApplication, call KillApplication() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillApplication(const std::string &bundleName) override; + + /** + * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @param uid, uid. + * @return ERR_OK, return back success, others fail. + */ + virtual int KillApplicationByUid(const std::string &bundleName, const int uid) override; + + virtual void AbilityAttachTimeOut(const sptr &token) override; + + virtual void PrepareTerminate(const sptr &token) override; + + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override; + + virtual void GetRunningProcessInfoByToken( + const sptr &token, AppExecFwk::RunningProcessInfo &info) override; + + virtual void StartSpecifiedAbility( + const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) override; + + virtual void RegisterStartSpecifiedAbilityResponse(const sptr &response) override; + + /** + * ANotify application update system environment changes. + * + * @param config System environment change parameters. + * @return Returns ERR_OK on success, others on failure. + */ + virtual void UpdateConfiguration(const Configuration &config) override; + + virtual int GetConfiguration(Configuration& config) override; + +private: + /** + * @brief Judge whether the application service is ready. + * + * @return Returns true means service is ready, otherwise service is not ready. + */ + bool IsReady() const; + +private: + std::shared_ptr amsMgrServiceInner_; + std::shared_ptr amsHandler_; + sptr systemAbilityMgr_; + + DISALLOW_COPY_AND_MOVE(AmsMgrScheduler); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_SCHEDULER_H diff --git a/services/appmgr/include/app_death_recipient.h b/services/appmgr/include/app_death_recipient.h new file mode 100644 index 0000000000000000000000000000000000000000..39179e0b3a0e9864b882dc210820b8634f83b888 --- /dev/null +++ b/services/appmgr/include/app_death_recipient.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_DEATH_RECIPIENT_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +#include "app_mgr_service_event_handler.h" + +namespace OHOS { +namespace AppExecFwk { +class AppMgrServiceInner; + +class AppDeathRecipient : public IRemoteObject::DeathRecipient { +public: + virtual void OnRemoteDied(const wptr &remote) override; + + /** + * @brief Setting event handler instance. + * + * @param handler, event handler instance. + */ + void SetEventHandler(const std::shared_ptr &handler); + + /** + * @brief Setting application service internal handler instance. + * + * @param serviceInner, application service internal handler instance. + */ + void SetAppMgrServiceInner(const std::shared_ptr &serviceInner); + +private: + std::weak_ptr handler_; + std::weak_ptr appMgrServiceInner_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_DEATH_RECIPIENT_H diff --git a/services/appmgr/include/app_lifecycle_deal.h b/services/appmgr/include/app_lifecycle_deal.h new file mode 100644 index 0000000000000000000000000000000000000000..1e9b8bc125f63b6b74747c7f984ff5f1f8895fdd --- /dev/null +++ b/services/appmgr/include/app_lifecycle_deal.h @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_LIFECYCLE_DEAL_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_LIFECYCLE_DEAL_H + +#include "app_scheduler_proxy.h" +#include "app_launch_data.h" +#include "ability_running_record.h" +#include "hap_module_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class AppLifeCycleDeal { +public: + AppLifeCycleDeal(); + virtual ~AppLifeCycleDeal(); + + /** + * LaunchApplication, call ScheduleLaunchApplication() through proxy project, + * Notify application to launch application. + * + * @param The app data value. + * + * @return + */ + void LaunchApplication(const AppLaunchData &launchData_, const Configuration &config); + + /** + * AddAbilityStageInfo, call ScheduleAbilityStageInfo() through proxy project, + * Notify application to launch application. + * + * @param The app data value. + * + * @return + */ + void AddAbilityStage(const HapModuleInfo &abilityStage); + + /** + * LaunchAbility, call ScheduleLaunchAbility() through proxy project, + * Notify application to launch ability. + * + * @param The ability info. + * @return + */ + void LaunchAbility(const std::shared_ptr &ability); + + /** + * ScheduleTerminate, call ScheduleTerminateApplication() through proxy project, + * Notify application to terminate. + * + * @return + */ + void ScheduleTerminate(); + + /** + * ScheduleForegroundRunning, call ScheduleForegroundApplication() through proxy project, + * Notify application to switch to foreground. + * + * @return + */ + void ScheduleForegroundRunning(); + + /** + * ScheduleBackgroundRunning, call ScheduleBackgroundApplication() through proxy project, + * Notify application to switch to background. + * + * @return + */ + void ScheduleBackgroundRunning(); + + /** + * ScheduleTrimMemory, call ScheduleShrinkMemory() through proxy project, + * Notifies the application of the memory seen. + * + * @param The memory value. + * + * @return + */ + void ScheduleTrimMemory(int32_t timeLevel); + + /** + * LowMemoryWarning, call ScheduleLowMemory() through proxy project, + * Notify application to low memory. + * + * @return + */ + void LowMemoryWarning(); + + /** + * ScheduleCleanAbility, call ScheduleCleanAbility() through proxy project, + * Notify application to clean ability. + * + * @param token, The ability token. + * @return + */ + void ScheduleCleanAbility(const sptr &token); + + /** + * ScheduleProcessSecurityExit, call ScheduleTerminateApplication() through proxy project, + * Notify application process exit safely. + * + * @return + */ + void ScheduleProcessSecurityExit(); + + /** + * @brief Setting client for application record. + * + * @param thread, the application client. + */ + void SetApplicationClient(const sptr &thread); + + /** + * @brief Obtains the client of the application record. + * + * @return Returns the application client. + */ + sptr GetApplicationClient() const; + + void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName); + + /** + * UpdateConfiguration, ANotify application update system environment changes. + * + * @param config, System environment change parameters. + */ + void UpdateConfiguration(const Configuration &config); + +private: + sptr appThread_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_LIFECYCLE_DEAL_H \ No newline at end of file diff --git a/services/appmgr/include/app_mgr_service.h b/services/appmgr/include/app_mgr_service.h new file mode 100644 index 0000000000000000000000000000000000000000..3ed7ee2b964bf5b1107b821d2f1709cf9b5f4961 --- /dev/null +++ b/services/appmgr/include/app_mgr_service.h @@ -0,0 +1,298 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_H + +#include +#include +#include + +#include "if_system_ability_manager.h" +#include "nocopyable.h" +#include "system_ability.h" + +#include "ability_info.h" +#include "ability_running_record.h" +#include "appexecfwk_errors.h" +#include "application_info.h" +#include "app_mgr_constants.h" +#include "app_mgr_stub.h" +#include "app_mgr_service_event_handler.h" +#include "app_mgr_service_inner.h" +#include "app_record_id.h" +#include "app_running_record.h" +#include "app_scheduler_proxy.h" +#include "ams_mgr_scheduler.h" + +namespace OHOS { +namespace AppExecFwk { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; + +struct AppMgrServiceState { + ServiceRunningState serviceRunningState = ServiceRunningState::STATE_NOT_START; + SpawnConnectionState connectionState = SpawnConnectionState::STATE_NOT_CONNECT; +}; + +class AMSEventHandler; + +class AppMgrService : public SystemAbility, public AppMgrStub { +public: + DECLEAR_SYSTEM_ABILITY(AppMgrService); + + AppMgrService(); + AppMgrService(const int32_t serviceId, bool runOnCreate = false); + virtual ~AppMgrService() override; + + // the function about application + // attach the application to ams, then ams can control it. + /** + * AttachApplication, call AttachApplication() through proxy object, + * get all the information needed to start the Application (data related to the Application ). + * + * @param app, information needed to start the Application. + * @return + */ + virtual void AttachApplication(const sptr &app) override; + + // notify the ams update the state of an app, when it entered foreground. + + /** + * ApplicationForegrounded, call ApplicationForegrounded() through proxy object, + * set the application to Foreground State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationForegrounded(const int32_t recordId) override; + + /** + * ApplicationBackgrounded, call ApplicationBackgrounded() through proxy object, + * set the application to Backgrounded State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationBackgrounded(const int32_t recordId) override; + + /** + * ApplicationTerminated, call ApplicationTerminated() through proxy object, + * terminate the application. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationTerminated(const int32_t recordId) override; + + /** + * AbilityCleaned,call through AbilityCleaned() proxy project, clean Ability record. + * + * @param token, a unique record that identifies AbilityCleaned from others. + * @return + */ + virtual void AbilityCleaned(const sptr &token) override; + + /** + * ClearUpApplicationData, call ClearUpApplicationData() through proxy project, + * clear the application data. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t ClearUpApplicationData(const std::string &bundleName) override; + + /** + * IsBackgroundRunningRestricted, call IsBackgroundRunningRestricted() through proxy project, + * Checks whether the process of this application is forbidden to run in the background. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t IsBackgroundRunningRestricted(const std::string &bundleName) override; + + /** + * GetAllRunningProcesses, call GetAllRunningProcesses() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetAllRunningProcesses(std::vector &info) override; + + /** + * GetProcessRunningInfosByUserId, call GetProcessRunningInfosByUserId() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @param userId, userId. + * + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) override; + + // the function about system + /** + * CheckPermission, call CheckPermission() through proxy object, check the permission. + * + * @param recordId, a unique record that identifies this Application from others. + * @param permission, check the permissions. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t CheckPermission(const int32_t recordId, const std::string &permission) override; + + // the function about service running info + /** + * QueryServiceState, Query application service status. + * + * @return the application service status. + */ + AppMgrServiceState QueryServiceState(); + + /** + * GetAmsMgr, call GetAmsMgr() through proxy object, get AMS interface instance. + * + * @return sptr, return to AMS interface instance. + */ + virtual sptr GetAmsMgr() override; + + /** + * SetAppSuspendTimes, Setting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void SetAppFreezingTime(int time) override; + + /** + * GetAppFreezingTime, Getting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void GetAppFreezingTime(int &time) override; + + /** + * Get system memory information. + * @param SystemMemoryAttr, memory information. + */ + virtual void GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig) override; + + /** + * Notify that the ability stage has been updated + * @param recordId, the app record. + */ + virtual void AddAbilityStageDone(const int32_t recordId) override; + + /** + * Start all resident process + */ + virtual void StartupResidentProcess() override; + + /** + * Start user test process. + * @param want, want object. + * @param observer, test observer remote object. + * @param bundleInfo, bundle info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const AppExecFwk::BundleInfo &bundleInfo) override; + + virtual void ScheduleAcceptWantDone( + const int32_t recordId, const AAFwk::Want &want, const std::string &flag) override; + +private: + /** + * Init, Initialize application services. + * + * @return ERR_OK, return back success, others fail. + */ + ErrCode Init(); + + // the function that overrode from SystemAbility + /** + * OnStart, Start application service. + * + * @return + */ + virtual void OnStart() override; + + /** + * OnStop, Stop application service. + * + * @return + */ + virtual void OnStop() override; + + /** + * @brief Judge whether the application service is ready. + * + * @return Returns true means service is ready, otherwise service is not ready. + */ + bool IsReady() const; + + /** + * AddAppDeathRecipient, Add monitoring death application record. + * + * @param pid, the application pid. + * @param appDeathRecipient, Application death recipient list. + * + * @return + */ + void AddAppDeathRecipient(const pid_t pid) const; + + /** + * SetInnerService, Setting application service Inner instance. + * + * @return + */ + void SetInnerService(const std::shared_ptr &innerService); + + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t RegisterApplicationStateObserver(const sptr &observer) override; + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) override; + + /** + * Get foreground applications. + * @param list, foreground apps. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetForegroundApplications(std::vector &list) override; + +private: + std::shared_ptr appMgrServiceInner_; + AppMgrServiceState appMgrServiceState_; + std::shared_ptr runner_; + std::shared_ptr handler_; + sptr systemAbilityMgr_; + sptr amsMgrScheduler_; + + DISALLOW_COPY_AND_MOVE(AppMgrService); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_H diff --git a/services/appmgr/include/app_mgr_service_event_handler.h b/services/appmgr/include/app_mgr_service_event_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..4ae9f1a416fc925340ad8bfffc40c67ae8d287c5 --- /dev/null +++ b/services/appmgr/include/app_mgr_service_event_handler.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_EVENT_HANDLER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_EVENT_HANDLER_H + +#include "event_handler.h" + +namespace OHOS { +namespace AppExecFwk { +class AppMgrServiceInner; + +class AMSEventHandler : public EventHandler { +public: + AMSEventHandler(const std::shared_ptr &runner, const std::weak_ptr &appMgr); + virtual ~AMSEventHandler() override; + + virtual void ProcessEvent(const InnerEvent::Pointer &event) override; + + static constexpr uint32_t TERMINATE_ABILITY_TIMEOUT_MSG = 0; + static constexpr uint32_t TERMINATE_APPLICATION_TIMEOUT_MSG = 1; + static constexpr uint32_t ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG = 2; + static constexpr uint32_t START_MULTI_INSTANCES_ABILITY_MSG = 3; + static constexpr uint32_t TERMINATE_ABILITY_TIMEOUT = 500; + static constexpr uint32_t TERMINATE_APPLICATION_TIMEOUT = 500; + static constexpr uint32_t ADD_ABILITY_STAGE_INFO_TIMEOUT = 3000; // ms + static constexpr uint32_t START_MULTI_INSTANCES_ABILITY_TIMEOUT = 3000; // ms +private: + std::weak_ptr appMgr_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_EVENT_HANDLER_H diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h new file mode 100644 index 0000000000000000000000000000000000000000..6d38e4a0c079e9a394369b8e80b4ee6fd2c8aafc --- /dev/null +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -0,0 +1,834 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_INNER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_INNER_H + +#include +#include +#include +#include + +#include "iremote_object.h" +#include "refbase.h" + +#include "ability_info.h" +#include "appexecfwk_errors.h" +#include "app_death_recipient.h" +#include "app_mgr_constants.h" +#include "app_record_id.h" +#include "app_running_record.h" +#include "app_scheduler_interface.h" +#include "app_spawn_client.h" +#include "app_task_info.h" +#include "iapp_state_callback.h" +#include "iapplication_state_observer.h" +#include "app_process_manager.h" +#include "remote_client_manager.h" +#include "app_running_manager.h" +#include "record_query_result.h" +#include "running_process_info.h" +#include "bundle_info.h" +#include "istart_specified_ability_response.h" + +#include "process_optimizer_uba.h" + +#include "ohos/aafwk/content/want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; + +class AppMgrServiceInner : public std::enable_shared_from_this { +public: + AppMgrServiceInner(); + virtual ~AppMgrServiceInner(); + + /** + * Initialize the object. + */ + void Init(); + /** + * LoadAbility, load the ability that needed to be started. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param abilityInfo, the ability information. + * @param appInfo, the app information. + * + * @return + */ + virtual void LoadAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo); + + /** + * TerminateAbility, terminate the token ability. + * + * @param token, he unique identification to terminate the ability. + * + * @return + */ + virtual void TerminateAbility(const sptr &token); + + /** + * UpdateAbilityState, update the ability status. + * + * @param token, the unique identification to update the ability. + * @param state, ability status that needs to be updated. + * + * @return + */ + virtual void UpdateAbilityState(const sptr &token, const AbilityState state); + + /** + * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status. + * + * @param token, the unique identification to update the extension. + * @param state, extension status that needs to be updated. + */ + virtual void UpdateExtensionState(const sptr &token, const ExtensionState state); + + /** + * StateChangedNotifyObserver, Call ability state change. + * + * @param ability, the ability info. + * @param state, the ability state. + * + * @return + */ + void StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility); + + /** + * RegisterAppStateCallback, register the callback. + * + * @param callback, Ams register the callback. + * + * @return + */ + virtual void RegisterAppStateCallback(const sptr &callback); + + /** + * StopAllProcess, Terminate all processes. + * + * @return + */ + virtual void StopAllProcess(); + + /** + * AbilityBehaviorAnalysis, ability behavior analysis assistant process optimization. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param visibility, the visibility information about windows info. + * @param perceptibility, the Perceptibility information about windows info. + * @param connectionState, the service ability connection state. + * @return + */ + virtual void AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState); + + /** + * KillProcessByAbilityToken, kill the process by ability token. + * + * @param token, the unique identification to the ability. + * @return + */ + virtual void KillProcessByAbilityToken(const sptr &token); + + /** + * KillProcessesByUserId, kill the processes by userId. + * + * @param userId, the user id. + * @return + */ + virtual void KillProcessesByUserId(int32_t userId); + + /** + * AttachApplication, get all the information needed to start the Application + * (data related to the Application ). + * + * @param app, information needed to start the Application. + * + * @return + */ + virtual void AttachApplication(const pid_t pid, const sptr &app); + + /** + * ApplicationForegrounded, set the application to Foreground State. + * + * @param recordId, a unique record that identifies this Application from others. + * + * @return + */ + virtual void ApplicationForegrounded(const int32_t recordId); + + /** + * ApplicationBackgrounded, set the application to Backgrounded State. + * + * @param recordId, a unique record that identifies this Application from others. + * + * @return + */ + virtual void ApplicationBackgrounded(const int32_t recordId); + + /** + * ApplicationTerminated, terminate the application. + * + * @param recordId, a unique record that identifies this Application from others. + * + * @return + */ + virtual void ApplicationTerminated(const int32_t recordId); + + /** + * AbilityTerminated, terminate the ability. + * + * @param token, the unique identification to terminated the ability. + * + * @return + */ + virtual void AbilityTerminated(const sptr &token); + + /** + * KillApplication, kill the application. + * + * @param bundleName, bundle name in Application record. + * + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillApplication(const std::string &bundleName); + + /** + * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @param uid, uid. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillApplicationByUid(const std::string &bundleName, const int uid); + + /** + * KillApplicationByUserId, kill the application by user ID. + * + * @param bundleName, bundle name in Application record. + * @param userId, user ID. + * + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t KillApplicationByUserId(const std::string &bundleName, const int userId); + + /** + * ClearUpApplicationData, clear the application data. + * + * @param bundleName, bundle name in Application record. + * @param callerUid, app uid in Application record. + * @param callerPid, app pid in Application record. + * + * @return + */ + virtual void ClearUpApplicationData(const std::string &bundleName, const int32_t callerUid, const pid_t callerPid); + + /** + * IsBackgroundRunningRestricted, Checks whether the process of this application is forbidden + * to run in the background. + * + * @param bundleName, bundle name in Application record. + * + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t IsBackgroundRunningRestricted(const std::string &bundleName); + + /** + * GetAllRunningProcesses, Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetAllRunningProcesses(std::vector &info); + + /** + * GetProcessRunningInfosByUserId, Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @param userId, userId. + * + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetProcessRunningInfosByUserId(std::vector &info, int32_t userId); + + // Get AppRunningRecord according to appInfo. Create if not exists. + // Create ability record if not exists and abilityInfo not null. + // Return AppRunningRecord pointer if success get or create. + // If error occurs, error code is in |result| + + /** + * CreateAppRunningRecord, create application record information. + * + * @param token, the unique identification to the ability. + * @param abilityInfo, ability information. + * @param appInfo, app information. + * @param processName, the app process name. + * @param uid, app uid in Application record. + * @param result, If error occurs, error code is in |result|. + * + * @return AppRunningRecord pointer if success create. + */ + std::shared_ptr CreateAppRunningRecord( + const sptr &token, + const sptr &preToken, + const std::shared_ptr &appInfo, + const std::shared_ptr &abilityInfo, + const std::string &processName, + const BundleInfo &bundleInfo, + const HapModuleInfo &hapModuleInfo); + + /** + * OnStop, Application management service stopped. + * + * @return + */ + void OnStop(); + + /** + * OpenAppSpawnConnection, Open connection with appspwan. + * + * @return ERR_OK ,return back success,others fail. + */ + virtual ErrCode OpenAppSpawnConnection(); + + /** + * CloseAppSpawnConnection, Close connection with appspwan. + * + * @return + */ + virtual void CloseAppSpawnConnection() const; + + /** + * QueryAppSpawnConnectionState, Query the connection status with appspwan. + * + * @return Returns the connection status with appspwan. + */ + virtual SpawnConnectionState QueryAppSpawnConnectionState() const; + + /** + * SetAppSpawnClient, Setting the client to connect with appspwan. + * + * @param spawnClient, the client to connect with appspwan. + * + * @return + */ + void SetAppSpawnClient(std::shared_ptr spawnClient); + + // Schedule launch application with specified |appRecord| + + /** + * LaunchApplication, Notify application to launch application. + * + * @param appRecord, the application record. + * + * @return + */ + void LaunchApplication(const std::shared_ptr &appRecord); + + /** + * Notice of AddAbilityStageInfo() + * + * @param recordId, the application record. + */ + virtual void AddAbilityStageDone(const int32_t recordId); + + /** + * GetRecordMap, Get all the ability information in the application record. + * + * @return all the ability information in the application record. + */ + const std::map> &GetRecordMap() const; + + /** + * GetAppRunningRecordByPid, Get process record by application pid. + * + * @param pid, the application pid. + * + * @return process record. + */ + std::shared_ptr GetAppRunningRecordByPid(const pid_t pid) const; + + /** + * GetAppRunningRecordByAbilityToken, Get process record by ability token. + * + * @param abilityToken, the ability token. + * + * @return process record. + */ + std::shared_ptr GetAppRunningRecordByAbilityToken(const sptr &abilityToken) const; + + /** + * GetAppRunningRecordByAppRecordId, Get process record by application id. + * + * @param recordId, the application id. + * + * @return process record. + */ + std::shared_ptr GetAppRunningRecordByAppRecordId(const int32_t recordId) const; + + /** + * OnAbilityStateChanged, Call ability state change. + * + * @param ability, the ability info. + * @param state, the ability state. + * + * @return + */ + void OnAbilityStateChanged(const std::shared_ptr &ability, const AbilityState state); + + /** + * GetRecentAppList, Get a list of recent applications. + * + * @return a list of recent applications. + */ + const std::list> &GetRecentAppList() const; + + /** + * GetRecentAppList, Remove the corresponding latest application list data by applying the name. + * + * @param appName, the application name. + * @param processName, the process name. + * + * @return + */ + void RemoveAppFromRecentList(const std::string &appName, const std::string &processName); + + /** + * GetRecentAppList, Clear recent application list. + * + * @return + */ + void ClearRecentAppList(); + + /** + * OnRemoteDied, Equipment death notification. + * + * @param remote, Death client. + * @return + */ + void OnRemoteDied(const wptr &remote); + + /** + * AddAppDeathRecipient, Add monitoring death application record. + * + * @param pid, the application pid. + * @param appDeathRecipient, Application death recipient list. + * + * @return + */ + + virtual void AddAppDeathRecipient(const pid_t pid, const sptr &appDeathRecipient) const; + /** + * ProcessOptimizerInit, Process Optimizer init. + * + * @param + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t ProcessOptimizerInit(); + + /** + * OptimizerAbilityStateChanged, Optimizer processing ability state changes. + * + * @param ability, the ability info. + * @param state, the ability state before change. + * + * @return + */ + virtual void OptimizerAbilityStateChanged( + const std::shared_ptr &ability, const AbilityState state); + + /** + * OptimizerAppStateChanged, Optimizer processing app state changes. + * + * @param appRecord, the app information. + * @param state, the app before change. + * @return + */ + virtual void OptimizerAppStateChanged( + const std::shared_ptr &appRecord, const ApplicationState state); + + /** + * SetAppSuspendTimes, Setting the Freezing Time of APP Background. + * + * @param time, The timeout(second) recorded when the application enters the background . + * + * @return Success or Failure . + */ + void SetAppFreezingTime(int time); + + /** + * GetAppFreezingTime, Getting the Freezing Time of APP Background. + * + * @param time, The timeout(second) recorded when the application enters the background . + * + * @return Success or Failure . + */ + void GetAppFreezingTime(int &time); + void HandleTimeOut(const InnerEvent::Pointer &event); + + void SetEventHandler(const std::shared_ptr &handler); + + void HandleAbilityAttachTimeOut(const sptr &token); + + void PrepareTerminate(const sptr &token); + + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message); + + /** + * SuspendApplication, Application state changed. + * + * @param appRecord, the app information. + * @param state, the app state. + */ + void OnAppStateChanged(const std::shared_ptr &appRecord, const ApplicationState state); + + void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info); + + /** + * UpdateConfiguration, ANotify application update system environment changes. + * + * @param config, System environment change parameters. + */ + void UpdateConfiguration(const Configuration &config); + + std::shared_ptr GetConfiguration(); + /** + * Start empty process + */ + void LoadResidentProcess(); + + void StartResidentProcess(const std::vector &v, int restartCount); + + bool CheckRemoteClient(); + + /** + * Register application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t RegisterApplicationStateObserver(const sptr &observer); + + /** + * Unregister application or process state observer. + * @param observer, ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t UnregisterApplicationStateObserver(const sptr &observer); + + /** + * Get Foreground Applications. + * + * @return Foreground Applications. + */ + int32_t GetForegroundApplications(std::vector &list); + + /** + * Start user test process. + * @param want, want object. + * @param observer, test observer remote object. + * @param bundleInfo, bundle info. + * @return Returns ERR_OK on success, others on failure. + */ + int StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const AppExecFwk::BundleInfo &bundleInfo); + + void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + + void RegisterStartSpecifiedAbilityResponse(const sptr &response); + + void ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag); + +private: + + void StartEmptyResidentProcess(const BundleInfo &info, const std::string &processName, int restartCount); + + void RestartResidentProcess(std::shared_ptr appRecord); + + bool CheckLoadabilityConditions(const sptr &token, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo); + + bool GetBundleInfo(const std::string &bundelName, BundleInfo &bundleInfo); + + void MakeProcessName(std::string &processName, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo); + /** + * StartAbility, load the ability that needed to be started(Start on the basis of the original process). + * Start on a new boot process + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param abilityInfo, the ability information. + * @param appInfo, the app information. + * + * @return + */ + void StartAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appRecord, + const HapModuleInfo &hapModuleInfo); + + /** + * UnsuspendApplication, Application process state switch to unsuspend. + * + * @param appRecord, the app information. + * + * @return + */ + void UnsuspendApplication(const std::shared_ptr &appRecord); + + /** + * SuspendApplication, Application process state switch to suspend. + * + * @param appRecord, the app information. + * + * @return + */ + void SuspendApplication(const std::shared_ptr &appRecord); + + /** + * LowMemoryApplicationAlert, Application low memory alert. + * + * @param appRecord, the app information. + * @param level, the app low memory level. + * + * @return + */ + void LowMemoryApplicationAlert( + const std::shared_ptr &appRecord, const CgroupManager::LowMemoryLevel level); + + /** + * GetAbilityOwnerApp, Get the process record of ability. + * + * @param abilityRecord, the ability information. + * + * @return process record. + */ + std::shared_ptr GetAbilityOwnerApp( + const std::shared_ptr &abilityRecord) const; + + /** + * GetAbilityRunningRecordByAbilityToken, Get the ability record by token. + * + * @param abilityToken, the ability token. + * + * @return ability record. + */ + std::shared_ptr GetAbilityRunningRecordByAbilityToken( + const sptr &abilityToken) const; + + /** + * StartProcess, load the ability that needed to be started(Start on a new boot process). + * + * @param appName, the app name. + * @param processName, the process name. + * @param appRecord, the app information. + * @param uid, the process uid. + * @param bundleName, the app bundleName. + * + * @return + */ + void StartProcess( + const std::string &appName, const std::string &processName, const std::shared_ptr &appRecord, + const int uid, const std::string &bundleName); + + /** + * PushAppFront, Adjust the latest application record to the top level. + * + * @param recordId, the app record id. + * + * @return + */ + void PushAppFront(const int32_t recordId); + + /** + * RemoveAppFromRecentListById, Remove the specified recent application record by application record id. + * + * @param recordId, the app record id. + * + * @return + */ + void RemoveAppFromRecentListById(const int32_t recordId); + + /** + * AddAppToRecentList, Add application to recent list. + * + * @param appName, the app name. + * @param processName, the process name. + * @param pid, the app pid. + * @param recordId, the app record id. + * + * @return + */ + void AddAppToRecentList( + const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId); + + /** + * AddAppToRecentList, Get application task information through ID. + * + * @param recordId, the app record id. + * + * @return application task information. + */ + const std::shared_ptr GetAppTaskInfoById(const int32_t recordId) const; + + /** + * KillProcessByPid, Kill process by PID. + * + * @param pid_t, the app record pid. + * + * @return ERR_OK, return back success,others fail. + */ + int32_t KillProcessByPid(const pid_t pid) const; + + /** + * WaitForRemoteProcessExit, Wait for the process to exit normally. + * + * @param pids, process number collection to exit. + * @param startTime, execution process security exit start time. + * + * @return true, return back success,others fail. + */ + bool WaitForRemoteProcessExit(std::list &pids, const int64_t startTime); + + /** + * GetAllPids, Get the corresponding pid collection. + * + * @param pids, process number collection to exit. + * + * @return true, return back success,others fail. + */ + bool GetAllPids(std::list &pids); + + /** + * process_exist, Judge whether the process exists. + * + * @param pids, process number collection to exit. + * + * @return true, return back existed,others non-existent. + */ + bool process_exist(pid_t &pid); + + /** + * CheckAllProcessExist, Determine whether all processes exist . + * + * @param pids, process number collection to exit. + * + * @return true, Returns that a process exists and all other processes do not exist. + */ + bool CheckAllProcessExist(std::list &pids); + + /** + * SystemTimeMillis, Get system time. + * + * @return the system time. + */ + int64_t SystemTimeMillis(); + + // Test add the bundle manager instance. + void SetBundleManager(sptr bundleManager); + + void HandleTerminateApplicationTimeOut(const int64_t eventId); + + void HandleAddAbilityStageTimeOut(const int64_t eventId); + + void ClipStringContent(const std::regex &re, const std::string &sorce, std::string &afferCutStr); + + bool GetBundleAndHapInfo(const AbilityInfo &abilityInfo, const std::shared_ptr &appInfo, + BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo); + AppProcessData WrapAppProcessData(const std::shared_ptr &appRecord, + const ApplicationState state); + + AppStateData WrapAppStateData(const std::shared_ptr &appRecord, + const ApplicationState state); + + ProcessData WrapProcessData(const std::shared_ptr &appRecord); + + void AddObserverDeathRecipient(const sptr &observer); + + void RemoveObserverDeathRecipient(const sptr &observer); + + void OnObserverDied(const wptr &remote); + + void HandleObserverDiedTask(const sptr &observer); + + bool ObserverExist(const sptr &observer); + + void OnProcessCreated(const std::shared_ptr &appRecord); + + void OnProcessDied(const std::shared_ptr &appRecord); + + int StartEmptyProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &info, const std::string &processName); + + void HandleStartSpecifiedAbilityTimeOut(const int64_t eventId); + + void GetGlobalConfiguration(); + +private: + /** + * ClearUpApplicationData, clear the application data. + * + * @param bundleName, bundle name in Application record. + * @param uid, app uid in Application record. + * @param pid, app pid in Application record. + * @param userId, userId. + * + * @return + */ + void ClearUpApplicationDataByUserId(const std::string &bundleName, + int32_t callerUid, pid_t callerPid, const int userId); + +private: + /** + * Notify application status. + * + * @param bundleName Indicates the name of the bundle. + * @param eventData Indicates the event defined by CommonEventSupport + * + * @return + */ + void NotifyAppStatus(const std::string &bundleName, const std::string &eventData); + + const std::string TASK_ON_CALLBACK_DIED = "OnCallbackDiedTask"; + std::vector> appStateObservers_; + std::map, sptr> recipientMap_; + std::recursive_mutex observerLock_; + std::vector> appStateCallbacks_; + std::shared_ptr appProcessManager_; + std::shared_ptr remoteClientManager_; + std::shared_ptr appRunningManager_; + std::shared_ptr processOptimizerUBA_; + std::shared_ptr eventHandler_; + std::shared_ptr configuration_; + std::mutex serviceLock_; + sptr startSpecifiedAbilityResponse_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_INNER_H diff --git a/services/appmgr/include/app_process_manager.h b/services/appmgr/include/app_process_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..9e92a62df7c312875048d4eacd342a75601cbd5b --- /dev/null +++ b/services/appmgr/include/app_process_manager.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_PROCESS_MANAGER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_PROCESS_MANAGER_H + +#include + +#include "iremote_object.h" +#include "refbase.h" + +#include "app_task_info.h" + +namespace OHOS { +namespace AppExecFwk { +class AppProcessManager { +public: + AppProcessManager(); + virtual ~AppProcessManager(); + + /** + * RemoveAppFromRecentList, Remove the corresponding latest application list data. + * + * @param appTaskInfo, the application task information. + * + * @return + */ + void RemoveAppFromRecentList(const std::shared_ptr &appTaskInfo); + + /** + * GetRecentAppList, Clear recent application list. + * + * @return + */ + void ClearRecentAppList(); + + /** + * AddAppToRecentList, Add application to recent list. + * + * @param appName, the app name. + * @param processName, the process name. + * @param pid, the app pid. + * @param recordId, the app record id. + * + * @return + */ + void AddAppToRecentList( + const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId); + + /** + * GetRecentAppList, Get a list of recent applications. + * + * @return a list of recent applications. + */ + const std::list> &GetRecentAppList() const; + + /** + * PushAppFront, Adjust the latest application record to the top level. + * + * @param recordId, the app record id. + * + * @return + */ + void PushAppFront(const int32_t recordId); + + /** + * RemoveAppFromRecentListById, Remove the specified recent application record by application record id. + * + * @param recordId, the app record id. + * + * @return + */ + void RemoveAppFromRecentListById(const int32_t recordId); + + /** + * AddAppToRecentList, Get application task information through ID. + * + * @param recordId, the app record id. + * + * @return application task information. + */ + const std::shared_ptr GetAppTaskInfoById(const int32_t recordId) const; + + /** + * GetAppTaskInfoByProcessName, Get application task information through process name. + * + * @param appName, the application name. + * @param processName, the process name. + * + * @return application task information. + */ + std::shared_ptr GetAppTaskInfoByProcessName( + const std::string &appName, const std::string &processName) const; + +private: + std::list> recentAppList_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_PROCESS_MANAGER_H \ No newline at end of file diff --git a/services/appmgr/include/app_running_manager.h b/services/appmgr/include/app_running_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..8d38a1c0b23f1da23b2f05c7aac9468f451f85f4 --- /dev/null +++ b/services/appmgr/include/app_running_manager.h @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_RUNNING_MANAGER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_RUNNING_MANAGER_H + +#include +#include +#include + +#include "iremote_object.h" +#include "refbase.h" + +#include "app_running_record.h" +#include "ability_info.h" +#include "application_info.h" +#include "app_state_data.h" +#include "record_query_result.h" +#include "running_process_info.h" +#include "bundle_info.h" + +namespace OHOS { +namespace AppExecFwk { +class AppRunningManager { +public: + AppRunningManager(); + virtual ~AppRunningManager(); + /** + * CreateAppRunningRecord, Get or create application record information. + * + * @param token, the unique identification to start the ability. + * @param abilityInfo, ability information. + * @param appInfo, app information. + * @param processName, app process name. + * @param uid, app uid in Application record. + * @param result, If error occurs, error code is in |result|. + * + * @return AppRunningRecord pointer if success get or create. + */ + std::shared_ptr CreateAppRunningRecord( + const std::shared_ptr &appInfo, const std::string &processName, const BundleInfo &bundleInfo); + + /** + * CheckAppRunningRecordIsExist, Get process record by application name and process Name. + * + * @param appName, the application name. + * @param processName, the process name. + * @param uid, the process uid. + * + * @return process record. + */ + std::shared_ptr CheckAppRunningRecordIsExist(const std::string &appName, + const std::string &processName, const int uid, const BundleInfo &bundleInfo); + + /** + * GetAppRunningRecordByPid, Get process record by application pid. + * + * @param pid, the application pid. + * + * @return process record. + */ + std::shared_ptr GetAppRunningRecordByPid(const pid_t pid); + + /** + * GetAppRunningRecordByAbilityToken, Get process record by ability token. + * + * @param abilityToken, the ability token. + * + * @return process record. + */ + std::shared_ptr GetAppRunningRecordByAbilityToken(const sptr &abilityToken); + + /** + * OnRemoteDied, Equipment death notification. + * + * @param remote, Death client. + * @return + */ + std::shared_ptr OnRemoteDied(const wptr &remote); + + /** + * GetAppRunningRecordMap, Get application record list. + * + * @return the application record list. + */ + const std::map> &GetAppRunningRecordMap(); + + /** + * RemoveAppRunningRecordById, Remove application information through application id. + * + * @param recordId, the application id. + * @return + */ + void RemoveAppRunningRecordById(const int32_t recordId); + + /** + * ClearAppRunningRecordMap, Clear application record list. + * + * @return + */ + void ClearAppRunningRecordMap(); + + /** + * Get the pid of a non-resident process. + * + * @return Return true if found, otherwise return false. + */ + bool ProcessExitByBundleName(const std::string &bundleName, std::list &pids); + /** + * Get Foreground Applications. + * + * @return Foreground Applications. + */ + void GetForegroundApplications(std::vector &list); + + /* + * ANotify application update system environment changes. + * + * @param config System environment change parameters. + * @return + */ + void UpdateConfiguration(const Configuration &config); + void HandleTerminateTimeOut(int64_t eventId); + void HandleAbilityAttachTimeOut(const sptr &token); + std::shared_ptr GetAppRunningRecord(const int64_t eventId); + void TerminateAbility(const sptr &token); + bool ProcessExitByBundleNameAndUid(const std::string &bundleName, const int uid, std::list &pids); + bool GetPidsByUserId(int32_t userId, std::list &pids); + + void PrepareTerminate(const sptr &token); + + std::shared_ptr GetTerminatingAppRunningRecord(const sptr &abilityToken); + + void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info); + + void ClipStringContent(const std::regex &re, const std::string &sorce, std::string &afferCutStr); + void HandleAddAbilityStageTimeOut(const int64_t eventId); + void HandleStartSpecifiedAbilityTimeOut(const int64_t eventId); +private: + std::shared_ptr GetAbilityRunningRecord(const int64_t eventId); + +private: + std::map> appRunningRecordMap_; + std::map processRestartRecord_; + std::recursive_mutex lock_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_RUNNING_MANAGER_H \ No newline at end of file diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h new file mode 100644 index 0000000000000000000000000000000000000000..2a010e28da4bccdf0d24b8d01a30529a780e111f --- /dev/null +++ b/services/appmgr/include/app_running_record.h @@ -0,0 +1,534 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_RUNNING_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_RUNNING_RECORD_H + +#include +#include +#include +#include +#include "iremote_object.h" +#include "ability_running_record.h" +#include "ability_state_data.h" +#include "application_info.h" +#include "app_death_recipient.h" +#include "app_launch_data.h" +#include "app_mgr_constants.h" +#include "app_scheduler_proxy.h" +#include "app_record_id.h" +#include "profile.h" +#include "priority_object.h" +#include "app_lifecycle_deal.h" +#include "module_running_record.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int RESTART_RESIDENT_PROCESS_MAX_TIMES = 15; +} +class AbilityRunningRecord; +class AppMgrServiceInner; +class AppRunningRecord : public std::enable_shared_from_this { +public: + static int64_t appEventId_; +public: + AppRunningRecord( + const std::shared_ptr &info, const int32_t recordId, const std::string &processName); + virtual ~AppRunningRecord() = default; + + /** + * @brief Obtains the app record bundleName. + * + * @return Returns app record bundleName. + */ + const std::string &GetBundleName() const; + + /** + * @brief Obtains the app record isLauncherApp flag. + * + * @return Returns app record isLauncherApp flag. + */ + bool IsLauncherApp() const; + + /** + * @brief Obtains the app record id. + * + * @return Returns app record id. + */ + int32_t GetRecordId() const; + + /** + * @brief Obtains the app name. + * + * @return Returns the app name. + */ + const std::string &GetName() const; + + /** + * @brief Obtains the app clone info. + * + * @return Returns the app isCloned. + */ + bool GetCloneInfo() const; + + /** + * @brief Obtains the process name. + * + * @return Returns the process name. + */ + const std::string &GetProcessName() const; + + /** + * @brief Obtains the sign code. + * + * @return Returns the sign code. + */ + const std::string &GetSignCode() const; + + /** + * @brief Setting the sign code. + * + * @param code, the sign code. + */ + void SetSignCode(const std::string &signCode); + + /** + * @brief Obtains the jointUserId. + * + * @return Returns the jointUserId. + */ + const std::string &GetJointUserId() const; + + /** + * @brief Setting the jointUserId. + * + * @param jointUserId, the jointUserId. + */ + void SetJointUserId(const std::string &jointUserId); + + /** + * @brief Obtains the application uid. + * + * @return Returns the application uid. + */ + int32_t GetUid() const; + + /** + * @brief Setting the application uid. + * + * @param state, the application uid. + */ + void SetUid(const int32_t uid); + + // Get current state for this process + + /** + * @brief Obtains the application state. + * + * @return Returns the application state. + */ + ApplicationState GetState() const; + + // Set current state for this process + + /** + * @brief Setting the application state. + * + * @param state, the application state. + */ + void SetState(const ApplicationState state); + + // Get abilities_ for this process + /** + * @brief Obtains the abilitys info for the application record. + * + * @return Returns the abilitys info for the application record. + */ + const std::map, std::shared_ptr> GetAbilities(); + // Update appThread with appThread + + /** + * @brief Setting the application client. + * + * @param thread, the application client. + */ + void SetApplicationClient(const sptr &thread); + + /** + * @brief Obtains the application client. + * + * @return Returns the application client. + */ + sptr GetApplicationClient() const; + + // Add new module instance to current running modules list managed by this process + /** + * AddModule, Add new module instance to current running modules list managed by this process. + * + * @param appInfo, the app info. + * @param token, the unique identification to the ability. + * @param abilityInfo, the ability info. + * @param hapModuleInfo, the hapModule info. + * + * @return the ability record. + */ + void AddModule(const std::shared_ptr &appInfo, const std::shared_ptr &abilityInfo, + const sptr &token, const HapModuleInfo &hapModuleInfo); + + void AddModules(const std::shared_ptr &appInfo, const std::vector &moduleInfos); + + std::shared_ptr GetModuleRecordByModuleName( + const std::string bundleName, const std::string &moduleName); + + std::shared_ptr GetModuleRunningRecordByToken(const sptr &token) const; + + std::shared_ptr GetModuleRunningRecordByTerminateLists(const sptr &token) const; + + // It can only used in SINGLETON mode. + /** + * GetAbilityRunningRecord, Get ability record by the ability Name. + * + * @param abilityName, the ability name. + * + * @return the ability record. + */ + std::shared_ptr GetAbilityRunningRecord(const std::string &abilityName) const; + + std::shared_ptr GetAbilityRunningRecord(const int64_t eventId) const; + + // Clear(remove) the specified ability record from the list + + /** + * ClearAbility, Clear ability record by record info. + * + * @param record, the ability record. + * + * @return + */ + void ClearAbility(const std::shared_ptr &record); + + // Update the trim memory level value of this process + /** + * @brief Setting the Trim Memory Level. + * + * @param level, the Memory Level. + */ + void SetTrimMemoryLevel(int32_t level); + + // Kill this process with a given reason + /** + * ForceKillApp, Kill this process with a given reason. + * + * @param reason, The reason to kill the process. + * + * @return + */ + void ForceKillApp(const std::string &reason) const; + + // Schedule to crash this app with a given description + /** + * ScheduleAppCrash, Schedule to crash this app with a given description. + * + * @param description, the given description. + * + * @return + */ + void ScheduleAppCrash(const std::string &description) const; + + /** + * LaunchApplication, Notify application to launch application. + * + * @return + */ + void LaunchApplication(const Configuration &config); + + /** + * AddAbilityStage, Notify application to ability stage. + * + * @return + */ + void AddAbilityStage(); + + void AddAbilityStageBySpecifiedAbility(const std::string &bundleName); + + /** + * AddAbilityStage Result returned. + * + * @return + */ + void AddAbilityStageDone(); + + /** + * LaunchAbility, Notify application to launch ability. + * + * @param ability, the ability record. + * + * @return + */ + void LaunchAbility(const std::shared_ptr &ability); + + /** + * LaunchPendingAbilities, Launch Pending Abilities. + * + * @return + */ + void LaunchPendingAbilities(); + + /** + * LowMemoryWarning, Low memory warning. + * + * @return + */ + void LowMemoryWarning(); + + /** + * ScheduleTerminate, Notify application to terminate. + * + * @return + */ + void ScheduleTerminate(); + + /** + * ScheduleTerminate, Notify application process exit safely. + * + * @return + */ + void ScheduleProcessSecurityExit(); + + /** + * ScheduleTrimMemory, Notifies the application of the memory seen. + * + * @return + */ + void ScheduleTrimMemory(); + + /** + * GetAbilityRunningRecordByToken, Obtaining the ability record through token. + * + * @param token, the unique identification to the ability. + * + * @return + */ + std::shared_ptr GetAbilityRunningRecordByToken(const sptr &token) const; + + std::shared_ptr GetAbilityByTerminateLists(const sptr &token) const; + + /** + * UpdateAbilityState, update the ability status. + * + * @param token, the unique identification to update the ability. + * @param state, ability status that needs to be updated. + * + * @return + */ + void UpdateAbilityState(const sptr &token, const AbilityState state); + + /** + * PopForegroundingAbilityTokens, Extract the token record from the foreground tokens list. + * + * @return + */ + void PopForegroundingAbilityTokens(); + + /** + * TerminateAbility, terminate the token ability. + * + * @param token, he unique identification to terminate the ability. + * + * @return + */ + void TerminateAbility(const sptr &token, const bool isForce); + + /** + * AbilityTerminated, terminate the ability. + * + * @param token, the unique identification to terminated the ability. + * + * @return + */ + void AbilityTerminated(const sptr &token); + + /** + * @brief Setting application service internal handler instance. + * + * @param serviceInner, application service internal handler instance. + */ + void SetAppMgrServiceInner(const std::weak_ptr &inner); + + /** + * @brief Setting application death recipient. + * + * @param appDeathRecipient, application death recipient instance. + */ + void SetAppDeathRecipient(const sptr &appDeathRecipient); + + /** + * RegisterAppDeathRecipient, Register application death recipient. + * + * @return + */ + void RegisterAppDeathRecipient() const; + + /** + * @brief Obtains application priority info. + * + * @return Returns the application priority info. + */ + std::shared_ptr GetPriorityObject(); + + /** + * RegisterAppDeathRecipient, Remove application death recipient record. + * + * @return + */ + void RemoveAppDeathRecipient() const; + + /** + * Notify application update system environment changes. + * + * @param config System environment change parameters. + * @return + */ + void UpdateConfiguration(const Configuration &config); + + void SetEventHandler(const std::shared_ptr &handler); + + int64_t GetEventId() const; + + bool IsLastAbilityRecord(const sptr &token); + + void SetTerminating(); + + bool IsTerminating(); + + bool IsKeepAliveApp() const; + + // Please use with caution, it may affect the ability to start. + void SetKeepAliveAppState(bool isKeepAlive, bool isNewMission); + + std::list> GetAllModuleRecord() const; + + std::map>> &GetModules(); + + const std::list> GetAppInfoList(); + + void SetRestartResidentProcCount(int count); + void DecRestartResidentProcCount(); + int GetRestartResidentProcCount() const; + bool CanRestartResidentProc(); + + /** + * Notify observers when state change. + * + * @param ability, ability or extension record. + * @param state, ability or extension state. + */ + void StateChangedNotifyObserver(const std::shared_ptr &ability, int32_t state, bool isAbility); + + void insertAbilityStageInfo(std::vector moduleInfos); + + void GetBundleNames(std::vector &bundleNames); + + void SetUserTestInfo(const UserTestRecord &record); + + void SetSpecifiedAbilityFlagAndWant(const bool flag, const AAFwk::Want &want, const std::string &moduleName); + bool IsStartSpecifiedAbility() const; + void ScheduleAcceptWant(const std::string &moduleName); + void ScheduleAcceptWantDone(); + const AAFwk::Want &GetSpecifiedWant() const; + +private: + /** + * SearchTheModuleInfoNeedToUpdated, Get an uninitialized abilitystage data. + * + * @return If an uninitialized data is found return true,Otherwise return false. + */ + bool GetTheModuleInfoNeedToUpdated(const std::string bundleName, HapModuleInfo &info); + + // drive application state changes when ability state changes. + /** + * ScheduleForegroundRunning, Notify application to switch to foreground. + * + * @return + */ + void ScheduleForegroundRunning(); + + /** + * ScheduleBackgroundRunning, Notify application to switch to background. + * + * @return + */ + void ScheduleBackgroundRunning(); + + /** + * AbilityForeground, Handling the ability process when switching to the foreground. + * + * @param ability, the ability info. + * + * @return + */ + void AbilityForeground(const std::shared_ptr &ability); + + /** + * AbilityBackground, Handling the ability process when switching to the background. + * + * @param ability, the ability info. + * + * @return + */ + void AbilityBackground(const std::shared_ptr &ability); + // drive application state changes when ability state changes. + + void SendEvent(uint32_t msg, int64_t timeOut); + + void RemoveModuleRecord(const std::shared_ptr &record); + +private: + bool isKeepAliveApp_ = false; // Only resident processes can be set to true, please choose carefully + bool isNewMission_ = false; + ApplicationState curState_ = ApplicationState::APP_STATE_CREATE; // current state of this process + + std::shared_ptr appInfo_ = nullptr; // the application's info of this process + int32_t appRecordId_ = 0; + std::string appName_; + std::string processName_; // the name of this process + int64_t eventId_ = 0; + std::list> foregroundingAbilityTokens_; + std::weak_ptr appMgrServiceInner_; + sptr appDeathRecipient_ = nullptr; + std::shared_ptr priorityObject_ = nullptr; + std::shared_ptr appLifeCycleDeal_ = nullptr; + std::shared_ptr eventHandler_ = nullptr; + bool isTerminating = false; + std::string signCode_; // the sign of this hap + std::string jointUserId_; + std::map> appInfos_; + std::map>> hapModules_; + int32_t mainUid_; + std::string mainBundleName_; + bool isLauncherApp_; + bool isClonedApp_; + std::string mainAppName_; + int restartResidentProcCount_ = RESTART_RESIDENT_PROCESS_MAX_TIMES; + bool isSpecifiedAbility_ = false; + AAFwk::Want SpecifiedWant_; + std::string moduleName_; + + UserTestRecord userTestRecord_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_RUNNING_RECORD_H diff --git a/services/appmgr/include/app_spawn_client.h b/services/appmgr/include/app_spawn_client.h new file mode 100644 index 0000000000000000000000000000000000000000..862e80345572bd60bf1a0838b9bd4063119a2a53 --- /dev/null +++ b/services/appmgr/include/app_spawn_client.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_CLIENT_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_CLIENT_H + +#include "nocopyable.h" +#include "app_spawn_msg_wrapper.h" +#include "app_spawn_socket.h" + +namespace OHOS { +namespace AppExecFwk { +enum class SpawnConnectionState { STATE_NOT_CONNECT, STATE_CONNECTED, STATE_CONNECT_FAILED }; + +class AppSpawnClient { +public: + /** + * Constructor. + */ + AppSpawnClient(); + + /** + * Destructor + */ + virtual ~AppSpawnClient() = default; + + /** + * Disable copy. + */ + DISALLOW_COPY_AND_MOVE(AppSpawnClient); + + /** + * Try connect to appspawn. + */ + ErrCode OpenConnection(); + + /** + * Close the connect of appspawn. + */ + void CloseConnection(); + + /** + * AppSpawnClient core function, Start request to appspawn. + * + * @param startMsg, request message. + * @param pid, pid of app process, get from appspawn. + */ + virtual ErrCode StartProcess(const AppSpawnStartMsg &startMsg, pid_t &pid); + + /** + * Return the connect state. + */ + SpawnConnectionState QueryConnectionState() const; + + /** + * Set function, unit test also use it. + */ + void SetSocket(const std::shared_ptr socket); + +private: + /** + * AppSpawnClient core function, + * + * @param startMsg, request message. + * @param pid, pid of app process, get it from appspawn. + */ + ErrCode StartProcessImpl(const AppSpawnStartMsg &startMsg, pid_t &pid); + +private: + std::shared_ptr socket_; + SpawnConnectionState state_ = SpawnConnectionState::STATE_NOT_CONNECT; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_CLIENT_H diff --git a/services/appmgr/include/app_spawn_msg_wrapper.h b/services/appmgr/include/app_spawn_msg_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..5d923cde860d9fc333c92fc5f344c352d4cde883 --- /dev/null +++ b/services/appmgr/include/app_spawn_msg_wrapper.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_MSG_WRAPPER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_MSG_WRAPPER_H + +#include +#include +#include + +#include "nocopyable.h" +#include "client_socket.h" + +namespace OHOS { +namespace AppExecFwk { +struct AppSpawnStartMsg { + int32_t uid; + int32_t gid; + std::vector gids; + std::string procName; + std::string soPath; + uint32_t accessTokenId; + std::string apl; +}; + +using AppSpawnMsg = AppSpawn::ClientSocket::AppProperty; + +constexpr auto LEN_PID = sizeof(pid_t); + +union AppSpawnPidMsg { + pid_t pid = 0; + char pidBuf[LEN_PID]; +}; + +class AppSpawnMsgWrapper { +public: + /** + * Constructor. + */ + AppSpawnMsgWrapper() = default; + + /** + * Destructor + */ + ~AppSpawnMsgWrapper(); + + /** + * Disable copy. + */ + DISALLOW_COPY_AND_MOVE(AppSpawnMsgWrapper); + + /** + * Verify message and assign to member variable. + * + * @param startMsg, request message. + */ + bool AssembleMsg(const AppSpawnStartMsg &startMsg); + + /** + * Get function, return isValid_. + */ + bool IsValid() const + { + return isValid_; + } + + /** + * Get function, return member variable message. + */ + const void *GetMsgBuf() const + { + return reinterpret_cast(msg_); + } + + /** + * Get function, return message length. + */ + int32_t GetMsgLength() const + { + return isValid_ ? sizeof(AppSpawnMsg) : 0; + } + +private: + /** + * Verify message. + * + * @param startMsg, request message. + */ + bool VerifyMsg(const AppSpawnStartMsg &startMsg) const; + + /** + * Print message. + * + * @param startMsg, request message. + */ + void DumpMsg() const; + + /** + * Release message. + */ + void FreeMsg(); + +private: + bool isValid_ = false; + // because AppSpawnMsg's size is uncertain, so should use raw pointer. + AppSpawnMsg *msg_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_MSG_WRAPPER_H diff --git a/services/appmgr/include/app_spawn_socket.h b/services/appmgr/include/app_spawn_socket.h new file mode 100644 index 0000000000000000000000000000000000000000..ef133c455abd192461b499a405cbd054df8b95fa --- /dev/null +++ b/services/appmgr/include/app_spawn_socket.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_SOCKET_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_SOCKET_H + +#include + +#include "nocopyable.h" +#include "client_socket.h" +#include "appexecfwk_errors.h" + +namespace OHOS { +namespace AppExecFwk { +class AppSpawnSocket { +public: + /** + * Constructor. + */ + AppSpawnSocket(); + + /** + * Destructor + */ + virtual ~AppSpawnSocket(); + + /** + * Disable copy. + */ + DISALLOW_COPY_AND_MOVE(AppSpawnSocket); + + /** + * Create client socket and connect the socket. + */ + virtual ErrCode OpenAppSpawnConnection(); + + /** + * Close the client socket. + */ + virtual void CloseAppSpawnConnection(); + + /** + * Write message to the socket. + * + * @param buf, message pointer. + * @param len, message size. + */ + virtual ErrCode WriteMessage(const void *buf, const int32_t len); + + /** + * Read message from the socket. + * + * @param buf, message pointer. + * @param len, message size. + */ + virtual ErrCode ReadMessage(void *buf, const int32_t len); + + /** + * Set function, unit test also use it. + * + * @param clientSocket, client socket. + */ + void SetClientSocket(const std::shared_ptr clientSocket); + +private: + std::shared_ptr clientSocket_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_SOCKET_H \ No newline at end of file diff --git a/services/appmgr/include/cgroup_manager.h b/services/appmgr/include/cgroup_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..85d15e353b82354b7093db7fab5d3d0050ab87c5 --- /dev/null +++ b/services/appmgr/include/cgroup_manager.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_CGROUP_MANAGER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_CGROUP_MANAGER_H + +#include +#include +#include + +#include "event_handler.h" +#include "file_descriptor_listener.h" +#include "nocopyable.h" +#include "singleton.h" +#include "unique_fd.h" + +namespace OHOS { +namespace AppExecFwk { +class CgroupManager : public FileDescriptorListener, public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(CgroupManager) +public: + enum SchedPolicy { + SCHED_POLICY_DEFAULT = 0, + SCHED_POLICY_BACKGROUND, + SCHED_POLICY_FREEZED, + + SCHED_POLICY_MAX + }; + + enum LowMemoryLevel { + LOW_MEMORY_LEVEL_LOW = 0, + LOW_MEMORY_LEVEL_MEDIUM, + LOW_MEMORY_LEVEL_CRITICAL, + + LOW_MEMORY_LEVEL_MAX + }; + + enum SchedPolicyCpu { + SCHED_POLICY_CPU_DEFAULT = 0, + SCHED_POLICY_CPU_BACKGROUND, + + SCHED_POLICY_CPU_MAX + }; + + enum SchedPolicyFreezer { + SCHED_POLICY_FREEZER_FROZEN = 0, + SCHED_POLICY_FREEZER_THAWED, + + SCHED_POLICY_FREEZER_MAX + }; + + std::function LowMemoryAlert; + +public: + virtual bool Init(); + virtual bool InitCheck(); + virtual bool IsInited() const; + virtual bool SetThreadSchedPolicy(int tid, SchedPolicy schedPolicy); + virtual bool SetProcessSchedPolicy(int pid, SchedPolicy schedPolicy); + virtual void OnReadable(int32_t fd) override; + +private: + std::shared_ptr eventHandler_; + int cpusetTasksFds_[SCHED_POLICY_CPU_MAX] = {-1}; + int cpuctlTasksFds_[SCHED_POLICY_CPU_MAX] = {-1}; + int freezerTasksFds_[SCHED_POLICY_FREEZER_MAX] = {-1}; + int memoryEventControlFd_ = -1; + int memoryEventFds_[LOW_MEMORY_LEVEL_MAX] = {-1}; + int memoryPressureFds_[LOW_MEMORY_LEVEL_MAX] = {-1}; + + bool RegisterLowMemoryMonitor(const int memoryEventFds[LOW_MEMORY_LEVEL_MAX], + const int memoryPressureFds[LOW_MEMORY_LEVEL_MAX], const int memoryEventControlFd, const LowMemoryLevel level, + const std::shared_ptr &eventHandler); + bool InitCpusetTasksFds(UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_MAX]); + bool InitCpuctlTasksFds(UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_MAX]); + bool InitFreezerTasksFds(UniqueFd freezerTasksFds[SCHED_POLICY_FREEZER_MAX]); + bool InitMemoryEventControlFd(UniqueFd &memoryEventControlFd); + bool InitMemoryEventFds(UniqueFd memoryEventFds[LOW_MEMORY_LEVEL_MAX]); + bool InitMemoryPressureFds(UniqueFd memoryPressureFds[LOW_MEMORY_LEVEL_MAX]); + bool SetCpusetSubsystem(const int tid, const SchedPolicy schedPolicy); + bool SetCpuctlSubsystem(const int tid, const SchedPolicy schedPolicy); + bool SetFreezerSubsystem(const int tid, const SchedPolicyFreezer state); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_CGROUP_MANAGER_H diff --git a/services/appmgr/include/lmks/lmks_server.h b/services/appmgr/include/lmks/lmks_server.h new file mode 100644 index 0000000000000000000000000000000000000000..86e56cffd30ee8530b6c33946687e4e94e27d8fb --- /dev/null +++ b/services/appmgr/include/lmks/lmks_server.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_SERVER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_SERVER_H + +#include +#include + +#include "lmks_utils.h" + +namespace OHOS { +namespace LMKS { +constexpr uint32_t MAX_LMKS_TARGETS = 6; // max number of lmks command targets +constexpr uint32_t MAX_LMKS_TARGETS_SIZE = sizeof(int) * (MAX_LMKS_TARGETS * 2 + 1); // max packet length + +using LMKS_PACKET = int[MAX_LMKS_TARGETS_SIZE / sizeof(int)]; + +class LmksServer { +public: + LmksServer(); + virtual ~LmksServer(); + + void StartServer(); + +private: + int RegisterSocket(); + int WaitConnection(); + int RecvSocketMessage(int connectFd, void *buf, int len); + int SendSocketMessage(int connectFd, const void *buf, int len); + void ProcessMessage(int connectFd, LMKS_PACKET cmds, int len); + void CloseSocket(); + +private: + bool isStart_; + int socketFd_; + struct sockaddr_un socketAddr_; + uint32_t socketAddrLen_; + std::shared_ptr lmksUtils_; +}; +} // namespace LMKS +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_SERVER_H diff --git a/services/appmgr/include/lmks/lmks_utils.h b/services/appmgr/include/lmks/lmks_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..bda20db18af30461929a591a7c6c65aad4bd4c49 --- /dev/null +++ b/services/appmgr/include/lmks/lmks_utils.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_UTILS_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_UTILS_H + +#include +#include + +namespace OHOS { +namespace LMKS { +class LmksUtils { +public: + LmksUtils(); + virtual ~LmksUtils(); + + int RemoveProcess(pid_t pid); + +private: + std::string GetProcName(pid_t pid); + int GetProcSize(pid_t pid); + ssize_t ReadAll(int fd, char *buf, size_t maxLen); +}; +} // namespace LMKS +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_UTILS_H diff --git a/services/appmgr/include/lmks_client.h b/services/appmgr/include/lmks_client.h new file mode 100644 index 0000000000000000000000000000000000000000..63b8934e3c74d1a0cf02487ce3246f50a8e2bf21 --- /dev/null +++ b/services/appmgr/include/lmks_client.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_CLIENT_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_CLIENT_H + +#include +#include +#include +#include +#include + +#include "ability_running_record.h" +#include "app_running_record.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +union LmksClientMsg { + int32_t result = -1; + int8_t resultBuf[sizeof(int32_t)]; +}; + +class LmksClient : public NoCopyable { +public: + using Targets = std::vector>; + +public: + LmksClient(); + virtual ~LmksClient(); + virtual int32_t Open(); + virtual void Close(); + virtual bool IsOpen() const; + virtual int32_t Target(const Targets &targets); + virtual int32_t ProcPrio(pid_t pid, uid_t uid, int oomAdj); + virtual int32_t ProcRemove(pid_t pid); + virtual bool ProcPurge(); + static bool CheckOomAdj(int v); + +private: + bool Write(const void *buf, size_t len); + bool Read(void *buf, size_t len); + +private: + int socket_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_LMKS_CLIENT_H diff --git a/services/appmgr/include/module_running_record.h b/services/appmgr/include/module_running_record.h new file mode 100644 index 0000000000000000000000000000000000000000..17b8a51ba0bb34c61d96b4142e09701f43f3e256 --- /dev/null +++ b/services/appmgr/include/module_running_record.h @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_MODULE_RUNNING_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_MODULE_RUNNING_RECORD_H + +#include +#include +#include +#include +#include "iremote_object.h" + +#include "ability_info.h" +#include "application_info.h" +#include "ability_running_record.h" +#include "app_mgr_constants.h" +#include "app_lifecycle_deal.h" +#include "app_mgr_service_event_handler.h" + +namespace OHOS { +namespace AppExecFwk { +enum class ModuleRecordState { + UNKNOWN_STATE, + INITIALIZED_STATE, + RUNNING_STATE, +}; + +class AppMgrServiceInner; +class ModuleRunningRecord { +public: + ModuleRunningRecord( + const std::shared_ptr &info, const std::shared_ptr &eventHandler); + virtual ~ModuleRunningRecord(); + + /** + * @brief Obtains module moduleName. + * + * @return Returns module moduleName. + */ + const std::string &GetModuleName() const; + + /** + * @param name, the module mainability name. + * + * @return + */ + void GetMainAbilityName(const std::string &name); + + void Init(const HapModuleInfo &info); + + const HapModuleInfo GetModuleInfo(); + + /** + * GetAbilityRunningRecordByToken, Obtaining the ability record through token. + * + * @param token, the unique identification to the ability. + * + * @return + */ + std::shared_ptr GetAbilityRunningRecordByToken(const sptr &token) const; + + // Add new ability instance to current running abilities list managed by this process + /** + * AddAbility, Add new ability instance to current running abilities list managed by this process. + * + * @param token, the unique identification to the ability. + * @param abilityInfo, the ability info. + * + * @return the ability record. + */ + std::shared_ptr AddAbility( + const sptr &token, const std::shared_ptr &abilityInfo); + + bool IsLastAbilityRecord(const sptr &token); + + // Get abilities_ for this process + /** + * @brief Obtains the abilitys info for the application record. + * + * @return Returns the abilitys info for the application record. + */ + const std::map, std::shared_ptr> &GetAbilities() const; + + std::shared_ptr GetAbilityByTerminateLists(const sptr &token) const; + + // Clear(remove) the specified ability record from the list + + /** + * ClearAbility, Clear ability record by record info. + * + * @param record, the ability record. + * + * @return + */ + void ClearAbility(const std::shared_ptr &record); + // It can only used in SINGLETON mode. + /** + * GetAbilityRunningRecord, Get ability record by the ability Name. + * + * @param abilityName, the ability name. + * + * @return the ability record. + */ + std::shared_ptr GetAbilityRunningRecord(const std::string &abilityName) const; + + std::shared_ptr GetAbilityRunningRecord(const int64_t eventId) const; + + /** + * LaunchAbility, Notify application to launch ability. + * + * @param ability, the ability record. + * + * @return + */ + void LaunchAbility(const std::shared_ptr &ability); + + /** + * LaunchPendingAbilities, Launch Pending Abilities. + * + * @return + */ + void LaunchPendingAbilities(); + + /** + * TerminateAbility, terminate the token ability. + * + * @param token, he unique identification to terminate the ability. + * + * @return + */ + void TerminateAbility(const sptr &token, const bool isForce); + + /** + * AbilityTerminated, terminate the ability. + * + * @param token, the unique identification to terminated the ability. + * + * @return + */ + void AbilityTerminated(const sptr &token); + + /** + * @brief Setting application service internal handler instance. + * + * @param serviceInner, application service internal handler instance. + */ + void SetAppMgrServiceInner(const std::weak_ptr &inner); + + // drive application state changes when ability state changes. + /** + * OnAbilityStateChanged, Call ability state change. + * + * @param ability, the ability info. + * @param state, the ability state. + * + * @return + */ + void OnAbilityStateChanged(const std::shared_ptr &ability, const AbilityState state); + + ModuleRecordState GetModuleRecordState(); + + void SetModuleRecordState(const ModuleRecordState &state); + + void GetHapModuleInfo(HapModuleInfo &info); + + void SetApplicationClient(std::shared_ptr &appLifeCycleDeal); + + const std::shared_ptr GetAppInfo(); + +private: + /** + * OptimizerAbilityStateChanged, Optimizer processing ability state changes. + * + * @param ability, the ability info. + * @param state, the ability state. + * + * @return + */ + void OptimizerAbilityStateChanged(const std::shared_ptr &ability, const AbilityState state); + + void SendEvent(uint32_t msg, int64_t timeOut, const std::shared_ptr &abilityRecord); + + ModuleRecordState GetState() const; + +private: + std::map, std::shared_ptr> abilities_; + std::map, std::shared_ptr> terminateAbilitys_; + std::weak_ptr appMgrServiceInner_; + std::shared_ptr appLifeCycleDeal_; + std::shared_ptr appInfo_; // the application's info + std::shared_ptr eventHandler_; + HapModuleInfo owenInfo_; + ModuleRecordState owenState_ = ModuleRecordState::UNKNOWN_STATE; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_MODULE_RUNNING_RECORD_H diff --git a/services/appmgr/include/process_optimizer.h b/services/appmgr/include/process_optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..10b4028bcff4cc9ac3228b8d814f66f98fcc183d --- /dev/null +++ b/services/appmgr/include/process_optimizer.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_PROCESS_OPTIMIZER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_PROCESS_OPTIMIZER_H + +#include +#include +#include +#include +#include + +#include "ability_running_record.h" +#include "app_running_record.h" +#include "cgroup_manager.h" +#include "lmks_client.h" +#include "event_handler.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +class ProcessOptimizer : public NoCopyable { +public: + using EventHandlerPtr = std::shared_ptr; + using AppPtr = std::shared_ptr; + using AbilityPtr = std::shared_ptr; + using CgroupManagerPtr = std::shared_ptr; + using LmksClientPtr = std::shared_ptr; + + static constexpr int APP_SUSPEND_TIMEOUT_DEFAULT = 5000; // in milliseconds + static constexpr int APP_SUSPEND_TIMEOUT_MAX = 30 * 1000; // in milliseconds + +public: + ProcessOptimizer(const LmksClientPtr &lmksClient = nullptr, int suspendTimeout = APP_SUSPEND_TIMEOUT_DEFAULT); + + virtual ~ProcessOptimizer(); + +public: + // callbacks + std::function AppSuspended; + std::function AppResumed; + std::function AppLowMemoryAlert; + std::function GetAbilityOwnerApp; + +public: + virtual bool Init(); + virtual void OnAppAdded(const AppPtr &app); + virtual void OnAppRemoved(const AppPtr &app); + virtual void OnAppStateChanged(const AppPtr &app, const ApplicationState oldState); + virtual void OnAbilityStarted(const AbilityPtr &ability); + virtual void OnAbilityConnected(const AbilityPtr &ability, const AbilityPtr &targetAbility); + virtual void OnAbilityDisconnected(const AbilityPtr &ability, const AbilityPtr &targetAbility); + virtual void OnAbilityStateChanged(const AbilityPtr &ability, const AbilityState oldState); + virtual void OnAbilityVisibleChanged(const AbilityPtr &ability); + virtual void OnAbilityPerceptibleChanged(const AbilityPtr &ability); + virtual void OnAbilityRemoved(const AbilityPtr &ability); + virtual void SetAppFreezingTime(int time); + virtual void GetAppFreezingTime(int &time); + +protected: + bool SetAppOomAdj(const AppPtr &app, int oomAdj); + bool SetAppSchedPolicy(const AppPtr &app, const CgroupManager::SchedPolicy schedPolicy); + virtual void OnLowMemoryAlert(const CgroupManager::LowMemoryLevel level); + +private: + bool UpdateAppOomAdj(const AppPtr &app); + bool GetAppOomAdj(const AppPtr &app,ApplicationState state,int &oomAdj,int &oomAdjMax); + bool UpdateAppSchedPolicy(const AppPtr &app); + void StartAppSuspendTimer(const AppPtr &app); + void StopAppSuspendTimer(const AppPtr &app); + void SuspendApp(const AppPtr &app); + std::string GetAppSuspendTimerName(const AppPtr &app); + +private: + using AppLru = std::list; + using SuspendTimers = std::set; + + LmksClientPtr lmksClient_; + AppLru appLru_; + EventHandlerPtr eventHandler_; + SuspendTimers suspendTimers_; + int suspendTimeout_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_PROCESS_OPTIMIZER_H diff --git a/services/appmgr/include/process_optimizer_uba.h b/services/appmgr/include/process_optimizer_uba.h new file mode 100644 index 0000000000000000000000000000000000000000..89c0440afd1ef1ec8e6eeaa633fa76c2e438cbca --- /dev/null +++ b/services/appmgr/include/process_optimizer_uba.h @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_PROCESS_OPTIMIZER_UBA_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_PROCESS_OPTIMIZER_UBA_H + +#include +#include +#include +#include +#include + +#include "process_optimizer.h" + +namespace OHOS { +namespace AppExecFwk { +// UBA short for User Behavior Analysis +using UbaService = int; +using UbaServicePtr = std::shared_ptr; + +class ProcessOptimizerUBA : public ProcessOptimizer { +public: + using AbilityToken = sptr; + +public: + ProcessOptimizerUBA(const UbaServicePtr &ubaService, const LmksClientPtr &lmksClient = nullptr, + int suspendTimeout = APP_SUSPEND_TIMEOUT_DEFAULT); + + virtual ~ProcessOptimizerUBA(); + +public: + // callbacks + std::function GetAbilityByToken; + +public: + void OnAppAdded(const AppPtr &app) override; + void OnAppRemoved(const AppPtr &app) override; + void OnAppStateChanged(const AppPtr &app, const ApplicationState oldState) override; + void OnAbilityStarted(const AbilityPtr &ability) override; + void OnAbilityConnected(const AbilityPtr &ability, const AbilityPtr &targetAbility) override; + void OnAbilityDisconnected(const AbilityPtr &ability, const AbilityPtr &targetAbility) override; + void OnAbilityStateChanged(const AbilityPtr &ability, const AbilityState oldState) override; + void OnAbilityVisibleChanged(const AbilityPtr &ability) override; + void OnAbilityPerceptibleChanged(const AbilityPtr &ability) override; + void OnAbilityRemoved(const AbilityPtr &ability) override; + void SetAppFreezingTime(int time) override; + void GetAppFreezingTime(int &time) override; + +protected: + void OnLowMemoryAlert(const CgroupManager::LowMemoryLevel level) override; + +private: + using Clock = std::chrono::system_clock; + using TimePoint = Clock::time_point; + + class BaseAbilityAction { + public: + BaseAbilityAction(const AbilityPtr &ability); + ~BaseAbilityAction() = default; + + TimePoint GetTime() const; + std::string GetTimeString() const; + const std::string &GetName() const; + + private: + TimePoint time_; + std::string name_; + }; + + class StartAbilityAction : public BaseAbilityAction { + public: + StartAbilityAction(const AbilityPtr &ability, const AbilityPtr &preAbility); + ~StartAbilityAction() = default; + + const std::string &GetPreName() const; + + private: + std::string preName_; + }; + + class ConnectAbilityAction : public BaseAbilityAction { + public: + ConnectAbilityAction(const AbilityPtr &ability, const AbilityPtr &targetAbility); + ~ConnectAbilityAction() = default; + + const std::string &GetTargetName() const; + + private: + std::string targetName_; + }; + + class DisconnectAbilityAction : public BaseAbilityAction { + public: + DisconnectAbilityAction(const AbilityPtr &ability, const AbilityPtr &targetAbility); + ~DisconnectAbilityAction() = default; + + const std::string &GetTargetName() const; + + private: + std::string targetName_; + }; + + class ChangeAbilityStateAction : public BaseAbilityAction { + public: + ChangeAbilityStateAction(const AbilityPtr &ability, const AbilityState oldState); + ~ChangeAbilityStateAction() = default; + + AbilityState GetOldState() const; + AbilityState GetNewState() const; + + private: + AbilityState oldState_; + AbilityState newState_; + }; + + class ChangeAbilityVisible : public BaseAbilityAction { + public: + ChangeAbilityVisible(const AbilityPtr &ability); + ~ChangeAbilityVisible() = default; + }; + + class ChangeAbilityPerceptible : public BaseAbilityAction { + public: + ChangeAbilityPerceptible(const AbilityPtr &ability); + ~ChangeAbilityPerceptible() = default; + }; + + class RemoveAbilityAction : public BaseAbilityAction { + public: + RemoveAbilityAction(const AbilityPtr &ability); + ~RemoveAbilityAction() = default; + }; + + using AbilityAction = + std::variant; + + template + void RecordAbilityAction(ARGS... args) + { + abilityActionCache_[abilityActionCount_++].emplace(args...); + if (abilityActionCount_ >= ABILITY_ACTION_CACHE_SIZE) { + CommitAbilityActions(); + } + } + + void CommitAbilityActions(); + void CommitStartAbilityAction(const StartAbilityAction& action, size_t index); + void CommitConnectAbilityAction(const ConnectAbilityAction& action, size_t index); + void CommitDisconnectAbilityAction(const DisconnectAbilityAction& action, size_t index); + void CommitChangedAbilityStateAction(const ChangeAbilityStateAction& action, size_t index); + void CommitRemoveAbilityAction(const RemoveAbilityAction& action, size_t index); + UbaServicePtr GetUbaService(); + +private: + UbaServicePtr ubaService_; + static constexpr size_t ABILITY_ACTION_CACHE_SIZE = 100; + AbilityAction abilityActionCache_[ABILITY_ACTION_CACHE_SIZE]; + size_t abilityActionCount_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_PROCESS_OPTIMIZER_UBA_H diff --git a/services/appmgr/include/record_query_result.h b/services/appmgr/include/record_query_result.h new file mode 100644 index 0000000000000000000000000000000000000000..539d7e50e956b5e0ce0ebb6f929dfbf3db0a21a5 --- /dev/null +++ b/services/appmgr/include/record_query_result.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_RECORF_QUERY_RESULT_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_RECORF_QUERY_RESULT_H + +namespace OHOS { +namespace AppExecFwk { +struct RecordQueryResult { + void Reset() + { + appExists = false; + abilityExists = false; + error = ERR_OK; + appRecordId = 0; + } + // if app not exists, create and set |appRecordId| + int32_t appRecordId = 0; + // if ability not exists, create and set |abilityRecordId| + bool appExists = false; + bool abilityExists = false; + ErrCode error = ERR_OK; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_RECORF_QUERY_RESULT_H \ No newline at end of file diff --git a/services/appmgr/include/remote_client_manager.h b/services/appmgr/include/remote_client_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..35656ea55639e172bd943573e30a873e93afac95 --- /dev/null +++ b/services/appmgr/include/remote_client_manager.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_REMOTE_CLIENT_MANAGER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_REMOTE_CLIENT_MANAGER_H + +#include "iremote_object.h" +#include "refbase.h" + +#include "app_spawn_client.h" +#include "bundlemgr/bundle_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class RemoteClientManager { +public: + RemoteClientManager(); + virtual ~RemoteClientManager(); + + /** + * GetSpawnClient, Get spawn client. + * + * @return the spawn client instance. + */ + std::shared_ptr GetSpawnClient(); + + /** + * @brief Setting spawn client instance. + * + * @param appSpawnClient, the spawn client instance. + */ + void SetSpawnClient(const std::shared_ptr &appSpawnClient); + + /** + * GetBundleManager, Get bundle management services. + * + * @return the bundle management services instance. + */ + sptr GetBundleManager(); + + /** + * @brief Setting bundle management instance. + * + * @param appSpawnClient, the bundle management instance. + */ + void SetBundleManager(sptr bundleManager); + +private: + std::shared_ptr appSpawnClient_; + sptr bundleManager_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_REMOTE_CLIENT_MANAGER_H \ No newline at end of file diff --git a/services/appmgr/include/start_via_asan.h b/services/appmgr/include/start_via_asan.h new file mode 100644 index 0000000000000000000000000000000000000000..599033add477cebd6a82837c731e9399a7fc6f79 --- /dev/null +++ b/services/appmgr/include/start_via_asan.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_START_VIA_ASAN_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_START_VIA_ASAN_H + +#include + +#include "singleton.h" + +#include "app_spawn_client.h" + +namespace OHOS { +namespace AppExecFwk { +class StartViaAsan { + DECLARE_DELAYED_SINGLETON(StartViaAsan); + +public: + bool IsAsanVersion(const std::string &appName) const; + void GetAsanStartMsg(AppSpawnStartMsg &startMsg) const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_START_VIA_ASAN_H \ No newline at end of file diff --git a/services/appmgr/lmks.cfg b/services/appmgr/lmks.cfg new file mode 100755 index 0000000000000000000000000000000000000000..e02a3865092b6c72b49216a8a0a5f4b22bc261e6 --- /dev/null +++ b/services/appmgr/lmks.cfg @@ -0,0 +1,17 @@ +{ + "jobs" : [{ + "name" : "late-fs", + "cmds" : [ + "start lmks" + ] + } + ], + "services" : [{ + "name" : "lmks", + "path" : ["/system/bin/lmks"], + "importance" : -20, + "uid" : "root", + "gid" : ["root"] + } + ] +} diff --git a/services/appmgr/lmks.rc b/services/appmgr/lmks.rc new file mode 100755 index 0000000000000000000000000000000000000000..bc89f051ab8fc6919a2b903cd342887a2539a982 --- /dev/null +++ b/services/appmgr/lmks.rc @@ -0,0 +1,23 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. + +on late-fs +# wait for selinux_policy_standard participate in compile +# start lmks + +service lmks /system/bin/lmks + class lmks + priority -20 + user root + group root + seclabel u:r:lmks:s0 diff --git a/services/appmgr/src/ability_running_record.cpp b/services/appmgr/src/ability_running_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c218661ec38c399f09080472457c835c024f055 --- /dev/null +++ b/services/appmgr/src/ability_running_record.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_running_record.h" + +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +AbilityRunningRecord::AbilityRunningRecord(const std::shared_ptr &info, const sptr &token) + : info_(info), token_(token) +{} + +AbilityRunningRecord::~AbilityRunningRecord() +{} + +const std::string &AbilityRunningRecord::GetName() const +{ + return info_->name; +} + +const std::shared_ptr &AbilityRunningRecord::GetAbilityInfo() const +{ + return info_; +} + +const sptr &AbilityRunningRecord::GetToken() const +{ + return token_; +} + +void AbilityRunningRecord::SetState(const AbilityState state) +{ + state_ = state; +} + +AbilityState AbilityRunningRecord::GetState() const +{ + return state_; +} + +bool AbilityRunningRecord::IsSameState(const AbilityState state) const +{ + return state_ == state; +} + +int32_t AbilityRunningRecord::GetLastLaunchTime() const +{ + return lastLaunchTime_; +} + +const sptr AbilityRunningRecord::GetPreToken() const +{ + return preToken_; +} + +void AbilityRunningRecord::SetPreToken(const sptr &preToken) +{ + preToken_ = preToken; +} + +void AbilityRunningRecord::SetVisibility(const int32_t visibility) +{ + visibility_ = visibility; +} + +int32_t AbilityRunningRecord::GetVisibility() const +{ + return visibility_; +} + +void AbilityRunningRecord::SetPerceptibility(const int32_t perceptibility) +{ + perceptibility_ = perceptibility; +} + +int32_t AbilityRunningRecord::GetPerceptibility() const +{ + return perceptibility_; +} + +void AbilityRunningRecord::SetConnectionState(const int32_t connectionState) +{ + connectionState_ = connectionState; +} + +int32_t AbilityRunningRecord::GetConnectionState() const +{ + return connectionState_; +} + +void AbilityRunningRecord::SetEventId(const int64_t eventId) +{ + eventId_ = eventId; +} + +int64_t AbilityRunningRecord::GetEventId() const +{ + return eventId_; +} + +void AbilityRunningRecord::SetTerminating() +{ + isTerminating_ = true; +} + +bool AbilityRunningRecord::IsTerminating() const +{ + return isTerminating_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90019d2fbe1b8e564b756556fa1f87fad52dc5e1 --- /dev/null +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_mgr_scheduler.h" +#include + +#include "datetime_ex.h" +#include "ipc_skeleton.h" +#include "system_ability_definition.h" + +#include "app_death_recipient.h" +#include "app_log_wrapper.h" +#include "app_mgr_constants.h" +#include "perf_profile.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string TASK_LOAD_ABILITY = "LoadAbilityTask"; +const std::string TASK_TERMINATE_ABILITY = "TerminateAbilityTask"; +const std::string TASK_UPDATE_ABILITY_STATE = "UpdateAbilityStateTask"; +const std::string TASK_UPDATE_EXTENSION_STATE = "UpdateExtensionStateTask"; +const std::string TASK_REGISTER_APP_STATE_CALLBACK = "RegisterAppStateCallbackTask"; +const std::string TASK_STOP_ALL_PROCESS = "StopAllProcessTask"; +const std::string TASK_ABILITY_BEHAVIOR_ANALYSIS = "AbilityBehaviorAnalysisTask"; +const std::string TASK_KILL_PROCESS_BY_ABILITYTOKEN = "KillProcessByAbilityTokenTask"; +const std::string TASK_KILL_PROCESSES_BY_USERID = "KillProcessesByUserIdTask"; +const std::string TASK_KILL_APPLICATION = "KillApplicationTask"; +}; // namespace + +AmsMgrScheduler::AmsMgrScheduler( + const std::shared_ptr &mgrServiceInner_, const std::shared_ptr &handler_) + : amsMgrServiceInner_(mgrServiceInner_), amsHandler_(handler_) +{} + +AmsMgrScheduler::~AmsMgrScheduler() +{ + APP_LOGI("AmsMgrScheduler instance destroyed"); +} + +void AmsMgrScheduler::LoadAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) +{ + if (!abilityInfo || !appInfo) { + APP_LOGE("param error"); + return; + } + + if (!IsReady()) { + APP_LOGE("AmsMgrScheduler not Ready"); + return; + } + PerfProfile::GetInstance().SetAbilityLoadStartTime(GetTickCount()); + std::function loadAbilityFunc = + std::bind(&AppMgrServiceInner::LoadAbility, amsMgrServiceInner_, token, preToken, abilityInfo, appInfo); + + amsHandler_->PostTask(loadAbilityFunc, TASK_LOAD_ABILITY); +} + +void AmsMgrScheduler::UpdateAbilityState(const sptr &token, const AbilityState state) +{ + if (!IsReady()) { + return; + } + std::function updateAbilityStateFunc = + std::bind(&AppMgrServiceInner::UpdateAbilityState, amsMgrServiceInner_, token, state); + amsHandler_->PostTask(updateAbilityStateFunc, TASK_UPDATE_ABILITY_STATE); +} + +void AmsMgrScheduler::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + if (!IsReady()) { + return; + } + std::function updateExtensionStateFunc = + std::bind(&AppMgrServiceInner::UpdateExtensionState, amsMgrServiceInner_, token, state); + amsHandler_->PostTask(updateExtensionStateFunc, TASK_UPDATE_EXTENSION_STATE); +} + +void AmsMgrScheduler::TerminateAbility(const sptr &token) +{ + if (!IsReady()) { + return; + } + std::function terminateAbilityFunc = + std::bind(&AppMgrServiceInner::TerminateAbility, amsMgrServiceInner_, token); + amsHandler_->PostTask(terminateAbilityFunc, TASK_TERMINATE_ABILITY); +} + +void AmsMgrScheduler::RegisterAppStateCallback(const sptr &callback) +{ + if (!IsReady()) { + return; + } + std::function registerAppStateCallbackFunc = + std::bind(&AppMgrServiceInner::RegisterAppStateCallback, amsMgrServiceInner_, callback); + amsHandler_->PostTask(registerAppStateCallbackFunc, TASK_REGISTER_APP_STATE_CALLBACK); +} + +void AmsMgrScheduler::Reset() +{ + if (!IsReady()) { + return; + } + std::function resetFunc = std::bind(&AppMgrServiceInner::StopAllProcess, amsMgrServiceInner_); + amsHandler_->PostTask(resetFunc, TASK_STOP_ALL_PROCESS); +} + +void AmsMgrScheduler::AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) +{ + if (!IsReady()) { + return; + } + std::function abilityBehaviorAnalysisFunc = std::bind(&AppMgrServiceInner::AbilityBehaviorAnalysis, + amsMgrServiceInner_, + token, + preToken, + visibility, + perceptibility, + connectionState); + amsHandler_->PostTask(abilityBehaviorAnalysisFunc, TASK_ABILITY_BEHAVIOR_ANALYSIS); +} + +void AmsMgrScheduler::KillProcessByAbilityToken(const sptr &token) +{ + if (!IsReady()) { + return; + } + std::function killProcessByAbilityTokenFunc = + std::bind(&AppMgrServiceInner::KillProcessByAbilityToken, amsMgrServiceInner_, token); + amsHandler_->PostTask(killProcessByAbilityTokenFunc, TASK_KILL_PROCESS_BY_ABILITYTOKEN); +} + +void AmsMgrScheduler::KillProcessesByUserId(int32_t userId) +{ + if (!IsReady()) { + return; + } + std::function killProcessesByUserIdFunc = + std::bind(&AppMgrServiceInner::KillProcessesByUserId, amsMgrServiceInner_, userId); + amsHandler_->PostTask(killProcessesByUserIdFunc, TASK_KILL_PROCESSES_BY_USERID); +} + +int32_t AmsMgrScheduler::KillProcessWithAccount(const std::string &bundleName, const int accountId) +{ + APP_LOGI("enter"); + APP_LOGI("bundleName = %{public}s, accountId = %{public}d", bundleName.c_str(), accountId); + + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + + APP_LOGI("end"); + + return amsMgrServiceInner_->KillApplicationByUserId(bundleName, accountId); +} + +void AmsMgrScheduler::AbilityAttachTimeOut(const sptr &token) +{ + APP_LOGI("AmsMgrScheduler AttachTimeOut begin"); + if (!IsReady()) { + return; + } + auto task = [=]() { amsMgrServiceInner_->HandleAbilityAttachTimeOut(token); }; + amsHandler_->PostTask(task); +} + +void AmsMgrScheduler::PrepareTerminate(const sptr &token) +{ + APP_LOGI("AmsMgrScheduler PrepareTerminate begin"); + if (!IsReady()) { + return; + } + auto task = [=]() { amsMgrServiceInner_->PrepareTerminate(token); }; + amsHandler_->PostTask(task); +} + +int32_t AmsMgrScheduler::KillApplication(const std::string &bundleName) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return amsMgrServiceInner_->KillApplication(bundleName); +} + +int32_t AmsMgrScheduler::KillApplicationByUid(const std::string &bundleName, const int uid) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return amsMgrServiceInner_->KillApplicationByUid(bundleName, uid); +} + +bool AmsMgrScheduler::IsReady() const +{ + if (!amsMgrServiceInner_) { + APP_LOGE("amsMgrServiceInner_ is null"); + return false; + } + if (!amsHandler_) { + APP_LOGE("amsHandler_ is null"); + return false; + } + return true; +} + +int AmsMgrScheduler::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return amsMgrServiceInner_->CompelVerifyPermission(permission, pid, uid, message); +} + +void AmsMgrScheduler::GetRunningProcessInfoByToken( + const sptr &token, AppExecFwk::RunningProcessInfo &info) +{ + if (!IsReady()) { + return; + } + + amsMgrServiceInner_->GetRunningProcessInfoByToken(token, info); +} + +void AmsMgrScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +{ + if (!IsReady()) { + return; + } + + auto task = [=]() { amsMgrServiceInner_->StartSpecifiedAbility(want, abilityInfo); }; + amsHandler_->PostTask(task); +} + +void AmsMgrScheduler::RegisterStartSpecifiedAbilityResponse(const sptr &response) +{ + if (!IsReady()) { + return; + } + auto task = [=]() { amsMgrServiceInner_->RegisterStartSpecifiedAbilityResponse(response); }; + amsHandler_->PostTask(task); +} + +void AmsMgrScheduler::UpdateConfiguration(const Configuration &config) +{ + APP_LOGI("AmsMgrScheduler UpdateConfiguration begin"); + if (!IsReady()) { + return; + } + auto task = [=]() { amsMgrServiceInner_->UpdateConfiguration(config); }; + amsHandler_->PostTask(task); + APP_LOGI("AmsMgrScheduler UpdateConfiguration end"); +} + +int AmsMgrScheduler::GetConfiguration(Configuration& config) +{ + APP_LOGI("AmsMgrScheduler GetConfiguration begin"); + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + if (!amsMgrServiceInner_->GetConfiguration()) { + return ERR_INVALID_OPERATION; + } + config = *(amsMgrServiceInner_->GetConfiguration()); + APP_LOGI("AmsMgrScheduler GetConfiguration end"); + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_death_recipient.cpp b/services/appmgr/src/app_death_recipient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c841c0310a1b08c55678815b701ebe69a1185d9 --- /dev/null +++ b/services/appmgr/src/app_death_recipient.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_death_recipient.h" + +#include "app_log_wrapper.h" +#include "app_mgr_service_inner.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string TASK_ON_REMOTE_DIED = "OnRemoteDiedTask"; +} + +void AppDeathRecipient::OnRemoteDied(const wptr &remote) +{ + if (remote == nullptr) { + APP_LOGE("remote is null"); + return; + } + + auto handler = handler_.lock(); + if (!handler) { + APP_LOGE("handler is null"); + return; + } + auto serviceInner = appMgrServiceInner_.lock(); + if (!serviceInner) { + APP_LOGE("serviceInner is null"); + return; + } + + std::function onRemoteDiedFunc = std::bind(&AppMgrServiceInner::OnRemoteDied, serviceInner, remote); + handler->PostTask(onRemoteDiedFunc, TASK_ON_REMOTE_DIED); +} + +void AppDeathRecipient::SetEventHandler(const std::shared_ptr &handler) +{ + handler_ = handler; +} + +void AppDeathRecipient::SetAppMgrServiceInner(const std::shared_ptr &serviceInner) +{ + appMgrServiceInner_ = serviceInner; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_lifecycle_deal.cpp b/services/appmgr/src/app_lifecycle_deal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fb997a3985b91863a1df33db1a58e000e089ae5 --- /dev/null +++ b/services/appmgr/src/app_lifecycle_deal.cpp @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_lifecycle_deal.h" +#include "app_log_wrapper.h" +#include "bytrace.h" + +namespace OHOS { +namespace AppExecFwk { +AppLifeCycleDeal::AppLifeCycleDeal() +{} + +AppLifeCycleDeal::~AppLifeCycleDeal() +{} + +void AppLifeCycleDeal::LaunchApplication(const AppLaunchData &launchData_, const Configuration &config) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("AppLifeCycleDeal ScheduleLaunchApplication"); + if (appThread_) { + appThread_->ScheduleLaunchApplication(launchData_, config); + } +} + +void AppLifeCycleDeal::AddAbilityStage(const HapModuleInfo &abilityStage) +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleAbilityStage(abilityStage); +} + +void AppLifeCycleDeal::LaunchAbility(const std::shared_ptr &ability) +{ + if (appThread_) { + appThread_->ScheduleLaunchAbility(*(ability->GetAbilityInfo()), ability->GetToken()); + } +} + +void AppLifeCycleDeal::ScheduleTerminate() +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleTerminateApplication(); +} + +void AppLifeCycleDeal::ScheduleForegroundRunning() +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleForegroundApplication(); +} + +void AppLifeCycleDeal::ScheduleBackgroundRunning() +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleBackgroundApplication(); +} + +void AppLifeCycleDeal::ScheduleTrimMemory(int32_t timeLevel) +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleShrinkMemory(timeLevel); +} + +void AppLifeCycleDeal::LowMemoryWarning() +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleLowMemory(); +} + +void AppLifeCycleDeal::ScheduleCleanAbility(const sptr &token) +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + appThread_->ScheduleCleanAbility(token); +} + +void AppLifeCycleDeal::ScheduleProcessSecurityExit() +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleProcessSecurityExit(); +} + +void AppLifeCycleDeal::SetApplicationClient(const sptr &thread) +{ + appThread_ = thread; +} + +sptr AppLifeCycleDeal::GetApplicationClient() const +{ + return appThread_; +} + +void AppLifeCycleDeal::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) +{ + if (!appThread_) { + APP_LOGE("appThread_ is nullptr"); + return; + } + + appThread_->ScheduleAcceptWant(want, moduleName); +} + +void AppLifeCycleDeal::UpdateConfiguration(const Configuration &config) +{ + APP_LOGI("call %{public}s", __func__); + if (!appThread_) { + APP_LOGI("appThread_ is null"); + return; + } + appThread_->ScheduleConfigurationUpdated(config); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp new file mode 100755 index 0000000000000000000000000000000000000000..32ded035fb51fa6cfa434535044cfd920c0be95a --- /dev/null +++ b/services/appmgr/src/app_mgr_service.cpp @@ -0,0 +1,403 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_service.h" + +#include +#include + +#include "datetime_ex.h" +#include "ipc_skeleton.h" +#include "system_ability_definition.h" + +#include "app_death_recipient.h" +#include "app_log_wrapper.h" +#include "app_mgr_constants.h" +#include "perf_profile.h" + +#include "system_environment_information.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int EXPERIENCE_MEM_THRESHOLD = 20; +static const float PERCENTAGE = 100.0; +const std::string TASK_ATTACH_APPLICATION = "AttachApplicationTask"; +const std::string TASK_APPLICATION_FOREGROUNDED = "ApplicationForegroundedTask"; +const std::string TASK_APPLICATION_BACKGROUNDED = "ApplicationBackgroundedTask"; +const std::string TASK_APPLICATION_TERMINATED = "ApplicationTerminatedTask"; +const std::string TASK_ABILITY_CLEANED = "AbilityCleanedTask"; +const std::string TASK_ADD_APP_DEATH_RECIPIENT = "AddAppRecipientTask"; +const std::string TASK_CLEAR_UP_APPLICATION_DATA = "ClearUpApplicationDataTask"; +const std::string TASK_STARTUP_RESIDENT_PROCESS = "StartupResidentProcess"; +const std::string TASK_ADD_ABILITY_STAGE_DONE = "AddAbilityStageDone"; +const std::string TASK_START_USER_TEST_PROCESS = "StartUserTestProcess"; +} // namespace + +REGISTER_SYSTEM_ABILITY_BY_ID(AppMgrService, APP_MGR_SERVICE_ID, true); + +AppMgrService::AppMgrService() +{ + appMgrServiceInner_ = std::make_shared(); + APP_LOGI("instance created with no para"); + PerfProfile::GetInstance().SetAmsLoadStartTime(GetTickCount()); +} + +AppMgrService::AppMgrService(const int32_t serviceId, bool runOnCreate) : SystemAbility(serviceId, runOnCreate) +{ + appMgrServiceInner_ = std::make_shared(); + APP_LOGI("instance created"); + PerfProfile::GetInstance().SetAmsLoadStartTime(GetTickCount()); +} + +AppMgrService::~AppMgrService() +{ + APP_LOGI("instance destroyed"); +} + +void AppMgrService::OnStart() +{ + APP_LOGI("ready to start service"); + if (appMgrServiceState_.serviceRunningState == ServiceRunningState::STATE_RUNNING) { + APP_LOGW("failed to start service since it's already running"); + return; + } + + ErrCode errCode = Init(); + if (FAILED(errCode)) { + APP_LOGE("init failed, errCode: %{public}08x", errCode); + return; + } + appMgrServiceState_.serviceRunningState = ServiceRunningState::STATE_RUNNING; + APP_LOGI("start service success"); + PerfProfile::GetInstance().SetAmsLoadEndTime(GetTickCount()); + PerfProfile::GetInstance().Dump(); +} + +void AppMgrService::OnStop() +{ + APP_LOGI("ready to stop service"); + appMgrServiceState_.serviceRunningState = ServiceRunningState::STATE_NOT_START; + handler_.reset(); + runner_.reset(); + if (appMgrServiceInner_) { + appMgrServiceInner_->OnStop(); + } + APP_LOGI("stop service success"); +} + +void AppMgrService::SetInnerService(const std::shared_ptr &innerService) +{ + appMgrServiceInner_ = innerService; +} + +AppMgrServiceState AppMgrService::QueryServiceState() +{ + if (appMgrServiceInner_) { + appMgrServiceState_.connectionState = appMgrServiceInner_->QueryAppSpawnConnectionState(); + } + return appMgrServiceState_; +} + +ErrCode AppMgrService::Init() +{ + APP_LOGI("ready to init"); + // start main thread message loop. + runner_ = EventRunner::Create(Constants::APP_MGR_SERVICE_NAME); + if (!runner_) { + APP_LOGE("init failed due to create runner error"); + return ERR_INVALID_OPERATION; + } + if (!appMgrServiceInner_) { + APP_LOGE("init failed without inner service"); + return ERR_INVALID_OPERATION; + } + appMgrServiceInner_->Init(); + handler_ = std::make_shared(runner_, appMgrServiceInner_); + if (!handler_) { + APP_LOGE("init failed without handler"); + return ERR_INVALID_OPERATION; + } + appMgrServiceInner_->SetEventHandler(handler_); + ErrCode openErr = appMgrServiceInner_->OpenAppSpawnConnection(); + if (FAILED(openErr)) { + APP_LOGW("failed to connect to AppSpawnDaemon! errCode: %{public}08x", openErr); + } + if (!Publish(this)) { + APP_LOGE("failed to publish appmgrservice to systemAbilityMgr"); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + amsMgrScheduler_ = new (std::nothrow) AmsMgrScheduler(appMgrServiceInner_, handler_); + if (!amsMgrScheduler_) { + APP_LOGE("init failed without ams scheduler"); + return ERR_INVALID_OPERATION; + } + if (appMgrServiceInner_->ProcessOptimizerInit() != ERR_OK) { + APP_LOGE("init failed without process optimizer"); + } + APP_LOGI("init success"); + return ERR_OK; +} + +int32_t AppMgrService::CheckPermission( + [[maybe_unused]] const int32_t recordId, [[maybe_unused]] const std::string &permission) +{ + APP_LOGI("check application's permission"); + + return ERR_OK; +} + +void AppMgrService::AttachApplication(const sptr &app) +{ + if (!IsReady()) { + APP_LOGE("AttachApplication failed, not ready."); + return; + } + + pid_t pid = IPCSkeleton::GetCallingPid(); + AddAppDeathRecipient(pid); + std::function attachApplicationFunc = + std::bind(&AppMgrServiceInner::AttachApplication, appMgrServiceInner_, pid, iface_cast(app)); + handler_->PostTask(attachApplicationFunc, TASK_ATTACH_APPLICATION); +} + +void AppMgrService::ApplicationForegrounded(const int32_t recordId) +{ + if (!IsReady()) { + return; + } + std::function applicationForegroundedFunc = + std::bind(&AppMgrServiceInner::ApplicationForegrounded, appMgrServiceInner_, recordId); + handler_->PostTask(applicationForegroundedFunc, TASK_APPLICATION_FOREGROUNDED); +} + +void AppMgrService::ApplicationBackgrounded(const int32_t recordId) +{ + if (!IsReady()) { + return; + } + std::function applicationBackgroundedFunc = + std::bind(&AppMgrServiceInner::ApplicationBackgrounded, appMgrServiceInner_, recordId); + handler_->PostTask(applicationBackgroundedFunc, TASK_APPLICATION_BACKGROUNDED); +} + +void AppMgrService::ApplicationTerminated(const int32_t recordId) +{ + if (!IsReady()) { + return; + } + std::function applicationTerminatedFunc = + std::bind(&AppMgrServiceInner::ApplicationTerminated, appMgrServiceInner_, recordId); + handler_->PostTask(applicationTerminatedFunc, TASK_APPLICATION_TERMINATED); +} + +void AppMgrService::AbilityCleaned(const sptr &token) +{ + if (!IsReady()) { + return; + } + std::function abilityCleanedFunc = + std::bind(&AppMgrServiceInner::AbilityTerminated, appMgrServiceInner_, token); + handler_->PostTask(abilityCleanedFunc, TASK_ABILITY_CLEANED); +} + +bool AppMgrService::IsReady() const +{ + if (!appMgrServiceInner_) { + APP_LOGE("appMgrServiceInner is null"); + return false; + } + if (!handler_) { + APP_LOGE("handler is null"); + return false; + } + return true; +} + +void AppMgrService::AddAppDeathRecipient(const pid_t pid) const +{ + if (!IsReady()) { + return; + } + sptr appDeathRecipient = new AppDeathRecipient(); + appDeathRecipient->SetEventHandler(handler_); + appDeathRecipient->SetAppMgrServiceInner(appMgrServiceInner_); + std::function addAppRecipientFunc = + std::bind(&AppMgrServiceInner::AddAppDeathRecipient, appMgrServiceInner_, pid, appDeathRecipient); + handler_->PostTask(addAppRecipientFunc, TASK_ADD_APP_DEATH_RECIPIENT); +} + +void AppMgrService::StartupResidentProcess() +{ + if (!IsReady()) { + return; + } + APP_LOGI("Notify start resident process"); + std::function startupResidentProcess = + std::bind(&AppMgrServiceInner::LoadResidentProcess, appMgrServiceInner_); + handler_->PostTask(startupResidentProcess, TASK_STARTUP_RESIDENT_PROCESS); +} + +sptr AppMgrService::GetAmsMgr() +{ + return amsMgrScheduler_; +} + +int32_t AppMgrService::ClearUpApplicationData(const std::string &bundleName) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + int32_t uid = IPCSkeleton::GetCallingUid(); + pid_t pid = IPCSkeleton::GetCallingPid(); + std::function clearUpApplicationDataFunc = + std::bind(&AppMgrServiceInner::ClearUpApplicationData, appMgrServiceInner_, bundleName, uid, pid); + handler_->PostTask(clearUpApplicationDataFunc, TASK_CLEAR_UP_APPLICATION_DATA); + return ERR_OK; +} + +int32_t AppMgrService::IsBackgroundRunningRestricted(const std::string &bundleName) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->IsBackgroundRunningRestricted(bundleName); +} + +int32_t AppMgrService::GetAllRunningProcesses(std::vector &info) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->GetAllRunningProcesses(info); +} + +int32_t AppMgrService::GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->GetProcessRunningInfosByUserId(info, userId); +} + +void AppMgrService::SetAppFreezingTime(int time) +{ + APP_LOGI("set app freeze time %{public}d", time); + if (!IsReady()) { + return; + } + appMgrServiceInner_->SetAppFreezingTime(time); +} + +void AppMgrService::GetAppFreezingTime(int &time) +{ + if (!IsReady()) { + return; + } + appMgrServiceInner_->GetAppFreezingTime(time); + APP_LOGE("get app freeze time %{public}d ", time); +} + +/** + * Get system memory information. + * @param SystemMemoryAttr, memory information. + */ +void AppMgrService::GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig) +{ + SystemEnv::KernelSystemMemoryInfo systemMemInfo; + SystemEnv::GetMemInfo(systemMemInfo); + int memThreshold = 0; + nlohmann::json memJson = nlohmann::json::parse(strConfig, nullptr, false); + if (memJson.is_discarded()) { + memThreshold = EXPERIENCE_MEM_THRESHOLD; + APP_LOGE("%{public}s, discarded memThreshold = %{public}d", __func__, EXPERIENCE_MEM_THRESHOLD); + } else { + if (!memJson.contains("memoryThreshold")) { + memThreshold = EXPERIENCE_MEM_THRESHOLD; + APP_LOGE("%{public}s, memThreshold = %{public}d", __func__, EXPERIENCE_MEM_THRESHOLD); + } else { + memThreshold = memJson.at("memorythreshold").get(); + APP_LOGI("memThreshold = %{public}d", memThreshold); + } + } + + memoryInfo.availSysMem_ = systemMemInfo.GetMemFree(); + memoryInfo.totalSysMem_ = systemMemInfo.GetMemTotal(); + memoryInfo.threshold_ = static_cast(memoryInfo.totalSysMem_ * memThreshold / PERCENTAGE); + memoryInfo.isSysInlowMem_ = memoryInfo.availSysMem_ < memoryInfo.threshold_; +} + +void AppMgrService::AddAbilityStageDone(const int32_t recordId) +{ + if (!IsReady()) { + return; + } + std::function addAbilityStageDone = + std::bind(&AppMgrServiceInner::AddAbilityStageDone, appMgrServiceInner_, recordId); + handler_->PostTask(addAbilityStageDone, TASK_ADD_ABILITY_STAGE_DONE); +} + +int32_t AppMgrService::RegisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (!IsReady()) { + APP_LOGE("%{public}s begin, not ready", __func__); + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->RegisterApplicationStateObserver(observer); +} + +int32_t AppMgrService::UnregisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (!IsReady()) { + APP_LOGE("%{public}s begin, not ready", __func__); + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->UnregisterApplicationStateObserver(observer); +} + +int32_t AppMgrService::GetForegroundApplications(std::vector &list) +{ + APP_LOGI("%{public}s begin", __func__); + if (!IsReady()) { + APP_LOGE("%{public}s begin, not ready", __func__); + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->GetForegroundApplications(list); +} + +int AppMgrService::StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const AppExecFwk::BundleInfo &bundleInfo) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + std::function startUserTestProcessFunc = + std::bind(&AppMgrServiceInner::StartUserTestProcess, appMgrServiceInner_, want, observer, bundleInfo); + handler_->PostTask(startUserTestProcessFunc, TASK_START_USER_TEST_PROCESS); + return ERR_OK; +} + +void AppMgrService::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag) +{ + if (!IsReady()) { + return; + } + auto task = [=]() { appMgrServiceInner_->ScheduleAcceptWantDone(recordId, want, flag); }; + handler_->PostTask(task); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service_event_handler.cpp b/services/appmgr/src/app_mgr_service_event_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a341764f5143c88ce3f07627cf3594256717cb53 --- /dev/null +++ b/services/appmgr/src/app_mgr_service_event_handler.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_service_event_handler.h" + +#include "app_log_wrapper.h" +#include "app_mgr_service_inner.h" + +namespace OHOS { +namespace AppExecFwk { +AMSEventHandler::AMSEventHandler( + const std::shared_ptr &runner, const std::weak_ptr &appMgr) + : EventHandler(runner), appMgr_(appMgr) +{ + APP_LOGI("instance created"); +} + +AMSEventHandler::~AMSEventHandler() +{ + APP_LOGI("instance destroyed"); +} + +void AMSEventHandler::ProcessEvent(const InnerEvent::Pointer &event) +{ + if (event == nullptr) { + APP_LOGE("AppEventHandler::ProcessEvent::parameter error"); + return; + } + + auto appManager = appMgr_.lock(); + if (!appManager) { + APP_LOGE("app manager is nullptr"); + return; + } + appManager->HandleTimeOut(event); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e69f774742fbe5bdd11378b8f30dd6a07e36e75f --- /dev/null +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -0,0 +1,2135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_service_inner.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "application_state_observer_stub.h" +#include "datetime_ex.h" +#include "perf_profile.h" + +#include "app_process_data.h" +#include "bundle_constants.h" +#include "bytrace.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "os_account_manager.h" +#include "permission/permission_kit.h" +#include "system_ability_definition.h" +#include "locale_config.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::Security; + +namespace { +// NANOSECONDS mean 10^9 nano second +constexpr int64_t NANOSECONDS = 1000000000; +// MICROSECONDS mean 10^6 millias second +constexpr int64_t MICROSECONDS = 1000000; +// Kill process timeout setting +constexpr int KILL_PROCESS_TIMEOUT_MICRO_SECONDS = 1000; +// Kill process delaytime setting +constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200; +const std::string CLASS_NAME = "ohos.app.MainThread"; +const std::string FUNC_NAME = "main"; +const std::string SO_PATH = "system/lib64/libmapleappkit.z.so"; +const int32_t SIGNAL_KILL = 9; +const std::string REQ_PERMISSION = "ohos.permission.LOCATION_IN_BACKGROUND"; +constexpr int32_t SYSTEM_UID = 1000; +constexpr int32_t USER_SCALE = 200000; +#define ENUM_TO_STRING(s) #s + +constexpr int32_t BASE_USER_RANGE = 200000; + +int32_t GetUserIdByUid(int32_t uid) +{ + return uid / BASE_USER_RANGE; +} +} // namespace + +using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED; +using OHOS::AppExecFwk::Constants::PERMISSION_NOT_GRANTED; +using OHOS::AppExecFwk::Constants::ROOT_UID; + +AppMgrServiceInner::AppMgrServiceInner() + : appProcessManager_(std::make_shared()), + remoteClientManager_(std::make_shared()), + appRunningManager_(std::make_shared()), + configuration_(std::make_shared()) +{} + +void AppMgrServiceInner::Init() +{ + GetGlobalConfiguration(); +} + +AppMgrServiceInner::~AppMgrServiceInner() +{} + +void AppMgrServiceInner::LoadAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!CheckLoadabilityConditions(token, abilityInfo, appInfo)) { + APP_LOGE("CheckLoadabilityConditions failed"); + return; + } + + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)) { + APP_LOGE("GetBundleAndHapInfo failed"); + return; + } + + std::string processName; + MakeProcessName(processName, abilityInfo, appInfo); + APP_LOGI("processName = [%{public}s]", processName.c_str()); + + auto appRecord = + appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo); + if (!appRecord) { + appRecord = + CreateAppRunningRecord(token, preToken, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + if (!appRecord) { + APP_LOGI("CreateAppRunningRecord failed, appRecord is nullptr"); + return; + } + StartProcess(abilityInfo->applicationName, processName, appRecord, + abilityInfo->applicationInfo.uid, abilityInfo->applicationInfo.bundleName); + } else { + StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo); + } + PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount()); + PerfProfile::GetInstance().Dump(); + PerfProfile::GetInstance().Reset(); +} + +bool AppMgrServiceInner::CheckLoadabilityConditions(const sptr &token, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) +{ + if (!token || !abilityInfo || !appInfo) { + APP_LOGE("param error"); + return false; + } + if (abilityInfo->name.empty() || appInfo->name.empty()) { + APP_LOGE("error abilityInfo or appInfo"); + return false; + } + if (abilityInfo->applicationName != appInfo->name) { + APP_LOGE("abilityInfo and appInfo have different appName, don't load for it"); + return false; + } + + return true; +} + +void AppMgrServiceInner::MakeProcessName(std::string &processName, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo) +{ + if (!abilityInfo || !appInfo) { + return; + } + if (!abilityInfo->process.empty()) { + processName = abilityInfo->process; + return; + } + if (!appInfo->process.empty()) { + processName = appInfo->process; + return; + } + processName = appInfo->bundleName; +} + +bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo, + const std::shared_ptr &appInfo, BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo) +{ + APP_LOGI("AppMgrServiceInner GetBundleAndHapInfo start!"); + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return false; + } + + auto userId = GetUserIdByUid(abilityInfo.applicationInfo.uid); + bool bundleMgrResult = bundleMgr_->GetBundleInfo(appInfo->bundleName, + BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId); + if (!bundleMgrResult) { + APP_LOGE("GetBundleInfo is fail"); + return false; + } + bundleMgrResult = bundleMgr_->GetHapModuleInfo(abilityInfo, hapModuleInfo); + if (!bundleMgrResult) { + APP_LOGE("GetHapModuleInfo is fail"); + return false; + } + + return true; +} + +void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr &app) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (pid <= 0) { + APP_LOGE("invalid pid:%{public}d", pid); + return; + } + if (!app) { + APP_LOGE("app client is null"); + return; + } + APP_LOGI("attach application pid:%{public}d", pid); + auto appRecord = GetAppRunningRecordByPid(pid); + if (!appRecord) { + APP_LOGE("no such appRecord"); + return; + } + appRecord->SetApplicationClient(app); + if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) { + LaunchApplication(appRecord); + } + appRecord->RegisterAppDeathRecipient(); +} + +void AppMgrServiceInner::LaunchApplication(const std::shared_ptr &appRecord) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!appRecord) { + APP_LOGE("appRecord is null"); + return; + } + + if (!configuration_) { + APP_LOGE("configuration_ is null"); + return; + } + + if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) { + APP_LOGE("wrong app state:%{public}d", appRecord->GetState()); + return; + } + appRecord->LaunchApplication(*configuration_); + appRecord->SetState(ApplicationState::APP_STATE_READY); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); + + // There is no ability when the resident process starts + // The status of all resident processes is ready + // There is no process of switching the foreground, waiting for his first ability to start + if (appRecord->IsKeepAliveApp()) { + appRecord->AddAbilityStage(); + return; + } + + if (appRecord->IsStartSpecifiedAbility()) { + appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName()); + return; + } + appRecord->LaunchPendingAbilities(); +} + +void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId) +{ + auto appRecord = GetAppRunningRecordByAppRecordId(recordId); + if (!appRecord) { + APP_LOGE("get app record failed"); + return; + } + appRecord->AddAbilityStageDone(); +} + +void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + auto appRecord = GetAppRunningRecordByAppRecordId(recordId); + if (!appRecord) { + APP_LOGE("get app record failed"); + return; + } + appRecord->PopForegroundingAbilityTokens(); + ApplicationState appState = appRecord->GetState(); + if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) { + appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND); + OptimizerAppStateChanged(appRecord, appState); + OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND); + } else if (appState == ApplicationState::APP_STATE_SUSPENDED) { + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); + } else { + APP_LOGW("app name(%{public}s), app state(%{public}d)!", + appRecord->GetName().c_str(), + static_cast(appState)); + } + + // push the foregrounded app front of RecentAppList. + PushAppFront(recordId); + APP_LOGI("application is foregrounded"); +} + +void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + auto appRecord = GetAppRunningRecordByAppRecordId(recordId); + if (!appRecord) { + APP_LOGE("get app record failed"); + return; + } + if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) { + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND); + OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND); + } else if (appRecord->GetState() == ApplicationState::APP_STATE_SUSPENDED) { + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); + } else { + APP_LOGW("app name(%{public}s), app state(%{public}d)!", + appRecord->GetName().c_str(), + static_cast(appRecord->GetState())); + } + + APP_LOGI("application is backgrounded"); +} + +void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + auto appRecord = GetAppRunningRecordByAppRecordId(recordId); + if (!appRecord) { + APP_LOGE("get app record failed"); + return; + } + // Maybe can't get in here + if (appRecord->IsKeepAliveApp()) { + return; + } + if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) { + APP_LOGE("current state is not background"); + return; + } + appRecord->SetState(ApplicationState::APP_STATE_TERMINATED); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND); + appRecord->RemoveAppDeathRecipient(); + OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); + appRunningManager_->RemoveAppRunningRecordById(recordId); + RemoveAppFromRecentListById(recordId); + OnProcessDied(appRecord); + + APP_LOGI("application is terminated"); +} + +int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName) +{ + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return ERR_NO_INIT; + } + + int result = ERR_OK; + int64_t startTime = SystemTimeMillis(); + std::list pids; + + if (!appRunningManager_->ProcessExitByBundleName(bundleName, pids)) { + APP_LOGI("The process corresponding to the package name did not start"); + return result; + } + if (WaitForRemoteProcessExit(pids, startTime)) { + APP_LOGI("The remote process exited successfully "); + NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); + return result; + } + for (auto iter = pids.begin(); iter != pids.end(); ++iter) { + result = KillProcessByPid(*iter); + if (result < 0) { + APP_LOGE("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter); + return result; + } + } + NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); + return result; +} + +int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid) +{ + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return ERR_NO_INIT; + } + int result = ERR_OK; + int64_t startTime = SystemTimeMillis(); + std::list pids; + if (remoteClientManager_ == nullptr) { + APP_LOGE("remoteClientManager_ fail"); + return ERR_NO_INIT; + } + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return ERR_NO_INIT; + } + APP_LOGI("uid value is %{public}d", uid); + if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) { + APP_LOGI("The process corresponding to the package name did not start"); + return result; + } + if (WaitForRemoteProcessExit(pids, startTime)) { + APP_LOGI("The remote process exited successfully "); + return result; + } + for (auto iter = pids.begin(); iter != pids.end(); ++iter) { + result = KillProcessByPid(*iter); + if (result < 0) { + APP_LOGE("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter); + return result; + } + } + return result; +} + +int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleName, const int userId) +{ + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return ERR_NO_INIT; + } + int result = ERR_OK; + int64_t startTime = SystemTimeMillis(); + std::list pids; + if (remoteClientManager_ == nullptr) { + APP_LOGE("remoteClientManager_ fail"); + return ERR_NO_INIT; + } + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return ERR_NO_INIT; + } + APP_LOGI("userId value is %{public}d", userId); + int uid = bundleMgr_->GetUidByBundleName(bundleName, userId); + APP_LOGI("uid value is %{public}d", uid); + if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) { + APP_LOGI("The process corresponding to the package name did not start"); + return result; + } + if (WaitForRemoteProcessExit(pids, startTime)) { + APP_LOGI("The remote process exited successfully "); + return result; + } + for (auto iter = pids.begin(); iter != pids.end(); ++iter) { + result = KillProcessByPid(*iter); + if (result < 0) { + APP_LOGE("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter); + return result; + } + } + return result; +} + +void AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName, int32_t callerUid, pid_t callerPid) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, Constants::DEFAULT_USERID); +} + +void AppMgrServiceInner::ClearUpApplicationDataByUserId( + const std::string &bundleName, int32_t callerUid, pid_t callerPid, const int userId) +{ + if (callerPid <= 0) { + APP_LOGE("invalid callerPid:%{public}d", callerPid); + return; + } + if (callerUid <= 0) { + APP_LOGE("invalid callerUid:%{public}d", callerUid); + return; + } + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return; + } + + // request to clear user information permission. + int32_t result = + Permission::PermissionKit::RemoveUserGrantedReqPermissions(bundleName, userId); + if (result) { + APP_LOGE("RemoveUserGrantedReqPermissions failed"); + return; + } + // 2.delete bundle side user data + if (!bundleMgr_->CleanBundleDataFiles(bundleName, userId)) { + APP_LOGE("Delete bundle side user data is fail"); + return; + } + // 3.kill application + // 4.revoke user rights + result = KillApplicationByUserId(bundleName, userId); + if (result < 0) { + APP_LOGE("Kill Application by bundle name is fail"); + return; + } + NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); +} + +int32_t AppMgrServiceInner::IsBackgroundRunningRestricted(const std::string &bundleName) +{ + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return ERR_DEAD_OBJECT; + } + return bundleMgr_->CheckPermission(bundleName, REQ_PERMISSION); +} + +int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector &info) +{ + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return ERR_DEAD_OBJECT; + } + // check permission + for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) { + const auto &appRecord = item.second; + if (USER_SCALE == 0) { + APP_LOGE("USER_SCALE is not zero"); + return ERR_WOULD_BLOCK; + } + int32_t userId = static_cast(appRecord->GetUid() / USER_SCALE); + bool isExist = false; + auto errCode = AccountSA::OsAccountManager::IsOsAccountActived(userId, isExist); + if ((errCode == ERR_OK) && isExist) { + RunningProcessInfo runningProcessInfo; + runningProcessInfo.processName_ = appRecord->GetProcessName(); + runningProcessInfo.pid_ = appRecord->GetPriorityObject()->GetPid(); + runningProcessInfo.uid_ = appRecord->GetUid(); + runningProcessInfo.state_ = static_cast(appRecord->GetState()); + appRecord->GetBundleNames(runningProcessInfo.bundleNames); + info.emplace_back(runningProcessInfo); + } + } + return ERR_OK; +} + +int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) +{ + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return ERR_DEAD_OBJECT; + } + + for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) { + const auto &appRecord = item.second; + if (USER_SCALE == 0) { + APP_LOGE("USER_SCALE is not zero"); + return ERR_WOULD_BLOCK; + } + int32_t userIdTemp = static_cast(appRecord->GetUid() / USER_SCALE); + if (userIdTemp == userId) { + RunningProcessInfo runningProcessInfo; + runningProcessInfo.processName_ = appRecord->GetProcessName(); + runningProcessInfo.pid_ = appRecord->GetPriorityObject()->GetPid(); + runningProcessInfo.uid_ = appRecord->GetUid(); + runningProcessInfo.state_ = static_cast(appRecord->GetState()); + appRecord->GetBundleNames(runningProcessInfo.bundleNames); + info.emplace_back(runningProcessInfo); + } + } + return ERR_OK; +} + +int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid) const +{ + int32_t ret = -1; + if (pid > 0) { + APP_LOGI("kill pid %{public}d", pid); + ret = kill(pid, SIGNAL_KILL); + } + return ret; +} + +bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list &pids, const int64_t startTime) +{ + int64_t delayTime = SystemTimeMillis() - startTime; + while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) { + if (CheckAllProcessExist(pids)) { + return true; + } + usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS); + delayTime = SystemTimeMillis() - startTime; + } + return false; +} + +bool AppMgrServiceInner::GetAllPids(std::list &pids) +{ + for (const auto &appTaskInfo : appProcessManager_->GetRecentAppList()) { + if (appTaskInfo) { + auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid()); + if (appRecord) { + pids.push_back(appTaskInfo->GetPid()); + appRecord->ScheduleProcessSecurityExit(); + } + } + } + return (pids.empty() ? false : true); +} + +bool AppMgrServiceInner::process_exist(pid_t &pid) +{ + char pid_path[128] = {0}; + struct stat stat_buf; + if (!pid) { + return false; + } + if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) { + return false; + } + if (stat(pid_path, &stat_buf) == 0) { + return true; + } + return false; +} + +bool AppMgrServiceInner::CheckAllProcessExist(std::list &pids) +{ + for (auto iter = pids.begin(); iter != pids.end(); ) { + if (!process_exist(*iter)) { + iter = pids.erase(iter); + } else { + iter++; + } + } + if (pids.empty()) { + return true; + } + return false; +} + +int64_t AppMgrServiceInner::SystemTimeMillis() +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_MONOTONIC, &t); + return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS; +} + +std::shared_ptr AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const +{ + return appRunningManager_->GetAppRunningRecordByPid(pid); +} + +std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(const sptr &token, + const sptr &preToken, const std::shared_ptr &appInfo, + const std::shared_ptr &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo, + const HapModuleInfo &hapModuleInfo) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!appRunningManager_) { + return nullptr; + } + auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo); + if (!appRecord) { + return nullptr; + } + + appRecord->SetEventHandler(eventHandler_); + appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + + if (preToken) { + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + if (abilityRecord) { + abilityRecord->SetPreToken(preToken); + } + } + + return appRecord; +} + +void AppMgrServiceInner::TerminateAbility(const sptr &token) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGD("AppMgrServiceInner::TerminateAbility begin"); + if (!token) { + APP_LOGE("AppMgrServiceInner::TerminateAbility token is null!"); + return; + } + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("AppMgrServiceInner::TerminateAbility app is not exist!"); + return; + } + if (appRecord->GetState() == ApplicationState::APP_STATE_SUSPENDED) { + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); + } + + if (appRunningManager_) { + appRunningManager_->TerminateAbility(token); + } +} + +void AppMgrServiceInner::UpdateAbilityState(const sptr &token, const AbilityState state) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!token) { + APP_LOGE("token is null!"); + return; + } + if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) { + APP_LOGE("state is not foreground or background!"); + return; + } + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("app is not exist!"); + return; + } + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + if (!abilityRecord) { + APP_LOGE("can not find ability record!"); + return; + } + if (state == abilityRecord->GetState()) { + APP_LOGE("current state is already, no need update!"); + return; + } + if (appRecord->GetState() == ApplicationState::APP_STATE_SUSPENDED) { + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); + } + + appRecord->UpdateAbilityState(token, state); +} + +void AppMgrServiceInner::UpdateExtensionState(const sptr &token, const ExtensionState state) +{ + if (!token) { + APP_LOGE("token is null!"); + return; + } + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("app is not exist!"); + return; + } + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + if (!abilityRecord) { + APP_LOGE("can not find ability record!"); + return; + } + appRecord->StateChangedNotifyObserver(abilityRecord, static_cast(state), false); +} + +void AppMgrServiceInner::OnStop() +{ + appRunningManager_->ClearAppRunningRecordMap(); + CloseAppSpawnConnection(); +} + +ErrCode AppMgrServiceInner::OpenAppSpawnConnection() +{ + if (remoteClientManager_->GetSpawnClient()) { + return remoteClientManager_->GetSpawnClient()->OpenConnection(); + } + return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT; +} + +void AppMgrServiceInner::CloseAppSpawnConnection() const +{ + if (remoteClientManager_->GetSpawnClient()) { + remoteClientManager_->GetSpawnClient()->CloseConnection(); + } +} + +SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const +{ + if (remoteClientManager_->GetSpawnClient()) { + return remoteClientManager_->GetSpawnClient()->QueryConnectionState(); + } + return SpawnConnectionState::STATE_NOT_CONNECT; +} + +const std::map> &AppMgrServiceInner::GetRecordMap() const +{ + return appRunningManager_->GetAppRunningRecordMap(); +} + +void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr spawnClient) +{ + remoteClientManager_->SetSpawnClient(std::move(spawnClient)); +} + +void AppMgrServiceInner::SetBundleManager(sptr bundleManager) +{ + remoteClientManager_->SetBundleManager(bundleManager); +} + +void AppMgrServiceInner::RegisterAppStateCallback(const sptr &callback) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (callback != nullptr) { + appStateCallbacks_.push_back(callback); + } +} + +void AppMgrServiceInner::StopAllProcess() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + ClearRecentAppList(); + appRunningManager_->ClearAppRunningRecordMap(); +} + +void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, + const int32_t visibility, // 0:false,1:true + const int32_t perceptibility, // 0:false,1:true + const int32_t connectionState) // 0:false,1:true +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!token) { + APP_LOGE("token is null"); + return; + } + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("app record is not exist for ability token"); + return; + } + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + if (!abilityRecord) { + APP_LOGE("ability record is not exist for ability previous token"); + return; + } + if (preToken) { + abilityRecord->SetPreToken(preToken); + } + if (abilityRecord->GetVisibility() != visibility) { + if (processOptimizerUBA_) { + processOptimizerUBA_->OnAbilityVisibleChanged(abilityRecord); + } + } + if (abilityRecord->GetPerceptibility() != perceptibility) { + if (processOptimizerUBA_) { + processOptimizerUBA_->OnAbilityPerceptibleChanged(abilityRecord); + } + } + abilityRecord->SetVisibility(visibility); + abilityRecord->SetPerceptibility(perceptibility); + abilityRecord->SetConnectionState(connectionState); + OptimizerAbilityStateChanged(abilityRecord, abilityRecord->GetState()); +} + +void AppMgrServiceInner::KillProcessByAbilityToken(const sptr &token) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!token) { + APP_LOGE("token is null"); + return; + } + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("app record is not exist for ability token"); + return; + } + + // befor exec ScheduleProcessSecurityExit return + // The resident process won't let him die + if (appRecord->IsKeepAliveApp()) { + return; + } + + std::list pids; + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + if (pid > 0) { + pids.push_back(pid); + appRecord->ScheduleProcessSecurityExit(); + if (!WaitForRemoteProcessExit(pids, SystemTimeMillis())) { + int32_t result = KillProcessByPid(pid); + if (result < 0) { + APP_LOGE("KillProcessByAbilityToken kill process is fail"); + return; + } + } + } +} + +void AppMgrServiceInner::KillProcessesByUserId(int32_t userId) +{ + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + + int64_t startTime = SystemTimeMillis(); + std::list pids; + if (!appRunningManager_->GetPidsByUserId(userId, pids)) { + APP_LOGI("The process corresponding to the userId did not start"); + return; + } + if (WaitForRemoteProcessExit(pids, startTime)) { + APP_LOGI("The remote process exited successfully "); + return; + } + for (auto iter = pids.begin(); iter != pids.end(); ++iter) { + auto result = KillProcessByPid(*iter); + if (result < 0) { + APP_LOGE("KillProcessByPid is failed. pid: %{public}d", *iter); + return; + } + } +} + +void AppMgrServiceInner::StartAbility(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appRecord, + const HapModuleInfo &hapModuleInfo) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("already create appRecord, just start ability"); + if (!appRecord) { + APP_LOGE("appRecord is null"); + return; + } + + if (abilityInfo->launchMode == LaunchMode::SINGLETON) { + auto abilityRecord = appRecord->GetAbilityRunningRecord(abilityInfo->name); + if (abilityRecord) { + APP_LOGW("same ability info in singleton launch mode, will not add ability"); + return; + } + } + + auto ability = appRecord->GetAbilityRunningRecordByToken(token); + if (ability && preToken) { + APP_LOGE("Ability is already started"); + ability->SetPreToken(preToken); + return; + } + + ApplicationState appState = appRecord->GetState(); + if (appState == ApplicationState::APP_STATE_SUSPENDED) { + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); + } + + auto appInfo = std::make_shared(abilityInfo->applicationInfo); + appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + if (!moduleRecord) { + APP_LOGE("add moduleRecord failed"); + return; + } + + ability = moduleRecord->GetAbilityRunningRecordByToken(token); + if (!ability) { + APP_LOGE("add ability failed"); + return; + } + + if (preToken != nullptr) { + ability->SetPreToken(preToken); + } + + if (appState == ApplicationState::APP_STATE_CREATE) { + APP_LOGE("in create state, don't launch ability"); + return; + } + appRecord->LaunchAbility(ability); +} + +std::shared_ptr AppMgrServiceInner::GetAppRunningRecordByAbilityToken( + const sptr &abilityToken) const +{ + return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken); +} + +void AppMgrServiceInner::UnsuspendApplication(const std::shared_ptr &appRecord) +{ + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + + APP_LOGI("app name is %{public}s , Uid is %{public}d", appRecord->GetName().c_str(), appRecord->GetUid()); + // Resume subscription via UID + DelayedSingleton::GetInstance()->Unfreeze(appRecord->GetUid()); +} + +void AppMgrServiceInner::SuspendApplication(const std::shared_ptr &appRecord) +{ + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + APP_LOGD("app name is %{public}s , Uid is %{public}d", appRecord->GetName().c_str(), appRecord->GetUid()); + // Temporary unsubscribe via UID + appRecord->SetState(ApplicationState::APP_STATE_SUSPENDED); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND); + DelayedSingleton::GetInstance()->Freeze(appRecord->GetUid()); +} + +void AppMgrServiceInner::LowMemoryApplicationAlert( + const std::shared_ptr &appRecord, const CgroupManager::LowMemoryLevel level) +{ + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } +} + +std::shared_ptr AppMgrServiceInner::GetAbilityOwnerApp( + const std::shared_ptr &abilityRecord) const +{ + if (!abilityRecord) { + APP_LOGE("ability record is null"); + return nullptr; + } + if (!abilityRecord->GetToken()) { + APP_LOGE("ability token is null"); + return nullptr; + } + auto appRecord = GetAppRunningRecordByAbilityToken(abilityRecord->GetToken()); + if (!appRecord) { + APP_LOGE("The app information corresponding to token does not exist"); + return nullptr; + } + return appRecord; +} + +std::shared_ptr AppMgrServiceInner::GetAbilityRunningRecordByAbilityToken( + const sptr &abilityToken) const +{ + if (!abilityToken) { + APP_LOGE("ability token is null"); + return nullptr; + } + auto appRecord = GetAppRunningRecordByAbilityToken(abilityToken); + if (!appRecord) { + APP_LOGE("The app information corresponding to token does not exist"); + return nullptr; + } + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(abilityToken); + if (!abilityRecord) { + APP_LOGE("The ability information corresponding to token does not exist"); + return nullptr; + } + return abilityRecord; +} + +void AppMgrServiceInner::AbilityTerminated(const sptr &token) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGD("begin"); + if (!token) { + APP_LOGE("token is null!"); + return; + } + + auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token); + if (!appRecord) { + APP_LOGE("app is not exist!"); + return; + } + + appRecord->AbilityTerminated(token); +} + +std::shared_ptr AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const +{ + const auto &iter = appRunningManager_->GetAppRunningRecordMap().find(recordId); + if (iter != appRunningManager_->GetAppRunningRecordMap().end()) { + return iter->second; + } + return nullptr; +} + +void AppMgrServiceInner::OnAppStateChanged( + const std::shared_ptr &appRecord, const ApplicationState state) +{ + APP_LOGD("begin, state:%{public}d", static_cast(state)); + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + + for (const auto &callback : appStateCallbacks_) { + if (callback != nullptr) { + callback->OnAppStateChanged(WrapAppProcessData(appRecord, state)); + } + } + + if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) { + AppStateData data = WrapAppStateData(appRecord, state); + APP_LOGD("OnForegroundApplicationChanged, size:%{public}d, name:%{public}s, uid:%{public}d, state:%{public}d", + (int32_t)appStateObservers_.size(), data.bundleName.c_str(), data.uid, data.state); + std::lock_guard lockNotify(observerLock_); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + observer->OnForegroundApplicationChanged(data); + } + } + } + + if (state == ApplicationState::APP_STATE_CREATE || state == ApplicationState::APP_STATE_TERMINATED) { + AppStateData data = WrapAppStateData(appRecord, state); + APP_LOGI("OnApplicationStateChanged, size:%{public}d, name:%{public}s, uid:%{public}d, state:%{public}d", + (int32_t)appStateObservers_.size(), data.bundleName.c_str(), data.uid, data.state); + std::lock_guard lockNotify(observerLock_); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + observer->OnApplicationStateChanged(data); + } + } + } +} + +AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr &appRecord, + const ApplicationState state) +{ + AppProcessData processData; + auto appInfoList = appRecord->GetAppInfoList(); + for (const auto &list : appInfoList) { + AppData data; + data.appName = list->name; + data.uid = list->uid; + processData.appDatas.push_back(data); + } + processData.processName = appRecord->GetProcessName(); + processData.pid = appRecord->GetPriorityObject()->GetPid(); + processData.appState = state; + return processData; +} + +AppStateData AppMgrServiceInner::WrapAppStateData(const std::shared_ptr &appRecord, + const ApplicationState state) +{ + AppStateData appStateData; + appStateData.bundleName = appRecord->GetBundleName(); + appStateData.state = static_cast(state); + appStateData.uid = appRecord->GetUid(); + return appStateData; +} + +ProcessData AppMgrServiceInner::WrapProcessData(const std::shared_ptr &appRecord) +{ + ProcessData processData; + processData.bundleName = appRecord->GetBundleName(); + processData.pid = appRecord->GetPriorityObject()->GetPid(); + processData.uid = appRecord->GetUid(); + return processData; +} + +void AppMgrServiceInner::OnAbilityStateChanged( + const std::shared_ptr &ability, const AbilityState state) +{ + APP_LOGD("begin, state:%{public}d", static_cast(state)); + if (!ability) { + APP_LOGE("ability is null"); + return; + } + for (const auto &callback : appStateCallbacks_) { + if (callback != nullptr) { + callback->OnAbilityRequestDone(ability->GetToken(), state); + } + } +} + +void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility) +{ + std::lock_guard lockNotify(observerLock_); + APP_LOGD("bundle:%{public}s, ability:%{public}s, state:%{public}d, pid:%{public}d, uid:%{public}d", + abilityStateData.bundleName.c_str(), abilityStateData.abilityName.c_str(), + abilityStateData.abilityState, abilityStateData.pid, abilityStateData.uid); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + if (isAbility) { + observer->OnAbilityStateChanged(abilityStateData); + } else { + observer->OnExtensionStateChanged(abilityStateData); + } + } + } +} + +void AppMgrServiceInner::OnProcessCreated(const std::shared_ptr &appRecord) +{ + APP_LOGD("OnProcessCreated begin."); + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + ProcessData data = WrapProcessData(appRecord); + APP_LOGD("OnProcessCreated, bundle:%{public}s, pid:%{public}d, uid:%{public}d, size:%{public}d", + data.bundleName.c_str(), data.uid, data.pid, (int32_t)appStateObservers_.size()); + std::lock_guard lockNotify(observerLock_); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + observer->OnProcessCreated(data); + } + } + APP_LOGD("end"); +} + +void AppMgrServiceInner::OnProcessDied(const std::shared_ptr &appRecord) +{ + APP_LOGD("OnProcessDied begin."); + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + ProcessData data = WrapProcessData(appRecord); + APP_LOGD("OnProcessDied, bundle:%{public}s, pid:%{public}d, uid:%{public}d, size:%{public}d", + data.bundleName.c_str(), data.uid, data.pid, (int32_t)appStateObservers_.size()); + std::lock_guard lockNotify(observerLock_); + for (const auto &observer : appStateObservers_) { + if (observer != nullptr) { + observer->OnProcessDied(data); + } + } + APP_LOGD("end"); +} + +void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, + const std::shared_ptr &appRecord, const int uid, const std::string &bundleName) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!remoteClientManager_->GetSpawnClient() || !appRecord) { + APP_LOGE("appSpawnClient or apprecord is null"); + return; + } + + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return; + } + + auto userId = GetUserIdByUid(uid); + AppSpawnStartMsg startMsg; + BundleInfo bundleInfo; + std::vector bundleInfos; + bool bundleMgrResult = bundleMgr_->GetBundleInfos(AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, + bundleInfos, userId); + if (!bundleMgrResult) { + APP_LOGE("GetBundleInfo is fail"); + return; + } + + auto isExist = [&bundleName, &uid](const AppExecFwk::BundleInfo &bundleInfo) { + return bundleInfo.name == bundleName && bundleInfo.uid == uid; + }; + auto bundleInfoIter = std::find_if(bundleInfos.begin(), bundleInfos.end(), isExist); + if (bundleInfoIter == bundleInfos.end()) { + APP_LOGE("Get target fail."); + return; + } + startMsg.uid = (*bundleInfoIter).uid; + startMsg.gid = (*bundleInfoIter).gid; + startMsg.accessTokenId = (*bundleInfoIter).applicationInfo.accessTokenId; + startMsg.apl = bundleMgr_->GetAppPrivilegeLevel(bundleName); + APP_LOGD("StartProcess come, accessTokenId: %{public}d, apl: %{public}s", + startMsg.accessTokenId, startMsg.apl.c_str()); + + bundleMgrResult = bundleMgr_->GetBundleGidsByUid(bundleName, uid, startMsg.gids); + if (!bundleMgrResult) { + APP_LOGE("GetBundleGids is fail"); + return; + } + startMsg.procName = processName; + startMsg.soPath = SO_PATH; + + PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount()); + pid_t pid = 0; + ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid); + if (FAILED(errCode)) { + APP_LOGE("failed to spawn new app process, errCode %{public}08x", errCode); + appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); + return; + } + APP_LOGI("newPid:%{public}d uid:%{public}d", pid, startMsg.uid); + appRecord->GetPriorityObject()->SetPid(pid); + appRecord->SetUid(startMsg.uid); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); + appRecord->SetAppMgrServiceInner(weak_from_this()); + OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); + AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId()); + OnProcessCreated(appRecord); + PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount()); +} + +void AppMgrServiceInner::RemoveAppFromRecentList(const std::string &appName, const std::string &processName) +{ + int64_t startTime = 0; + std::list pids; + auto appTaskInfo = appProcessManager_->GetAppTaskInfoByProcessName(appName, processName); + if (!appTaskInfo) { + return; + } + auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid()); + if (!appRecord) { + appProcessManager_->RemoveAppFromRecentList(appTaskInfo); + return; + } + + // Do not delete resident processes, berfor exec ScheduleProcessSecurityExit + if (appRecord->IsKeepAliveApp()) { + return; + } + + startTime = SystemTimeMillis(); + pids.push_back(appTaskInfo->GetPid()); + appRecord->ScheduleProcessSecurityExit(); + if (!WaitForRemoteProcessExit(pids, startTime)) { + int32_t result = KillProcessByPid(appTaskInfo->GetPid()); + if (result < 0) { + APP_LOGE("RemoveAppFromRecentList kill process is fail"); + return; + } + } + appProcessManager_->RemoveAppFromRecentList(appTaskInfo); +} + +const std::list> &AppMgrServiceInner::GetRecentAppList() const +{ + return appProcessManager_->GetRecentAppList(); +} + +void AppMgrServiceInner::ClearRecentAppList() +{ + int64_t startTime = 0; + std::list pids; + if (GetAllPids(pids)) { + return; + } + + startTime = SystemTimeMillis(); + if (WaitForRemoteProcessExit(pids, startTime)) { + appProcessManager_->ClearRecentAppList(); + return; + } + for (auto iter = pids.begin(); iter != pids.end(); ++iter) { + int32_t result = KillProcessByPid(*iter); + if (result < 0) { + APP_LOGE("ClearRecentAppList kill process is fail"); + return; + } + } + appProcessManager_->ClearRecentAppList(); +} + +void AppMgrServiceInner::OnRemoteDied(const wptr &remote) +{ + APP_LOGE("On remote died."); + auto appRecord = appRunningManager_->OnRemoteDied(remote); + if (appRecord) { + for (const auto &item : appRecord->GetAbilities()) { + const auto &abilityRecord = item.second; + OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED); + appRecord->StateChangedNotifyObserver(abilityRecord, + static_cast(AbilityState::ABILITY_STATE_TERMINATED), true); + } + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); + RemoveAppFromRecentListById(appRecord->GetRecordId()); + OnProcessDied(appRecord); + } + + if (appRecord && appRecord->IsKeepAliveApp()) { + appRecord->DecRestartResidentProcCount(); + if (appRecord->CanRestartResidentProc()) { + auto restartProcss = [appRecord, innerService = shared_from_this()]() { + innerService->RestartResidentProcess(appRecord); + }; + + if (!eventHandler_) { + APP_LOGE("eventHandler_ is nullptr"); + return; + } + eventHandler_->PostTask(restartProcss, "RestartResidentProcess"); + } + } +} + +void AppMgrServiceInner::PushAppFront(const int32_t recordId) +{ + appProcessManager_->PushAppFront(recordId); +} + +void AppMgrServiceInner::RemoveAppFromRecentListById(const int32_t recordId) +{ + appProcessManager_->RemoveAppFromRecentListById(recordId); +} + +void AppMgrServiceInner::AddAppToRecentList( + const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId) +{ + appProcessManager_->AddAppToRecentList(appName, processName, pid, recordId); +} + +const std::shared_ptr AppMgrServiceInner::GetAppTaskInfoById(const int32_t recordId) const +{ + return appProcessManager_->GetAppTaskInfoById(recordId); +} + +void AppMgrServiceInner::AddAppDeathRecipient(const pid_t pid, const sptr &appDeathRecipient) const +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + std::shared_ptr appRecord = GetAppRunningRecordByPid(pid); + if (appRecord) { + appRecord->SetAppDeathRecipient(appDeathRecipient); + } +} + +int32_t AppMgrServiceInner::ProcessOptimizerInit() +{ + processOptimizerUBA_ = std::make_shared(nullptr); + bool isSuccess = processOptimizerUBA_->Init(); + if (!isSuccess) { + processOptimizerUBA_.reset(); + processOptimizerUBA_ = nullptr; + APP_LOGE("optimizer init is fail"); + return ERR_NO_INIT; + } + processOptimizerUBA_->AppSuspended = + std::bind(&AppMgrServiceInner::SuspendApplication, this, std::placeholders::_1); + // Register freeze callback function + processOptimizerUBA_->AppResumed = + std::bind(&AppMgrServiceInner::UnsuspendApplication, this, std::placeholders::_1); + // Register freeze recovery callback function + processOptimizerUBA_->AppLowMemoryAlert = + std::bind(&AppMgrServiceInner::LowMemoryApplicationAlert, this, std::placeholders::_1, std::placeholders::_2); + // Register low memory warning callback function + processOptimizerUBA_->GetAbilityOwnerApp = + std::bind(&AppMgrServiceInner::GetAbilityOwnerApp, this, std::placeholders::_1); + // Register to get the application record callback of ability + processOptimizerUBA_->GetAbilityByToken = + std::bind(&AppMgrServiceInner::GetAbilityRunningRecordByAbilityToken, this, std::placeholders::_1); + // Register to get the ability record through the token callback + APP_LOGI("optimizer init is success"); + return ERR_OK; +} + +void AppMgrServiceInner::OptimizerAbilityStateChanged( + const std::shared_ptr &ability, const AbilityState state) +{ + if (!processOptimizerUBA_) { + APP_LOGE("process optimizer is not init"); + return; + } + + if ((ability->GetAbilityInfo()->type == AbilityType::PAGE) || + (ability->GetAbilityInfo()->type == AbilityType::DATA)) { + if (ability->GetState() == AbilityState::ABILITY_STATE_CREATE) { + processOptimizerUBA_->OnAbilityStarted(ability); + APP_LOGI("optimizer OnAbilityStarted is called"); + } else if (ability->GetState() == AbilityState::ABILITY_STATE_TERMINATED) { + processOptimizerUBA_->OnAbilityRemoved(ability); + APP_LOGI("optimizer OnAbilityRemoved is called"); + } else { + processOptimizerUBA_->OnAbilityStateChanged(ability, state); + APP_LOGI("optimizer OnAbilityStateChanged is called"); + } + } else if (ability->GetAbilityInfo()->type == AbilityType::SERVICE) { + auto appRecord = GetAppRunningRecordByAbilityToken(ability->GetPreToken()); + if (!appRecord) { + APP_LOGE("app record is not exist for ability token"); + return; + } + auto targetAbility = appRecord->GetAbilityRunningRecordByToken(ability->GetPreToken()); + if (!targetAbility) { + APP_LOGE("ability record is not exist for ability previous token"); + return; + } + if (ability->GetConnectionState()) { + // connect + processOptimizerUBA_->OnAbilityConnected(ability, targetAbility); + APP_LOGI("optimizer OnAbilityConnected is called"); + } else { + // disconnect + processOptimizerUBA_->OnAbilityDisconnected(ability, targetAbility); + APP_LOGI("optimizer OnAbilityDisconnected is called"); + } + } else { + APP_LOGI("OptimizerAbilityStateChanged ability type is unknown"); + } + + if (ability->GetState() != state) { + processOptimizerUBA_->OnAbilityStateChanged(ability, state); + APP_LOGI("optimizer OnAbilityStateChanged is called"); + } +} + +void AppMgrServiceInner::OptimizerAppStateChanged( + const std::shared_ptr &appRecord, const ApplicationState state) +{ + if (!processOptimizerUBA_) { + APP_LOGE("process optimizer is not init"); + return; + } + if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) { + processOptimizerUBA_->OnAppAdded(appRecord); + APP_LOGI("optimizer OnAppAdded is called"); + } else if (appRecord->GetState() == ApplicationState::APP_STATE_TERMINATED) { + processOptimizerUBA_->OnAppRemoved(appRecord); + APP_LOGI("optimizer OnAppRemoved is called"); + } else { + processOptimizerUBA_->OnAppStateChanged(appRecord, state); + APP_LOGI("optimizer OnAppStateChanged is called"); + } +} + +void AppMgrServiceInner::SetAppFreezingTime(int time) +{ + if (!processOptimizerUBA_) { + APP_LOGE("process optimizer is not init"); + return; + } + + std::lock_guard setFreezeTimeLock(serviceLock_); + processOptimizerUBA_->SetAppFreezingTime(time); +} + +void AppMgrServiceInner::GetAppFreezingTime(int &time) +{ + if (!processOptimizerUBA_) { + APP_LOGE("process optimizer is not init"); + return; + } + std::lock_guard getFreezeTimeLock(serviceLock_); + processOptimizerUBA_->GetAppFreezingTime(time); +} + +void AppMgrServiceInner::HandleTimeOut(const InnerEvent::Pointer &event) +{ + APP_LOGI("handle time out"); + if (!appRunningManager_ || event == nullptr) { + APP_LOGE("appRunningManager or event is nullptr"); + return; + } + switch (event->GetInnerEventId()) { + case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG: + appRunningManager_->HandleTerminateTimeOut(event->GetParam()); + break; + case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG: + HandleTerminateApplicationTimeOut(event->GetParam()); + break; + case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG: + HandleAddAbilityStageTimeOut(event->GetParam()); + break; + case AMSEventHandler::START_MULTI_INSTANCES_ABILITY_MSG: + HandleStartSpecifiedAbilityTimeOut(event->GetParam()); + break; + default: + break; + } +} + +void AppMgrServiceInner::SetEventHandler(const std::shared_ptr &handler) +{ + eventHandler_ = handler; +} + +void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr &token) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + APP_LOGI("%{public}s called", __func__); + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + appRunningManager_->HandleAbilityAttachTimeOut(token); +} + +void AppMgrServiceInner::PrepareTerminate(const sptr &token) +{ + APP_LOGI("Prepare terminate"); + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + appRunningManager_->PrepareTerminate(token); +} + +void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId) +{ + APP_LOGI("handle terminate application time out"); + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + auto appRecord = appRunningManager_->GetAppRunningRecord(eventId); + if (!appRecord) { + APP_LOGE("appRecord is nullptr"); + return; + } + appRecord->SetState(ApplicationState::APP_STATE_TERMINATED); + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND); + appRecord->RemoveAppDeathRecipient(); + OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + if (pid > 0) { + int32_t result = KillProcessByPid(pid); + if (result < 0) { + APP_LOGE("KillProcessByAbilityToken kill process is fail"); + return; + } + } + appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); + RemoveAppFromRecentListById(appRecord->GetRecordId()); + OnProcessDied(appRecord); +} + +void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId) +{ + APP_LOGI("called add ability stage info time out!"); + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + auto appRecord = appRunningManager_->GetAppRunningRecord(eventId); + if (!appRecord) { + APP_LOGE("appRecord is nullptr"); + return; + } + + appRecord->SetState(ApplicationState::APP_STATE_TERMINATED); + appRecord->RemoveAppDeathRecipient(); + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + KillProcessByPid(pid); + appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); + + OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); + RemoveAppFromRecentListById(appRecord->GetRecordId()); + OnProcessDied(appRecord); +} + +int AppMgrServiceInner::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) +{ + APP_LOGI("compel verify permission"); + message = ENUM_TO_STRING(PERMISSION_NOT_GRANTED); + if (!remoteClientManager_) { + APP_LOGE("remoteClientManager_ is nullptr"); + return ERR_NO_INIT; + } + if (permission.empty()) { + APP_LOGI("permission is empty, PERMISSION_GRANTED"); + message = ENUM_TO_STRING(PERMISSION_GRANTED); + return ERR_OK; + } + if (pid == getpid()) { + APP_LOGI("pid is my pid, PERMISSION_GRANTED"); + message = ENUM_TO_STRING(PERMISSION_GRANTED); + return ERR_OK; + } + int userId = Constants::DEFAULT_USERID; + auto appRecord = GetAppRunningRecordByPid(pid); + if (!appRecord) { + APP_LOGE("app record is nullptr"); + return PERMISSION_NOT_GRANTED; + } + auto bundleName = appRecord->GetBundleName(); + if (appRecord->GetCloneInfo()) { + userId = Constants::C_UESRID; + } + auto bundleMgr = remoteClientManager_->GetBundleManager(); + if (bundleMgr == nullptr) { + APP_LOGE("GetBundleManager fail"); + return ERR_NO_INIT; + } + auto bmsUid = bundleMgr->GetUidByBundleName(bundleName, userId); + if (bmsUid == ROOT_UID || bmsUid == SYSTEM_UID) { + APP_LOGI("uid is root or system, PERMISSION_GRANTED"); + message = ENUM_TO_STRING(PERMISSION_GRANTED); + return ERR_OK; + } + if (bmsUid != uid) { + APP_LOGI("check uid != bms uid, PERMISSION_NOT_GRANTED"); + return PERMISSION_NOT_GRANTED; + } + auto result = bundleMgr->CheckPermissionByUid(bundleName, permission, userId); + if (result != PERMISSION_GRANTED) { + return PERMISSION_NOT_GRANTED; + } + message = ENUM_TO_STRING(PERMISSION_GRANTED); + return ERR_OK; +} + +void AppMgrServiceInner::GetRunningProcessInfoByToken( + const sptr &token, AppExecFwk::RunningProcessInfo &info) +{ + APP_LOGI("%{public}s called", __func__); + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + appRunningManager_->GetRunningProcessInfoByToken(token, info); +} + +void AppMgrServiceInner::LoadResidentProcess() +{ + APP_LOGI("%{public}s called", __func__); + if (!CheckRemoteClient()) { + APP_LOGE("GetBundleManager fail"); + return; + } + + std::vector infos; + auto funRet = remoteClientManager_->GetBundleManager()->QueryKeepAliveBundleInfos(infos); + if (!funRet) { + APP_LOGE("QueryKeepAliveBundleInfos fail!"); + return; + } + + APP_LOGI("Get KeepAlive BundleInfo Size : [%{public}d]", static_cast(infos.size())); + StartResidentProcess(infos, -1); +} + +void AppMgrServiceInner::StartResidentProcess(const std::vector &infos, int restartCount) +{ + APP_LOGI("start resident process"); + if (infos.empty()) { + APP_LOGE("infos is empty!"); + return; + } + + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return; + } + + for (auto &bundle : infos) { + auto processName = + bundle.applicationInfo.process.empty() ? bundle.applicationInfo.bundleName : bundle.applicationInfo.process; + APP_LOGI("processName = [%{public}s]", processName.c_str()); + // Inspection records + auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist( + bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle); + if (appRecord) { + APP_LOGI("processName [%{public}s] Already exists ", processName.c_str()); + continue; + } + StartEmptyResidentProcess(bundle, processName, restartCount); + } +} + +void AppMgrServiceInner::StartEmptyResidentProcess( + const BundleInfo &info, const std::string &processName, int restartCount) +{ + APP_LOGI("start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str()); + if (!CheckRemoteClient() || !appRunningManager_) { + APP_LOGI("Failed to start resident process!"); + return; + } + + auto appInfo = std::make_shared(info.applicationInfo); + auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info); + if (!appRecord) { + APP_LOGE("start process [%{public}s] failed!", processName.c_str()); + return; + } + + StartProcess(appInfo->name, processName, appRecord, appInfo->uid, appInfo->bundleName); + + // If it is empty, the startup failed + if (!appRecord) { + APP_LOGE("start process [%{public}s] failed!", processName.c_str()); + return; + } + + bool isStageBased = false; + bool moduelJson = false; + if (!info.hapModuleInfos.empty()) { + isStageBased = info.hapModuleInfos.back().isStageBasedModel; + moduelJson = info.hapModuleInfos.back().isModuleJson; + } + APP_LOGI("StartEmptyResidentProcess stage:%{public}d moduel:%{public}d size:%{public}d", + isStageBased, moduelJson, (int32_t)info.hapModuleInfos.size()); + appRecord->SetKeepAliveAppState(true, isStageBased); + + if (restartCount > 0) { + APP_LOGI("StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount); + appRecord->SetRestartResidentProcCount(restartCount); + } + + appRecord->SetEventHandler(eventHandler_); + appRecord->AddModules(appInfo, info.hapModuleInfos); + APP_LOGI("StartEmptyResidentProcess oK pid : [%{public}d], ", appRecord->GetPriorityObject()->GetPid()); +} + +bool AppMgrServiceInner::CheckRemoteClient() +{ + if (!remoteClientManager_) { + APP_LOGE("remoteClientManager_ is null"); + return false; + } + + if (!remoteClientManager_->GetSpawnClient()) { + APP_LOGE("appSpawnClient is null"); + return false; + } + + if (!remoteClientManager_->GetBundleManager()) { + APP_LOGE("GetBundleManager fail"); + return false; + } + return true; +} + +void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr appRecord) +{ + if (!CheckRemoteClient() || !appRecord || !appRunningManager_) { + APP_LOGE("restart resident process failed!"); + return; + } + + auto bundleMgr = remoteClientManager_->GetBundleManager(); + BundleInfo bundleInfo; + if (!bundleMgr->GetBundleInfo(appRecord->GetBundleName(), BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo)) { + APP_LOGE("GetBundleInfo fail"); + return; + } + std::vector infos; + infos.emplace_back(bundleInfo); + StartResidentProcess(infos, appRecord->GetRestartResidentProcCount()); +} + +void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const std::string &eventData) +{ + APP_LOGI("%{public}s called, bundle name is %{public}s, event is %{public}s", + __func__, bundleName.c_str(), eventData.c_str()); + Want want; + want.SetAction(eventData); + ElementName element; + element.SetBundleName(bundleName); + want.SetElement(element); + want.SetParam(Constants::USER_ID, 0); + EventFwk::CommonEventData commonData {want}; + EventFwk::CommonEventManager::PublishCommonEvent(commonData); +} + +int32_t AppMgrServiceInner::RegisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + std::lock_guard lockRegister(observerLock_); + if (observer == nullptr) { + APP_LOGE("Observer nullptr"); + return ERR_INVALID_VALUE; + } + if (ObserverExist(observer)) { + APP_LOGE("Observer exist."); + return ERR_INVALID_VALUE; + } + appStateObservers_.push_back(observer); + APP_LOGI("%{public}s appStateObservers_ size:%{public}d", __func__, (int32_t)appStateObservers_.size()); + AddObserverDeathRecipient(observer); + return ERR_OK; +} + +int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + std::lock_guard lockUnregister(observerLock_); + if (observer == nullptr) { + APP_LOGE("Observer nullptr"); + return ERR_INVALID_VALUE; + } + std::vector>::iterator it; + for (it = appStateObservers_.begin(); it != appStateObservers_.end(); ++it) { + if ((*it)->AsObject() == observer->AsObject()) { + appStateObservers_.erase(it); + APP_LOGI("%{public}s appStateObservers_ size:%{public}d", __func__, (int32_t)appStateObservers_.size()); + RemoveObserverDeathRecipient(observer); + return ERR_OK; + } + } + APP_LOGE("Observer not exist."); + return ERR_INVALID_VALUE; +} + +bool AppMgrServiceInner::ObserverExist(const sptr &observer) +{ + if (observer == nullptr) { + APP_LOGE("Observer nullptr"); + return false; + } + for (int i = 0; i < (int)appStateObservers_.size(); i++) { + if (appStateObservers_[i]->AsObject() == observer->AsObject()) { + return true; + } + } + return false; +} + +void AppMgrServiceInner::AddObserverDeathRecipient(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (observer == nullptr || observer->AsObject() == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + auto it = recipientMap_.find(observer->AsObject()); + if (it != recipientMap_.end()) { + APP_LOGE("This death recipient has been added."); + return; + } else { + sptr deathRecipient = new ApplicationStateObserverRecipient( + std::bind(&AppMgrServiceInner::OnObserverDied, this, std::placeholders::_1)); + observer->AsObject()->AddDeathRecipient(deathRecipient); + recipientMap_.emplace(observer->AsObject(), deathRecipient); + } +} + +void AppMgrServiceInner::RemoveObserverDeathRecipient(const sptr &observer) +{ + APP_LOGI("%{public}s begin", __func__); + if (observer == nullptr || observer->AsObject() == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + auto it = recipientMap_.find(observer->AsObject()); + if (it != recipientMap_.end()) { + it->first->RemoveDeathRecipient(it->second); + recipientMap_.erase(it); + return; + } +} + +void AppMgrServiceInner::OnObserverDied(const wptr &remote) +{ + APP_LOGI("%{public}s begin", __func__); + auto object = remote.promote(); + if (object == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + if (eventHandler_) { + auto task = [object, appManager = this]() {appManager->HandleObserverDiedTask(object);}; + eventHandler_->PostTask(task, TASK_ON_CALLBACK_DIED); + } +} + +void AppMgrServiceInner::HandleObserverDiedTask(const sptr &observer) +{ + APP_LOGI("Handle call back died task."); + if (observer == nullptr) { + APP_LOGE("observer nullptr."); + return; + } + sptr object = iface_cast(observer); + UnregisterApplicationStateObserver(object); +} + +int32_t AppMgrServiceInner::GetForegroundApplications(std::vector &list) +{ + APP_LOGI("%{public}s, begin.", __func__); + appRunningManager_->GetForegroundApplications(list); + return ERR_OK; +} + +int AppMgrServiceInner::StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &bundleInfo) +{ + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is nullptr"); + return ERR_INVALID_VALUE; + } + + auto processName = bundleInfo.applicationInfo.process.empty() ? + bundleInfo.applicationInfo.bundleName : bundleInfo.applicationInfo.process; + APP_LOGI("processName = [%{public}s]", processName.c_str()); + + // Inspection records + auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist( + bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo); + if (appRecord) { + APP_LOGI("processName [%{public}s] Already exists ", processName.c_str()); + return ERR_INVALID_VALUE; + } + + return StartEmptyProcess(want, observer, bundleInfo, processName); +} + +int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &info, const std::string &processName) +{ + APP_LOGI("enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str()); + if (!CheckRemoteClient() || !appRunningManager_) { + APP_LOGE("Failed to start the process being tested!"); + return ERR_INVALID_VALUE; + } + + auto appInfo = std::make_shared(info.applicationInfo); + auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info); + if (!appRecord) { + APP_LOGE("start process [%{public}s] failed!", processName.c_str()); + return ERR_INVALID_VALUE; + } + + UserTestRecord testRecord; + testRecord.want = want; + testRecord.observer = observer; + appRecord->SetUserTestInfo(testRecord); + + StartProcess(appInfo->name, processName, appRecord, appInfo->uid, appInfo->bundleName); + + // If it is empty, the startup failed + if (!appRecord) { + APP_LOGE("start process [%{public}s] failed!", processName.c_str()); + return ERR_INVALID_VALUE; + } + + appRecord->SetEventHandler(eventHandler_); + appRecord->AddModules(appInfo, info.hapModuleInfos); + APP_LOGI("StartEmptyProcess OK pid : [%{public}d]", appRecord->GetPriorityObject()->GetPid()); + + return ERR_OK; +} + +void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +{ + APP_LOGD("Start specified ability."); + if (!CheckRemoteClient()) { + return; + } + + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + auto appInfo = std::make_shared(abilityInfo.applicationInfo); + if (!appInfo) { + APP_LOGE("appInfo is nullptr."); + return; + } + + if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo)) { + return; + } + + std::string processName; + auto abilityInfoPtr = std::make_shared(abilityInfo); + if (!abilityInfoPtr) { + APP_LOGE("abilityInfoPtr is nullptr."); + return; + } + MakeProcessName(processName, abilityInfoPtr, appInfo); + + std::vector hapModules; + hapModules.emplace_back(hapModuleInfo); + + std::shared_ptr appRecord; + appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo); + if (!appRecord) { + // new app record + appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo); + if (!appRecord) { + APP_LOGE("start process [%{public}s] failed!", processName.c_str()); + return; + } + + StartProcess(appInfo->name, processName, appRecord, appInfo->uid, appInfo->bundleName); + + appRecord->SetEventHandler(eventHandler_); + appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName); + appRecord->AddModules(appInfo, hapModules); + } else { + APP_LOGD("process is exist"); + appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName); + auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + if (!moduleRecord) { + APP_LOGD("module record is nullptr, add modules"); + appRecord->AddModules(appInfo, hapModules); + appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName); + } else { + APP_LOGD("schedule accept want"); + appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName); + } + } +} + +void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr &response) +{ + if (!response) { + APP_LOGE("response is nullptr, register failed."); + return; + } + + startSpecifiedAbilityResponse_ = response; +} + +void AppMgrServiceInner::ScheduleAcceptWantDone( + const int32_t recordId, const AAFwk::Want &want, const std::string &flag) +{ + APP_LOGD("Schedule accept want done, flag: %{public}s", flag.c_str()); + + auto appRecord = GetAppRunningRecordByAppRecordId(recordId); + if (!appRecord) { + APP_LOGE("Get app record failed."); + return; + } + appRecord->ScheduleAcceptWantDone(); + + if (startSpecifiedAbilityResponse_) { + startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag); + } +} + +void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId) +{} + +void AppMgrServiceInner::UpdateConfiguration(const Configuration &config) +{ + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is null"); + return; + } + + std::vector changeKeyV; + configuration_->CompareDifferent(changeKeyV, config); + int size = changeKeyV.size(); + APP_LOGI("changeKeyV size :%{public}d", size); + if (!changeKeyV.empty()) { + configuration_->Merge(changeKeyV, config); + // all app + appRunningManager_->UpdateConfiguration(config); + } +} + +void AppMgrServiceInner::GetGlobalConfiguration() +{ + if (!configuration_) { + APP_LOGE("configuration_ is null"); + return; + } + // Currently only this interface is known + auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); + APP_LOGI("current global language is : %{public}s", language.c_str()); + configuration_->AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, language); +} + +std::shared_ptr AppMgrServiceInner::GetConfiguration() +{ + return configuration_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_process_manager.cpp b/services/appmgr/src/app_process_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3786b3d8dbb7fed3c77380c61e261d6a922cc8c --- /dev/null +++ b/services/appmgr/src/app_process_manager.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_process_manager.h" +#include + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +AppProcessManager::AppProcessManager() +{} + +AppProcessManager::~AppProcessManager() +{} + +void AppProcessManager::RemoveAppFromRecentList(const std::shared_ptr &appTaskInfo) +{ + if (appTaskInfo) { + recentAppList_.remove(appTaskInfo); + } +} + +void AppProcessManager::ClearRecentAppList() +{ + recentAppList_.clear(); +} + +void AppProcessManager::AddAppToRecentList( + const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId) +{ + auto appTaskInfo = std::make_shared(); + appTaskInfo->SetName(appName); + appTaskInfo->SetProcessName(processName); + appTaskInfo->SetPid(pid); + appTaskInfo->SetRecordId(recordId); + recentAppList_.push_front(appTaskInfo); +} + +const std::list> &AppProcessManager::GetRecentAppList() const +{ + return recentAppList_; +} + +void AppProcessManager::PushAppFront(const int32_t recordId) +{ + auto appTaskInfo = GetAppTaskInfoById(recordId); + if (appTaskInfo) { + recentAppList_.remove(appTaskInfo); + recentAppList_.push_front(appTaskInfo); + } +} + +void AppProcessManager::RemoveAppFromRecentListById(const int32_t recordId) +{ + auto appTaskInfo = GetAppTaskInfoById(recordId); + if (appTaskInfo) { + recentAppList_.remove(appTaskInfo); + } +} + +const std::shared_ptr AppProcessManager::GetAppTaskInfoById(const int32_t recordId) const +{ + const auto &iter = std::find_if(recentAppList_.begin(), recentAppList_.end(), [&recordId](const auto &appTaskInfo) { + return appTaskInfo ? (appTaskInfo->GetRecordId() == recordId) : false; + }); + return (iter == recentAppList_.end()) ? nullptr : (*iter); +} + +std::shared_ptr AppProcessManager::GetAppTaskInfoByProcessName( + const std::string &appName, const std::string &processName) const +{ + const auto &iter = + std::find_if(recentAppList_.begin(), recentAppList_.end(), [&appName, &processName](const auto &appTaskInfo) { + return ((appTaskInfo->GetName() == appName) && (appTaskInfo->GetProcessName() == processName)); + }); + return ((iter == recentAppList_.end()) ? nullptr : *iter); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db78229fbcebcf538aaf86d07c1ab8a593253b9c --- /dev/null +++ b/services/appmgr/src/app_running_manager.cpp @@ -0,0 +1,465 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_running_manager.h" + +#include "datetime_ex.h" +#include "iremote_object.h" + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "os_account_manager.h" +#include "perf_profile.h" + +namespace OHOS { +namespace AppExecFwk { +AppRunningManager::AppRunningManager() +{} +AppRunningManager::~AppRunningManager() +{} + +std::shared_ptr AppRunningManager::CreateAppRunningRecord( + const std::shared_ptr &appInfo, const std::string &processName, const BundleInfo &bundleInfo) +{ + std::lock_guard guard(lock_); + if (!appInfo) { + APP_LOGE("param error"); + return nullptr; + } + + if (processName.empty()) { + APP_LOGE("processName error"); + return nullptr; + } + + auto recordId = AppRecordId::Create(); + auto appRecord = std::make_shared(appInfo, recordId, processName); + if (!appRecord) { + return nullptr; + } + + std::regex rule("[a-zA-Z.]+[-_#]{1}"); + std::string signCode; + ClipStringContent(rule, bundleInfo.appId, signCode); + + APP_LOGI("Create processName : %{public}s | recordId : %{public}d | signCode : %{public}s", + processName.c_str(), recordId, signCode.c_str()); + appRecord->SetSignCode(signCode); + appRecord->SetJointUserId(bundleInfo.jointUserId); + appRunningRecordMap_.emplace(recordId, appRecord); + return appRecord; +} + +std::shared_ptr AppRunningManager::CheckAppRunningRecordIsExist(const std::string &appName, + const std::string &processName, const int uid, const BundleInfo &bundleInfo) +{ + APP_LOGI("CheckAppRunningRecordIsExist appName : %{public}s | processName : %{public}s | uid : %{public}d", + appName.c_str(), processName.c_str(), uid); + std::lock_guard guard(lock_); + + std::regex rule("[a-zA-Z.]+[-_#]{1}"); + std::string signCode; + auto jointUserId = bundleInfo.jointUserId; + APP_LOGI("jointUserId : %{public}s", jointUserId.c_str()); + ClipStringContent(rule, bundleInfo.appId, signCode); + + auto FindSameProcess = [signCode, processName, jointUserId](const auto &pair) { + return ((pair.second->GetSignCode() == signCode) && + (pair.second->GetProcessName() == processName) && + (pair.second->GetJointUserId() == jointUserId) && + !(pair.second->IsTerminating())); + }; + + // If it is not empty, look for whether it can come in the same process + if (jointUserId.empty()) { + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + APP_LOGI("appRecord->GetProcessName() : %{public}s", appRecord->GetProcessName().c_str()); + if (appRecord && appRecord->GetProcessName() == processName && !(appRecord->IsTerminating())) { + auto appInfoList = appRecord->GetAppInfoList(); + APP_LOGI("appInfoList : %{public}zu", appInfoList.size()); + auto isExist = [&appName, &uid](const std::shared_ptr &appInfo) { + APP_LOGI("appInfo->name : %{public}s", appInfo->name.c_str()); + return appInfo->name == appName && appInfo->uid == uid; + }; + auto appInfoIter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist); + if (appInfoIter != appInfoList.end()) { + return appRecord; + } + } + } + return nullptr; + } + + auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), FindSameProcess); + return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second); +} + +std::shared_ptr AppRunningManager::GetAppRunningRecordByPid(const pid_t pid) +{ + std::lock_guard guard(lock_); + auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { + return pair.second->GetPriorityObject()->GetPid() == pid; + }); + return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second); +} + +std::shared_ptr AppRunningManager::GetAppRunningRecordByAbilityToken( + const sptr &abilityToken) +{ + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord && appRecord->GetAbilityRunningRecordByToken(abilityToken)) { + APP_LOGI("appRecord is exit"); + return appRecord; + } + } + return nullptr; +} + +bool AppRunningManager::ProcessExitByBundleName(const std::string &bundleName, std::list &pids) +{ + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + // condition [!appRecord->IsKeepAliveApp()] Is to not kill the resident process. + // Before using this method, consider whether you need. + if (appRecord && !appRecord->IsKeepAliveApp()) { + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + auto appInfoList = appRecord->GetAppInfoList(); + auto isExist = [&bundleName](const std::shared_ptr &appInfo) { + return appInfo->bundleName == bundleName; + }; + auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist); + if (iter != appInfoList.end() && pid > 0) { + pids.push_back(pid); + appRecord->ScheduleProcessSecurityExit(); + } + } + } + + return !pids.empty(); +} + +bool AppRunningManager::GetPidsByUserId(int32_t userId, std::list &pids) +{ + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord) { + int32_t id = -1; + if ((AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(appRecord->GetUid(), id) == 0) && + (id == userId)) { + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + if (pid > 0) { + pids.push_back(pid); + appRecord->ScheduleProcessSecurityExit(); + } + } + } + } + + return (pids.empty() ? false : true); +} + +bool AppRunningManager::ProcessExitByBundleNameAndUid( + const std::string &bundleName, const int uid, std::list &pids) +{ + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord) { + auto appInfoList = appRecord->GetAppInfoList(); + auto isExist = [&bundleName, &uid](const std::shared_ptr &appInfo) { + return appInfo->bundleName == bundleName && appInfo->uid == uid; + }; + auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist); + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + if (iter != appInfoList.end() && pid > 0) { + pids.push_back(pid); + appRecord->ScheduleProcessSecurityExit(); + } + } + } + + return (pids.empty() ? false : true); +} + +std::shared_ptr AppRunningManager::OnRemoteDied(const wptr &remote) +{ + std::lock_guard guard(lock_); + if (remote == nullptr) { + APP_LOGE("remote is null"); + return nullptr; + } + sptr object = remote.promote(); + if (!object) { + APP_LOGE("object is null"); + return nullptr; + } + const auto &iter = + std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&object](const auto &pair) { + if (pair.second && pair.second->GetApplicationClient() != nullptr) { + return pair.second->GetApplicationClient()->AsObject() == object; + } + return false; + }); + if (iter != appRunningRecordMap_.end()) { + auto appRecord = iter->second; + appRecord->SetApplicationClient(nullptr); + appRunningRecordMap_.erase(iter); + if (appRecord) { + return appRecord; + } + } + return nullptr; +} + +const std::map> &AppRunningManager::GetAppRunningRecordMap() +{ + std::lock_guard guard(lock_); + return appRunningRecordMap_; +} + +void AppRunningManager::RemoveAppRunningRecordById(const int32_t recordId) +{ + std::lock_guard guard(lock_); + appRunningRecordMap_.erase(recordId); +} + +void AppRunningManager::ClearAppRunningRecordMap() +{ + std::lock_guard guard(lock_); + appRunningRecordMap_.clear(); +} + +void AppRunningManager::HandleTerminateTimeOut(int64_t eventId) +{ + APP_LOGI("Handle terminate timeout."); + auto abilityRecord = GetAbilityRunningRecord(eventId); + if (!abilityRecord) { + APP_LOGE("abilityRecord is nullptr."); + return; + } + auto abilityToken = abilityRecord->GetToken(); + auto appRecord = GetTerminatingAppRunningRecord(abilityToken); + if (!appRecord) { + APP_LOGE("appRecord is nullptr."); + return; + } + appRecord->AbilityTerminated(abilityToken); +} + +std::shared_ptr AppRunningManager::GetTerminatingAppRunningRecord( + const sptr &abilityToken) +{ + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord && appRecord->GetAbilityByTerminateLists(abilityToken)) { + return appRecord; + } + } + return nullptr; +} + +std::shared_ptr AppRunningManager::GetAbilityRunningRecord(const int64_t eventId) +{ + APP_LOGI("Get ability running record by eventId."); + std::lock_guard guard(lock_); + for (auto &item : appRunningRecordMap_) { + if (item.second) { + auto abilityRecord = item.second->GetAbilityRunningRecord(eventId); + if (abilityRecord) { + return abilityRecord; + } + } + } + return nullptr; +} + +std::shared_ptr AppRunningManager::GetAppRunningRecord(const int64_t eventId) +{ + APP_LOGI("Get app running record by eventId."); + std::lock_guard guard(lock_); + auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&eventId](const auto &pair) { + return pair.second->GetEventId() == eventId; + }); + return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second); +} + +void AppRunningManager::HandleAbilityAttachTimeOut(const sptr &token) +{ + APP_LOGI("Handle ability attach timeOut."); + if (token == nullptr) { + APP_LOGE("token is nullptr."); + return; + } + + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("appRecord is nullptr."); + return; + } + + std::shared_ptr abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + if (abilityRecord) { + abilityRecord->SetTerminating(); + } + + if (appRecord->IsLastAbilityRecord(token)) { + appRecord->SetTerminating(); + } + + appRecord->TerminateAbility(token, true); +} + +void AppRunningManager::PrepareTerminate(const sptr &token) +{ + APP_LOGI("Prepare terminate."); + if (token == nullptr) { + APP_LOGE("token is nullptr."); + return; + } + + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("appRecord is nullptr."); + return; + } + + if (appRecord->IsLastAbilityRecord(token)) { + appRecord->SetTerminating(); + } +} + +void AppRunningManager::TerminateAbility(const sptr &token) +{ + APP_LOGI("Terminate ability."); + if (!token) { + APP_LOGE("token is nullptr."); + return; + } + + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("appRecord is nullptr."); + return; + } + + if (appRecord->IsLastAbilityRecord(token) && !appRecord->IsKeepAliveApp()) { + appRecord->SetTerminating(); + } + + appRecord->TerminateAbility(token, false); +} + +void AppRunningManager::GetRunningProcessInfoByToken( + const sptr &token, AppExecFwk::RunningProcessInfo &info) +{ + std::lock_guard guard(lock_); + auto appRecord = GetAppRunningRecordByAbilityToken(token); + if (!appRecord) { + APP_LOGE("appRecord is nullptr"); + return; + } + + info.processName_ = appRecord->GetName(); + info.pid_ = appRecord->GetPriorityObject()->GetPid(); + info.uid_ = appRecord->GetUid(); + info.bundleNames.emplace_back(appRecord->GetBundleName()); +} + +void AppRunningManager::ClipStringContent(const std::regex &re, const std::string &sorce, std::string &afferCutStr) +{ + std::smatch basket; + if (std::regex_search(sorce, basket, re)) { + APP_LOGI("prefix str: [%{public}s]", basket.prefix().str().c_str()); + APP_LOGI("suffix str: [%{public}s]", basket.suffix().str().c_str()); + afferCutStr = basket.prefix().str() + basket.suffix().str(); + } +} + +void AppRunningManager::GetForegroundApplications(std::vector &list) +{ + APP_LOGI("%{public}s, begin.", __func__); + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) { + AppStateData appData; + appData.bundleName = appRecord->GetBundleName(); + appData.uid = appRecord->GetUid(); + appData.state = static_cast(ApplicationState::APP_STATE_FOREGROUND); + list.push_back(appData); + APP_LOGI("%{public}s, bundleName:%{public}s", __func__, appData.bundleName.c_str()); + } + } +} + +void AppRunningManager::HandleAddAbilityStageTimeOut(const int64_t eventId) +{ + APP_LOGD("Handle add ability stage timeout."); + auto abilityRecord = GetAbilityRunningRecord(eventId); + if (!abilityRecord) { + APP_LOGE("abilityRecord is nullptr"); + return; + } + + auto abilityToken = abilityRecord->GetToken(); + auto appRecord = GetTerminatingAppRunningRecord(abilityToken); + if (!appRecord) { + APP_LOGE("appRecord is nullptr"); + return; + } + + appRecord->ScheduleProcessSecurityExit(); +} + +void AppRunningManager::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId) +{ + APP_LOGD("Handle receive multi instances timeout."); + auto abilityRecord = GetAbilityRunningRecord(eventId); + if (!abilityRecord) { + APP_LOGE("abilityRecord is nullptr"); + return; + } + + auto abilityToken = abilityRecord->GetToken(); + auto appRecord = GetTerminatingAppRunningRecord(abilityToken); + if (!appRecord) { + APP_LOGE("appRecord is nullptr"); + return; + } + + appRecord->ScheduleProcessSecurityExit(); +} + +void AppRunningManager::UpdateConfiguration(const Configuration &config) +{ + APP_LOGI("call %{public}s", __func__); + std::lock_guard guard(lock_); + APP_LOGI("current app size %{public}d", static_cast(appRunningRecordMap_.size())); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord) { + APP_LOGI("Notification app [%{public}s]", appRecord->GetName().c_str()); + appRecord->UpdateConfiguration(config); + } + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d03d9c331d9554fc996f0112d96e2cb5c0251c2 --- /dev/null +++ b/services/appmgr/src/app_running_record.cpp @@ -0,0 +1,911 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_running_record.h" +#include "app_log_wrapper.h" +#include "app_mgr_service_inner.h" +#include "bytrace.h" + +namespace OHOS { +namespace AppExecFwk { +int64_t AppRunningRecord::appEventId_ = 0; +AppRunningRecord::AppRunningRecord( + const std::shared_ptr &info, const int32_t recordId, const std::string &processName) + : appRecordId_(recordId), processName_(processName) +{ + if (info) { + mainBundleName_ = info->bundleName; + isLauncherApp_ = info->isLauncherApp; + isClonedApp_ = info->isCloned; + mainAppName_ = info->name; + } +} + +void AppRunningRecord::SetApplicationClient(const sptr &thread) +{ + if (!appLifeCycleDeal_) { + appLifeCycleDeal_ = std::make_shared(); + } + appLifeCycleDeal_->SetApplicationClient(thread); + + auto moduleRecordList = GetAllModuleRecord(); + if (moduleRecordList.empty()) { + APP_LOGE("moduleRecordList is empty"); + return; + } + for (const auto &moduleRecord : moduleRecordList) { + moduleRecord->SetApplicationClient(appLifeCycleDeal_); + } +} + +const std::string &AppRunningRecord::GetBundleName() const +{ + return mainBundleName_; +} + +bool AppRunningRecord::IsLauncherApp() const +{ + return isLauncherApp_; +} + +int32_t AppRunningRecord::GetRecordId() const +{ + return appRecordId_; +} + +const std::string &AppRunningRecord::GetName() const +{ + return mainAppName_; +} + +bool AppRunningRecord::GetCloneInfo() const +{ + return isClonedApp_; +} + +const std::string &AppRunningRecord::GetSignCode() const +{ + return signCode_; +} + +void AppRunningRecord::SetSignCode(const std::string &signCode) +{ + signCode_ = signCode; +} + +const std::string &AppRunningRecord::GetJointUserId() const +{ + return jointUserId_; +} + +void AppRunningRecord::SetJointUserId(const std::string &jointUserId) +{ + jointUserId_ = jointUserId; +} + +const std::string &AppRunningRecord::GetProcessName() const +{ + return processName_; +} + +int32_t AppRunningRecord::GetUid() const +{ + return mainUid_; +} + +void AppRunningRecord::SetUid(const int32_t uid) +{ + mainUid_ = uid; +} + +ApplicationState AppRunningRecord::GetState() const +{ + return curState_; +} + +void AppRunningRecord::SetState(const ApplicationState state) +{ + if (state >= ApplicationState::APP_STATE_END) { + APP_LOGE("Invalid application state"); + return; + } + curState_ = state; +} + +const std::list> AppRunningRecord::GetAppInfoList() +{ + std::list> appInfoList; + for (const auto &item : appInfos_) { + appInfoList.push_back(item.second); + } + return appInfoList; +} + +const std::map, std::shared_ptr> AppRunningRecord::GetAbilities() +{ + std::map, std::shared_ptr> abilitysMap; + auto moduleRecordList = GetAllModuleRecord(); + for (const auto &moduleRecord : moduleRecordList) { + auto abilities = moduleRecord->GetAbilities(); + abilitysMap.insert(abilities.begin(), abilities.end()); + } + return abilitysMap; +} + +std::map>> &AppRunningRecord::GetModules() +{ + return hapModules_; +} + +sptr AppRunningRecord::GetApplicationClient() const +{ + return (appLifeCycleDeal_ ? appLifeCycleDeal_->GetApplicationClient() : nullptr); +} + +std::shared_ptr AppRunningRecord::GetAbilityRunningRecord(const std::string &abilityName) const +{ + APP_LOGI("Get ability running record by ability name."); + auto moduleRecordList = GetAllModuleRecord(); + for (const auto &moduleRecord : moduleRecordList) { + auto abilityRecord = moduleRecord->GetAbilityRunningRecord(abilityName); + if (abilityRecord) { + return abilityRecord; + } + } + + return nullptr; +} + +std::shared_ptr AppRunningRecord::GetAbilityRunningRecord(const int64_t eventId) const +{ + APP_LOGI("Get ability running record by eventId."); + auto moduleRecordList = GetAllModuleRecord(); + for (const auto &moduleRecord : moduleRecordList) { + auto abilityRecord = moduleRecord->GetAbilityRunningRecord(eventId); + if (abilityRecord) { + return abilityRecord; + } + } + + return nullptr; +} + +void AppRunningRecord::ClearAbility(const std::shared_ptr &record) +{ + if (!record) { + APP_LOGE("Param record is null"); + return; + } + + auto moduleRecord = GetModuleRunningRecordByToken(record->GetToken()); + if (!moduleRecord) { + APP_LOGE("moduleRecord is not exit"); + return; + } + + moduleRecord->ClearAbility(record); + + if (moduleRecord->GetAbilities().empty()) { + RemoveModuleRecord(moduleRecord); + } +} + +void AppRunningRecord::RemoveModuleRecord(const std::shared_ptr &moudleRecord) +{ + APP_LOGI("Remove module record."); + + for (auto &item : hapModules_) { + auto iter = std::find_if(item.second.begin(), + item.second.end(), + [&moudleRecord](const std::shared_ptr &record) { return moudleRecord == record; }); + if (iter != item.second.end()) { + iter = item.second.erase(iter); + if (item.second.empty()) { + hapModules_.erase(item.first); + appInfos_.erase(item.first); + } + return; + } + } +} + +void AppRunningRecord::ForceKillApp([[maybe_unused]] const std::string &reason) const +{} + +void AppRunningRecord::ScheduleAppCrash([[maybe_unused]] const std::string &description) const +{} + +void AppRunningRecord::LaunchApplication(const Configuration &config) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } + if (!appLifeCycleDeal_->GetApplicationClient()) { + APP_LOGE("appThread is null"); + return; + } + AppLaunchData launchData; + auto moduleRecords = appInfos_.find(mainBundleName_); + if (moduleRecords != appInfos_.end()) { + launchData.SetApplicationInfo(*(moduleRecords->second)); + } + ProcessInfo processInfo(processName_, GetPriorityObject()->GetPid()); + launchData.SetProcessInfo(processInfo); + launchData.SetRecordId(appRecordId_); + launchData.SetUId(mainUid_); + launchData.SetUserTestInfo(userTestRecord_); + APP_LOGI("ScheduleLaunchApplication app:%{public}s", GetName().c_str()); + appLifeCycleDeal_->LaunchApplication(launchData, config); +} + +void AppRunningRecord::AddAbilityStage() +{ + if (!isNewMission_) { + APP_LOGI("Current version than supports !"); + return; + } + HapModuleInfo abilityStage; + if (GetTheModuleInfoNeedToUpdated(mainBundleName_, abilityStage)) { + SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT); + APP_LOGI("Current Informed module : [%{public}s] | bundle : [%{public}s]", + abilityStage.moduleName.c_str(), mainBundleName_.c_str()); + appLifeCycleDeal_->AddAbilityStage(abilityStage); + return; + } + + APP_LOGI("The current process[%{public}s] is updated", processName_.c_str()); +} + +void AppRunningRecord::AddAbilityStageBySpecifiedAbility(const std::string &bundleName) +{ + HapModuleInfo hapModuleInfo; + if (GetTheModuleInfoNeedToUpdated(bundleName, hapModuleInfo)) { + SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT); + appLifeCycleDeal_->AddAbilityStage(hapModuleInfo); + } +} + +void AppRunningRecord::AddAbilityStageDone() +{ + APP_LOGI("Add ability stage done. bundle %{public}s and eventId %{public}d", mainBundleName_.c_str(), + static_cast(eventId_)); + eventHandler_->RemoveEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, eventId_); + // Should proceed to the next notification + + if (isSpecifiedAbility_) { + ScheduleAcceptWant(moduleName_); + return; + } + + AddAbilityStage(); +} + +void AppRunningRecord::LaunchAbility(const std::shared_ptr &ability) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } + if (!ability || !ability->GetToken()) { + APP_LOGE("abilityRecord or abilityToken is nullptr."); + return; + } + + auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken()); + if (!moduleRecord) { + APP_LOGE("moduleRecord is nullptr"); + return; + } + + moduleRecord->LaunchAbility(ability); +} + +void AppRunningRecord::ScheduleTerminate() +{ + SendEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleTerminate(); + } +} + +void AppRunningRecord::LaunchPendingAbilities() +{ + APP_LOGI("Launch pending abilities."); + + auto moduleRecordList = GetAllModuleRecord(); + if (moduleRecordList.empty()) { + APP_LOGE("moduleRecordList is empty"); + return; + } + for (const auto &moduleRecord : moduleRecordList) { + moduleRecord->SetApplicationClient(appLifeCycleDeal_); + moduleRecord->LaunchPendingAbilities(); + } +} +void AppRunningRecord::ScheduleForegroundRunning() +{ + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleForegroundRunning(); + } +} + +void AppRunningRecord::ScheduleBackgroundRunning() +{ + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleBackgroundRunning(); + } +} + +void AppRunningRecord::ScheduleProcessSecurityExit() +{ + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleProcessSecurityExit(); + } +} + +void AppRunningRecord::ScheduleTrimMemory() +{ + if (appLifeCycleDeal_ && priorityObject_) { + appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel()); + } +} + +void AppRunningRecord::LowMemoryWarning() +{ + if (appLifeCycleDeal_) { + appLifeCycleDeal_->LowMemoryWarning(); + } +} + +void AppRunningRecord::AddModules( + const std::shared_ptr &appInfo, const std::vector &moduleInfos) +{ + APP_LOGI("Add modules"); + + if (moduleInfos.empty()) { + APP_LOGI("moduleInfos is empty."); + return; + } + + for (auto &iter : moduleInfos) { + AddModule(appInfo, nullptr, nullptr, iter); + } +} + +void AppRunningRecord::AddModule(const std::shared_ptr &appInfo, + const std::shared_ptr &abilityInfo, const sptr &token, + const HapModuleInfo &hapModuleInfo) +{ + APP_LOGI("Add module."); + + if (!appInfo) { + APP_LOGE("appInfo is null"); + return; + } + + std::shared_ptr moduleRecord; + std::vector> moduleList; + + auto initModuleRecord = [=](const std::shared_ptr &moduleRecord) { + moduleRecord->Init(hapModuleInfo); + moduleRecord->SetAppMgrServiceInner(appMgrServiceInner_); + moduleRecord->SetApplicationClient(appLifeCycleDeal_); + }; + + const auto &iter = hapModules_.find(appInfo->bundleName); + if (iter != hapModules_.end()) { + moduleRecord = GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + if (!moduleRecord) { + moduleRecord = std::make_shared(appInfo, eventHandler_); + iter->second.push_back(moduleRecord); + initModuleRecord(moduleRecord); + } + } else { + moduleRecord = std::make_shared(appInfo, eventHandler_); + moduleList.push_back(moduleRecord); + hapModules_.emplace(appInfo->bundleName, moduleList); + appInfos_.emplace(appInfo->bundleName, appInfo); + initModuleRecord(moduleRecord); + } + + if (!abilityInfo || !token) { + APP_LOGE("abilityinfo or token is nullptr"); + return; + } + moduleRecord->AddAbility(token, abilityInfo); + + return; +} + +std::shared_ptr AppRunningRecord::GetModuleRecordByModuleName( + const std::string bundleName, const std::string &moduleName) +{ + APP_LOGI("Get module record by module name."); + auto moduleRecords = hapModules_.find(bundleName); + if (moduleRecords != hapModules_.end()) { + for (auto &iter : moduleRecords->second) { + if (iter->GetModuleName() == moduleName) { + return iter; + } + } + } + + return nullptr; +} + +void AppRunningRecord::StateChangedNotifyObserver( + const std::shared_ptr &ability, const int32_t state, bool isAbility) +{ + if (!ability) { + APP_LOGE("ability is null"); + return; + } + AbilityStateData abilityStateData; + abilityStateData.bundleName = ability->GetAbilityInfo()->applicationInfo.bundleName; + abilityStateData.abilityName = ability->GetName(); + abilityStateData.pid = GetPriorityObject()->GetPid(); + abilityStateData.abilityState = state; + abilityStateData.uid = ability->GetAbilityInfo()->applicationInfo.uid; + abilityStateData.token = ability->GetToken(); + + if (isAbility && ability->GetAbilityInfo() != nullptr && + ability->GetAbilityInfo()->type == AbilityType::EXTENSION) { + APP_LOGI("extension type, not notify any more."); + return; + } + auto serviceInner = appMgrServiceInner_.lock(); + if (serviceInner) { + serviceInner->StateChangedNotifyObserver(abilityStateData, isAbility); + } +} + +std::shared_ptr AppRunningRecord::GetModuleRunningRecordByToken( + const sptr &token) const +{ + if (!token) { + APP_LOGE("token is null"); + return nullptr; + } + + auto moduleRecordList = GetAllModuleRecord(); + for (const auto &moduleRecord : moduleRecordList) { + if (moduleRecord && moduleRecord->GetAbilityRunningRecordByToken(token)) { + return moduleRecord; + } + } + + return nullptr; +} + +std::shared_ptr AppRunningRecord::GetModuleRunningRecordByTerminateLists( + const sptr &token) const +{ + if (!token) { + APP_LOGE("token is null"); + return nullptr; + } + + auto moduleRecordList = GetAllModuleRecord(); + for (const auto &moduleRecord : moduleRecordList) { + if (moduleRecord && moduleRecord->GetAbilityByTerminateLists(token)) { + return moduleRecord; + } + } + + return nullptr; +} + +std::shared_ptr AppRunningRecord::GetAbilityRunningRecordByToken( + const sptr &token) const +{ + auto moduleRecord = GetModuleRunningRecordByToken(token); + if (!moduleRecord) { + APP_LOGE("moduleRecord is not exit"); + return nullptr; + } + return moduleRecord->GetAbilityRunningRecordByToken(token); +} + +std::shared_ptr AppRunningRecord::GetAbilityByTerminateLists( + const sptr &token) const +{ + auto moduleRecord = GetModuleRunningRecordByTerminateLists(token); + if (!moduleRecord) { + APP_LOGE("moduleRecord is not exit"); + return nullptr; + } + return moduleRecord->GetAbilityByTerminateLists(token); +} + +void AppRunningRecord::UpdateAbilityState(const sptr &token, const AbilityState state) +{ + APP_LOGI("state is :%{public}d", static_cast(state)); + auto abilityRecord = GetAbilityRunningRecordByToken(token); + if (!abilityRecord) { + APP_LOGE("can not find ability record"); + return; + } + if (state == abilityRecord->GetState()) { + APP_LOGE("current state is already, no need update"); + return; + } + + if (state == AbilityState::ABILITY_STATE_FOREGROUND) { + AbilityForeground(abilityRecord); + } else if (state == AbilityState::ABILITY_STATE_BACKGROUND) { + AbilityBackground(abilityRecord); + } else { + APP_LOGW("wrong state"); + } +} + +void AppRunningRecord::AbilityForeground(const std::shared_ptr &ability) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!ability) { + APP_LOGE("ability is null"); + return; + } + AbilityState curAbilityState = ability->GetState(); + if (curAbilityState != AbilityState::ABILITY_STATE_READY && + curAbilityState != AbilityState::ABILITY_STATE_BACKGROUND) { + APP_LOGE("ability state(%{public}d) error", static_cast(curAbilityState)); + return; + } + + // We need schedule application to foregrounded when current application state is ready or background running. + if (curState_ == ApplicationState::APP_STATE_READY || curState_ == ApplicationState::APP_STATE_BACKGROUND) { + if (foregroundingAbilityTokens_.empty()) { + ScheduleForegroundRunning(); + } + foregroundingAbilityTokens_.push_back(ability->GetToken()); + return; + } else if (curState_ == ApplicationState::APP_STATE_FOREGROUND) { + // Just change ability to foreground if current application state is foreground. + auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken()); + moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND); + StateChangedNotifyObserver(ability, static_cast(AbilityState::ABILITY_STATE_FOREGROUND), true); + auto serviceInner = appMgrServiceInner_.lock(); + if (serviceInner) { + serviceInner->OnAppStateChanged(shared_from_this(), curState_); + } + } else { + APP_LOGW("wrong application state"); + } +} + +void AppRunningRecord::AbilityBackground(const std::shared_ptr &ability) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!ability) { + APP_LOGE("ability is null"); + return; + } + if (ability->GetState() != AbilityState::ABILITY_STATE_FOREGROUND) { + APP_LOGE("ability state is not foreground"); + return; + } + + // First change ability to backgrounded. + auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken()); + moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BACKGROUND); + StateChangedNotifyObserver(ability, static_cast(AbilityState::ABILITY_STATE_BACKGROUND), true); + if (curState_ == ApplicationState::APP_STATE_FOREGROUND) { + int32_t foregroundSize = 0; + auto abilitysMap = GetAbilities(); + for (const auto &item : abilitysMap) { + const auto &abilityRecord = item.second; + if (abilityRecord && abilityRecord->GetState() == AbilityState::ABILITY_STATE_FOREGROUND) { + foregroundSize++; + break; + } + } + + // Then schedule application background when all ability is not foreground. + if (foregroundSize == 0) { + ScheduleBackgroundRunning(); + } + } else { + APP_LOGW("wrong application state"); + } +} + +void AppRunningRecord::PopForegroundingAbilityTokens() +{ + APP_LOGI("size:%{public}d", static_cast(foregroundingAbilityTokens_.size())); + while (!foregroundingAbilityTokens_.empty()) { + const auto &token = foregroundingAbilityTokens_.front(); + auto ability = GetAbilityRunningRecordByToken(token); + auto moduleRecord = GetModuleRunningRecordByToken(token); + moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND); + StateChangedNotifyObserver(ability, static_cast(AbilityState::ABILITY_STATE_FOREGROUND), true); + foregroundingAbilityTokens_.pop_front(); + } +} + +void AppRunningRecord::TerminateAbility(const sptr &token, const bool isForce) +{ + APP_LOGI("Terminate ability, isForce: %{public}d", static_cast(isForce)); + + auto moduleRecord = GetModuleRunningRecordByToken(token); + if (!moduleRecord) { + APP_LOGE("can not find module record"); + return; + } + + auto abilityRecord = GetAbilityRunningRecordByToken(token); + StateChangedNotifyObserver(abilityRecord, static_cast(AbilityState::ABILITY_STATE_TERMINATED), true); + moduleRecord->TerminateAbility(token, isForce); + APP_LOGI("AppRunningRecord::TerminateAbility end"); +} + +void AppRunningRecord::AbilityTerminated(const sptr &token) +{ + APP_LOGI("Ability terminated."); + auto moduleRecord = GetModuleRunningRecordByTerminateLists(token); + if (!moduleRecord) { + APP_LOGE("Can not find module record"); + return; + } + moduleRecord->AbilityTerminated(token); + + if (moduleRecord->GetAbilities().empty()) { + RemoveModuleRecord(moduleRecord); + } + + auto moduleRecordList = GetAllModuleRecord(); + if (moduleRecordList.empty()) { + ScheduleTerminate(); + } +} + +std::list> AppRunningRecord::GetAllModuleRecord() const +{ + std::list> moduleRecordList; + for (const auto &item : hapModules_) { + for (const auto &list : item.second) { + moduleRecordList.push_back(list); + } + } + APP_LOGI("GetAllModuleRecord size:%{public}zu", moduleRecordList.size()); + return moduleRecordList; +} + +void AppRunningRecord::RegisterAppDeathRecipient() const +{ + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } + if (!appLifeCycleDeal_->GetApplicationClient()) { + APP_LOGE("appThread is nullptr"); + return; + } + auto object = appLifeCycleDeal_->GetApplicationClient()->AsObject(); + if (object) { + object->AddDeathRecipient(appDeathRecipient_); + } +} + +void AppRunningRecord::RemoveAppDeathRecipient() const +{ + if (appLifeCycleDeal_ == nullptr) { + APP_LOGE("appLifeCycleDeal_ is null"); + return; + } + if (!appLifeCycleDeal_->GetApplicationClient()) { + APP_LOGE("appThread is nullptr."); + return; + } + auto object = appLifeCycleDeal_->GetApplicationClient()->AsObject(); + if (object) { + object->RemoveDeathRecipient(appDeathRecipient_); + } +} + +void AppRunningRecord::SetAppMgrServiceInner(const std::weak_ptr &inner) +{ + appMgrServiceInner_ = inner; + + auto moduleRecordList = GetAllModuleRecord(); + if (moduleRecordList.empty()) { + APP_LOGE("moduleRecordList is empty"); + return; + } + + for (const auto &moduleRecord : moduleRecordList) { + moduleRecord->SetAppMgrServiceInner(appMgrServiceInner_); + } +} + +void AppRunningRecord::SetAppDeathRecipient(const sptr &appDeathRecipient) +{ + appDeathRecipient_ = appDeathRecipient; +} + +std::shared_ptr AppRunningRecord::GetPriorityObject() +{ + if (!priorityObject_) { + priorityObject_ = std::make_shared(); + } + + return priorityObject_; +} + +void AppRunningRecord::SendEvent(uint32_t msg, int64_t timeOut) +{ + if (!eventHandler_) { + APP_LOGE("eventHandler_ is nullptr"); + return; + } + + appEventId_++; + eventId_ = appEventId_; + APP_LOGI("eventId %{public}d", static_cast(eventId_)); + eventHandler_->SendEvent(msg, appEventId_, timeOut); +} + +int64_t AppRunningRecord::GetEventId() const +{ + return eventId_; +} + +void AppRunningRecord::SetEventHandler(const std::shared_ptr &handler) +{ + eventHandler_ = handler; +} + +bool AppRunningRecord::IsLastAbilityRecord(const sptr &token) +{ + if (!token) { + APP_LOGE("token is nullptr"); + return false; + } + + auto moduleRecord = GetModuleRunningRecordByToken(token); + if (!moduleRecord) { + APP_LOGE("can not find module record"); + return false; + } + + auto moduleRecordList = GetAllModuleRecord(); + if (moduleRecordList.size() == 1) { + return moduleRecord->IsLastAbilityRecord(token); + } + + return false; +} + +void AppRunningRecord::SetTerminating() +{ + isTerminating = true; +} + +bool AppRunningRecord::IsTerminating() +{ + return isTerminating; +} + +bool AppRunningRecord::IsKeepAliveApp() const +{ + return isKeepAliveApp_; +} + +void AppRunningRecord::SetKeepAliveAppState(bool isKeepAlive, bool isNewMission) +{ + isKeepAliveApp_ = isKeepAlive; + isNewMission_ = isNewMission; +} + +bool AppRunningRecord::GetTheModuleInfoNeedToUpdated(const std::string bundleName, HapModuleInfo &info) +{ + bool result = false; + auto moduleInfoVectorIter = hapModules_.find(bundleName); + if (moduleInfoVectorIter == hapModules_.end() || moduleInfoVectorIter->second.empty()) { + return result; + } + auto findCondition = [](const std::shared_ptr &record) { + if (record) { + return record->GetModuleRecordState() == ModuleRecordState::INITIALIZED_STATE; + } + return false; + }; + auto moduleRecordIter = + std::find_if(moduleInfoVectorIter->second.begin(), moduleInfoVectorIter->second.end(), findCondition); + if (moduleRecordIter != moduleInfoVectorIter->second.end()) { + (*moduleRecordIter)->GetHapModuleInfo(info); + (*moduleRecordIter)->SetModuleRecordState(ModuleRecordState::RUNNING_STATE); + result = true; + } + + return result; +} + +void AppRunningRecord::SetRestartResidentProcCount(int count) +{ + restartResidentProcCount_ = count; +} + +void AppRunningRecord::DecRestartResidentProcCount() +{ + restartResidentProcCount_--; +} + +int AppRunningRecord::GetRestartResidentProcCount() const +{ + return restartResidentProcCount_; +} + +bool AppRunningRecord::CanRestartResidentProc() +{ + return (restartResidentProcCount_ > 0); +} + +void AppRunningRecord::GetBundleNames(std::vector &bundleNames) +{ + for (auto &app : appInfos_) { + bundleNames.emplace_back(app.first); + } +} + +void AppRunningRecord::SetUserTestInfo(const UserTestRecord &record) +{ + userTestRecord_ = record; +} + +void AppRunningRecord::SetSpecifiedAbilityFlagAndWant( + const bool flag, const AAFwk::Want &want, const std::string &moduleName) +{ + isSpecifiedAbility_ = flag; + SpecifiedWant_ = want; + moduleName_ = moduleName; +} + +bool AppRunningRecord::IsStartSpecifiedAbility() const +{ + return isSpecifiedAbility_; +} + +void AppRunningRecord::ScheduleAcceptWant(const std::string &moduleName) +{ + SendEvent( + AMSEventHandler::START_MULTI_INSTANCES_ABILITY_MSG, AMSEventHandler::START_MULTI_INSTANCES_ABILITY_TIMEOUT); + appLifeCycleDeal_->ScheduleAcceptWant(SpecifiedWant_, moduleName); +} + +void AppRunningRecord::ScheduleAcceptWantDone() +{ + eventHandler_->RemoveEvent(AMSEventHandler::START_MULTI_INSTANCES_ABILITY_MSG, appRecordId_); +} + +const AAFwk::Want &AppRunningRecord::GetSpecifiedWant() const +{ + return SpecifiedWant_; +} + +void AppRunningRecord::UpdateConfiguration(const Configuration &config) +{ + APP_LOGI("call %{public}s", __func__); + if (!appLifeCycleDeal_) { + APP_LOGI("appLifeCycleDeal_ is null"); + return; + } + appLifeCycleDeal_->UpdateConfiguration(config); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_spawn_client.cpp b/services/appmgr/src/app_spawn_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2229827afac0e8e054b1183e63dd9ab0e67671f6 --- /dev/null +++ b/services/appmgr/src/app_spawn_client.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_spawn_client.h" + +#include "app_log_wrapper.h" +#include "bytrace.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t CONNECT_RETRY_DELAY = 200 * 1000; // 200ms +const int32_t CONNECT_RETRY_MAX_TIMES = 15; +} // namespace + +AppSpawnClient::AppSpawnClient() +{ + socket_ = std::make_shared(); + state_ = SpawnConnectionState::STATE_NOT_CONNECT; +} + +ErrCode AppSpawnClient::OpenConnection() +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!socket_) { + APP_LOGE("failed to open connection without socket!"); + return ERR_APPEXECFWK_BAD_APPSPAWN_SOCKET; + } + + int32_t retryCount = 1; + ErrCode errCode = socket_->OpenAppSpawnConnection(); + while (FAILED(errCode) && retryCount <= CONNECT_RETRY_MAX_TIMES) { + APP_LOGW("failed to OpenConnection, retry times %{public}d ...", retryCount); + usleep(CONNECT_RETRY_DELAY); + errCode = socket_->OpenAppSpawnConnection(); + retryCount++; + } + if (SUCCEEDED(errCode)) { + state_ = SpawnConnectionState::STATE_CONNECTED; + } else { + APP_LOGE("failed to openConnection, errorCode is %{public}08x", errCode); + state_ = SpawnConnectionState::STATE_CONNECT_FAILED; + } + return errCode; +} + +ErrCode AppSpawnClient::StartProcess(const AppSpawnStartMsg &startMsg, pid_t &pid) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + int32_t retryCount = 1; + ErrCode errCode = StartProcessImpl(startMsg, pid); + while (FAILED(errCode) && retryCount <= CONNECT_RETRY_MAX_TIMES) { + APP_LOGW("failed to StartProcess, retry times %{public}d ...", retryCount); + usleep(CONNECT_RETRY_DELAY); + errCode = StartProcessImpl(startMsg, pid); + retryCount++; + } + return errCode; +} + +ErrCode AppSpawnClient::StartProcessImpl(const AppSpawnStartMsg &startMsg, pid_t &pid) +{ + BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); + if (!socket_) { + APP_LOGE("failed to startProcess without socket!"); + return ERR_APPEXECFWK_BAD_APPSPAWN_SOCKET; + } + + ErrCode result = ERR_OK; + // openconnection failed, return fail + if (state_ != SpawnConnectionState::STATE_CONNECTED) { + result = OpenConnection(); + if (FAILED(result)) { + APP_LOGE("connect to appspawn failed!"); + return result; + } + } + std::unique_ptr autoCloseConnection( + this, [](AppSpawnClient *client) { client->CloseConnection(); }); + + AppSpawnMsgWrapper msgWrapper; + if (!msgWrapper.AssembleMsg(startMsg)) { + APP_LOGE("AssembleMsg failed!"); + return ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED; + } + AppSpawnPidMsg pidMsg; + if (msgWrapper.IsValid()) { + result = socket_->WriteMessage(msgWrapper.GetMsgBuf(), msgWrapper.GetMsgLength()); + if (FAILED(result)) { + APP_LOGE("WriteMessage failed!"); + return result; + } + result = socket_->ReadMessage(reinterpret_cast(pidMsg.pidBuf), LEN_PID); + if (FAILED(result)) { + APP_LOGE("ReadMessage failed!"); + return result; + } + } + if (pidMsg.pid <= 0) { + APP_LOGE("invalid pid!"); + result = ERR_APPEXECFWK_INVALID_PID; + } else { + pid = pidMsg.pid; + } + return result; +} + +SpawnConnectionState AppSpawnClient::QueryConnectionState() const +{ + return state_; +} + +void AppSpawnClient::CloseConnection() +{ + if (socket_ && state_ == SpawnConnectionState::STATE_CONNECTED) { + socket_->CloseAppSpawnConnection(); + } + state_ = SpawnConnectionState::STATE_NOT_CONNECT; +} + +void AppSpawnClient::SetSocket(const std::shared_ptr socket) +{ + socket_ = socket; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_spawn_msg_wrapper.cpp b/services/appmgr/src/app_spawn_msg_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0864799d66a1ae78765bbbfb06fb57c7dbb94e64 --- /dev/null +++ b/services/appmgr/src/app_spawn_msg_wrapper.cpp @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_spawn_msg_wrapper.h" + +#include "securec.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +AppSpawnMsgWrapper::~AppSpawnMsgWrapper() +{ + FreeMsg(); +} + +bool AppSpawnMsgWrapper::AssembleMsg(const AppSpawnStartMsg &startMsg) +{ + if (!VerifyMsg(startMsg)) { + return false; + } + FreeMsg(); + int32_t msgSize = sizeof(AppSpawnMsg) + 1; + msg_ = static_cast(malloc(msgSize)); + if (msg_ == nullptr) { + APP_LOGE("failed to malloc!"); + return false; + } + if (memset_s(msg_, msgSize, 0, msgSize) != EOK) { + APP_LOGE("failed to memset!"); + return false; + } + msg_->uid = startMsg.uid; + msg_->gid = startMsg.gid; + msg_->gidCount = startMsg.gids.size(); + for (uint32_t i = 0; i < msg_->gidCount; ++i) { + msg_->gidTable[i] = startMsg.gids[i]; + } + if (strcpy_s(msg_->processName, sizeof(msg_->processName), startMsg.procName.c_str()) != EOK) { + APP_LOGE("failed to transform procName!"); + return false; + } + if (strcpy_s(msg_->soPath, sizeof(msg_->soPath), startMsg.soPath.c_str()) != EOK) { + APP_LOGE("failed to transform soPath!"); + return false; + } + msg_->accessTokenId = startMsg.accessTokenId; + if (strcpy_s(msg_->apl, sizeof(msg_->apl), startMsg.apl.c_str()) != EOK) { + APP_LOGE("failed to transform apl!"); + return false; + } + + isValid_ = true; + DumpMsg(); + return isValid_; +} + +bool AppSpawnMsgWrapper::VerifyMsg(const AppSpawnStartMsg &startMsg) const +{ + if (startMsg.uid < 0) { + APP_LOGE("invalid uid! [%{public}d]", startMsg.uid); + return false; + } + + if (startMsg.gid < 0) { + APP_LOGE("invalid gid! [%{public}d]", startMsg.gid); + return false; + } + + if (startMsg.gids.size() > AppSpawn::ClientSocket::MAX_GIDS) { + APP_LOGE("too many app gids!"); + return false; + } + + for (uint32_t i = 0; i < startMsg.gids.size(); ++i) { + if (startMsg.gids[i] < 0) { + APP_LOGE("invalid gids array! [%{public}d]", startMsg.gids[i]); + return false; + } + } + + if (startMsg.procName.empty() || startMsg.procName.size() >= AppSpawn::ClientSocket::LEN_PROC_NAME) { + APP_LOGE("invalid procName!"); + return false; + } + + return true; +} + +void AppSpawnMsgWrapper::DumpMsg() const +{ + if (!isValid_) { + return; + } + APP_LOGI("************AppSpawnMsg*************"); + APP_LOGI("uid: %{public}d", msg_->uid); + APP_LOGI("gid: %{public}d", msg_->gid); + for (uint32_t i = 0; i < msg_->gidCount; ++i) { + APP_LOGI("gidTable[%{public}d]: %{public}d", i, msg_->gidTable[i]); + } + APP_LOGI("procName: %{public}s", msg_->processName); + APP_LOGI("soPath: %{private}s", msg_->soPath); + APP_LOGI("************************************"); +} + +void AppSpawnMsgWrapper::FreeMsg() +{ + if (msg_ != nullptr) { + free(msg_); + msg_ = nullptr; + isValid_ = false; + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/app_spawn_socket.cpp b/services/appmgr/src/app_spawn_socket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..327b5255cee3cbc79a513c0b3027c839cc3fbb39 --- /dev/null +++ b/services/appmgr/src/app_spawn_socket.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_spawn_socket.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +// arg "AppSpawn" cannot be defined as string object since REGISTER_SYSTEM_ABILITY will +// firstly start without init this string object, which leads to error. + +AppSpawnSocket::AppSpawnSocket() : clientSocket_(std::make_unique("AppSpawn")) +{} + +AppSpawnSocket::~AppSpawnSocket() +{} + +ErrCode AppSpawnSocket::OpenAppSpawnConnection() +{ + APP_LOGD("ready to open connection"); + if (clientSocket_) { + if (clientSocket_->CreateClient() != ERR_OK) { + APP_LOGE("failed to create socketClient"); + return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT; + } + if (clientSocket_->ConnectSocket() != ERR_OK) { + APP_LOGE("failed to connect socket"); + return ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED; + } + APP_LOGD("connection has been opened"); + return ERR_OK; + } + APP_LOGE("failed to open connection without socket"); + return ERR_APPEXECFWK_BAD_APPSPAWN_SOCKET; +} + +void AppSpawnSocket::CloseAppSpawnConnection() +{ + if (clientSocket_) { + clientSocket_->CloseClient(); + } +} + +ErrCode AppSpawnSocket::WriteMessage(const void *buf, const int32_t len) +{ + APP_LOGD("ready to write message"); + if (len <= 0) { + APP_LOGE("failed to write message due to invalid length of message"); + return ERR_INVALID_VALUE; + } + if (buf == nullptr) { + APP_LOGE("failed to write message due to null buf"); + return ERR_INVALID_VALUE; + } + if (clientSocket_) { + if (clientSocket_->WriteSocketMessage(buf, len) != len) { + APP_LOGE("failed to write message due to invalid write length"); + return ERR_APPEXECFWK_SOCKET_WRITE_FAILED; + } + APP_LOGD("write message success"); + return ERR_OK; + } + + APP_LOGE("failed to write message without socket"); + return ERR_APPEXECFWK_BAD_APPSPAWN_SOCKET; +} + +ErrCode AppSpawnSocket::ReadMessage(void *buf, const int32_t len) +{ + APP_LOGD("ready to read message"); + if (len <= 0) { + APP_LOGE("failed to read message due to invalid length of cache"); + return ERR_INVALID_VALUE; + } + if (buf == nullptr) { + APP_LOGE("failed to read message due to null buf"); + return ERR_INVALID_VALUE; + } + if (clientSocket_) { + if (clientSocket_->ReadSocketMessage(buf, len) != len) { + APP_LOGE("failed to read message due to invalid read length"); + return ERR_APPEXECFWK_SOCKET_READ_FAILED; + } + APP_LOGD("read message success"); + return ERR_OK; + } + APP_LOGE("failed to read message without socket"); + return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT; +} + +void AppSpawnSocket::SetClientSocket(const std::shared_ptr clientSocket) +{ + clientSocket_ = clientSocket; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/cgroup_manager.cpp b/services/appmgr/src/cgroup_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..886961a9d43a4cc2159702e7798dafa652e9f27a --- /dev/null +++ b/services/appmgr/src/cgroup_manager.cpp @@ -0,0 +1,524 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "cgroup_manager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "app_log_wrapper.h" +#include "event_handler.h" +#include "securec.h" + +constexpr std::string_view CG_CPUSET_DEFAULT_TASKS_PATH("/dev/cpuset/tasks"); +constexpr std::string_view CG_CPUSET_BACKGROUND_TASKS_PATH("/dev/cpuset/background/tasks"); +constexpr std::string_view CG_CPUCTL_DEFAULT_TASKS_PATH("/dev/cpuctl/tasks"); +constexpr std::string_view CG_CPUCTL_BACKGROUND_TASKS_PATH("/dev/cpuctl/background/tasks"); +constexpr std::string_view CG_FREEZER_FROZEN_TASKS_PATH("/dev/freezer/frozen/tasks"); +constexpr std::string_view CG_FREEZER_THAWED_TASKS_PATH("/dev/freezer/thawed/tasks"); +[[maybe_unused]] constexpr std::string_view CG_MEM_OOMCTL_PATH("/dev/memcg/memory.oom_control"); +constexpr std::string_view CG_MEM_EVTCTL_PATH("/dev/memcg/cgroup.event_control"); +constexpr std::string_view CG_MEM_PRESSURE_LEVEL_PATH("/dev/memcg/memory.pressure_level"); + +namespace OHOS { +namespace AppExecFwk { +namespace { +class ScopeGuard final { +public: + using Function = std::function; + +public: + explicit ScopeGuard(Function fn) : fn_(fn), dismissed_(false) + {} + + ~ScopeGuard() + { + if (!dismissed_) { + fn_(); + } + } + +public: + void Dismiss() + { + dismissed_ = true; + } + +private: + Function fn_; + bool dismissed_ = false; +}; + +int WriteValue(int fd, std::string_view v) +{ + if (fd < 0) { + errno = EINVAL; + return -1; + } + + int ret = TEMP_FAILURE_RETRY(write(fd, v.data(), v.size())); + if (ret != 0) { + APP_LOGE("err: %{public}s.", strerror(errno)); + } + fsync(fd); + + return ret; +} + +int WriteValue(int fd, int v, bool newLine = true) +{ + if (fd < 0) { + errno = EINVAL; + return -1; + } + + char str[32] = {0}; + + int len = snprintf_s(str, sizeof(str), sizeof(str) - 1, newLine ? "%d\n" : "%d", v); + if (len < 1) { + return -1; + } + + return WriteValue(fd, str); +} +} // namespace + +CgroupManager::CgroupManager() +{} + +CgroupManager::~CgroupManager() +{ + for (int i = 0; i < LOW_MEMORY_LEVEL_MAX; ++i) { + if (memoryEventFds_[i] >= 0) { + if (eventHandler_) { + eventHandler_->RemoveFileDescriptorListener(memoryEventFds_[i]); + } + close(memoryEventFds_[i]); + } + if (memoryPressureFds_[i] >= 0) { + close(memoryPressureFds_[i]); + } + } + + if (memoryEventControlFd_ >= 0) { + close(memoryEventControlFd_); + } + + for (int i = 0; i < SCHED_POLICY_CPU_MAX; ++i) { + if (cpusetTasksFds_[i] >= 0) { + close(cpusetTasksFds_[i]); + } + } +} + +bool CgroupManager::Init() +{ + APP_LOGI("Init enter."); + if (IsInited()) { + APP_LOGE("already inited."); + return false; + } + + auto eventHandler = std::make_shared(EventRunner::Create()); + if (!eventHandler) { + APP_LOGE("failed to get event handler."); + return false; + } + + if (!InitCheck()) { + return false; + } + + if (!RegisterLowMemoryMonitor( + memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_LOW, eventHandler)) { + return false; + } + + ScopeGuard lowLevelListenerGuard( + [&]() { eventHandler->RemoveFileDescriptorListener(memoryEventFds_[LOW_MEMORY_LEVEL_LOW]); }); + + if (!RegisterLowMemoryMonitor( + memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_MEDIUM, eventHandler)) { + return false; + } + + ScopeGuard mediumLevelListenerGuard( + [&]() { eventHandler->RemoveFileDescriptorListener(memoryEventFds_[LOW_MEMORY_LEVEL_MEDIUM]); }); + + if (!RegisterLowMemoryMonitor( + memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_CRITICAL, eventHandler)) { + return false; + } + + ScopeGuard criticalLevelListenerGuard( + [&]() { eventHandler->RemoveFileDescriptorListener(memoryEventFds_[LOW_MEMORY_LEVEL_CRITICAL]); }); + + eventHandler_ = eventHandler; + lowLevelListenerGuard.Dismiss(); + mediumLevelListenerGuard.Dismiss(); + criticalLevelListenerGuard.Dismiss(); + + return true; +} + +bool CgroupManager::InitCheck() +{ + UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_MAX]; + if (!InitCpusetTasksFds(cpusetTasksFds)) { + return false; + } + + UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_MAX]; + if (!InitCpuctlTasksFds(cpuctlTasksFds)) { + return false; + } + + UniqueFd freezerTasksFds[SCHED_POLICY_FREEZER_MAX]; + if (!InitFreezerTasksFds(freezerTasksFds)) { + return false; + } + + UniqueFd memoryEventControlFd; + if (!InitMemoryEventControlFd(memoryEventControlFd)) { + return false; + } + + UniqueFd memoryEventFds[LOW_MEMORY_LEVEL_MAX]; + if (!InitMemoryEventFds(memoryEventFds)) { + return false; + } + + UniqueFd memoryPressureFds[LOW_MEMORY_LEVEL_MAX]; + if (!InitMemoryPressureFds(memoryPressureFds)) { + return false; + } + return true; +} + +bool CgroupManager::IsInited() const +{ + return bool(eventHandler_); +} + +bool CgroupManager::SetThreadSchedPolicy(int tid, SchedPolicy schedPolicy) +{ + if (!IsInited()) { + APP_LOGE("not inited."); + return false; + } + + if (tid < 1) { + APP_LOGE("invalid tid %{public}d.", tid); + return false; + } + + if (schedPolicy < 0 || schedPolicy >= SchedPolicy::SCHED_POLICY_MAX) { + APP_LOGE("invalid sched policy %{public}d.", schedPolicy); + return false; + } + + if (schedPolicy == SchedPolicy::SCHED_POLICY_FREEZED) { + // set frozen of freezer + if (!SetFreezerSubsystem(tid, SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN)) { + APP_LOGE("set freezer subsystem failed sched policy %{public}d.", schedPolicy); + return false; + } + } else { + // set cpuset + if (!SetCpusetSubsystem(tid, schedPolicy)) { + APP_LOGE("set cpuset subsystem failed sched policy %{public}d.", schedPolicy); + return false; + } + // set cpuctl + if (!SetCpuctlSubsystem(tid, schedPolicy)) { + APP_LOGE("set cpuctl subsystem failed sched policy %{public}d.", schedPolicy); + return false; + } + + // set thawed of freezer + if (!SetFreezerSubsystem(tid, SchedPolicyFreezer::SCHED_POLICY_FREEZER_THAWED)) { + APP_LOGE("set freezer subsystem failed sched policy %{public}d.", schedPolicy); + return false; + } + } + + return true; +} + +bool CgroupManager::SetProcessSchedPolicy(int pid, SchedPolicy schedPolicy) +{ + if (!IsInited()) { + APP_LOGE("not inited."); + return false; + } + + if (pid < 1) { + APP_LOGE("invalid pid %{public}d", pid); + return false; + } + + if (schedPolicy < 0 && schedPolicy >= SCHED_POLICY_MAX) { + APP_LOGE("invalid sched policy %{public}d", schedPolicy); + return false; + } + + // Set all threads's sched policy inside this process. + char taskDir[64]; + if (snprintf_s(taskDir, sizeof(taskDir), sizeof(taskDir) - 1, "/proc/%d/task", pid) < 0) { + return false; + } + + DIR *dir = opendir(taskDir); + if (dir == nullptr) { + APP_LOGE("failed to opendir invalid pid %{public}d taskDir %{public}s , %{public}s", + pid, + taskDir, + strerror(errno)); + return false; + } + + struct dirent *dent; + while ((dent = readdir(dir))) { + // Filter out '.' & '..' + if (dent->d_name[0] != '.') { + SetThreadSchedPolicy(atoi(dent->d_name), schedPolicy); + } + } + + closedir(dir); + + return true; +} + +void CgroupManager::OnReadable(int32_t fd) +{ + APP_LOGW("system low memory alert."); + + if (!LowMemoryAlert) { + APP_LOGW("'LowMemoryAlert' not available."); + return; + } + + auto TryToRaiseLowMemoryAlert = [=](LowMemoryLevel level) { + if (fd == memoryEventFds_[level]) { + APP_LOGW("checking level %{public}d", level); + uint64_t count = 0; + int ret = TEMP_FAILURE_RETRY(read(fd, &count, sizeof(uint64_t))); + if (ret <= 0) { + APP_LOGW("failed to read eventfd %{public}d.", errno); + return false; + } + if (count < 1) { + APP_LOGW("invalid eventfd count %{public}" PRIu64 ".", count); + return false; + } + APP_LOGW("raising low memory alert for level %{public}d...", level); + LowMemoryAlert(level); + return true; + } + return false; + }; + + if (TryToRaiseLowMemoryAlert(LOW_MEMORY_LEVEL_LOW)) { + return; + } + + if (TryToRaiseLowMemoryAlert(LOW_MEMORY_LEVEL_MEDIUM)) { + return; + } + + if (TryToRaiseLowMemoryAlert(LOW_MEMORY_LEVEL_CRITICAL)) { + return; + } + + // Should not reach here! + APP_LOGE("Unknown fd %{public}d.", fd); +} + +bool CgroupManager::RegisterLowMemoryMonitor(const int memoryEventFds[LOW_MEMORY_LEVEL_MAX], + const int memoryPressureFds[LOW_MEMORY_LEVEL_MAX], const int memoryEventControlFd, const LowMemoryLevel level, + const std::shared_ptr &eventHandler) +{ + APP_LOGI("RegisterLowMemoryMonitor(%{public}d) registering low memory monitor %{public}d...", __LINE__, level); + + char buf[64] = {0}; + static const char *levelName[] = {"low", "medium", "critical"}; + + if (snprintf_s(buf, + sizeof(buf), + sizeof(buf) - 1, + "%d %d %s", + memoryEventFds[level], + memoryPressureFds[level], + levelName[level]) < 0) { + return false; + } + + int ret = TEMP_FAILURE_RETRY(write(memoryEventControlFd, buf, strlen(buf) + 1)); + if (ret < 0) { + APP_LOGI("RegisterLowMemoryMonitor(%{public}d) failed to write memory control %{public}d...", __LINE__, errno); + return false; + } + + eventHandler->AddFileDescriptorListener(memoryEventFds[level], FILE_DESCRIPTOR_INPUT_EVENT, shared_from_this()); + + return true; +} + +bool CgroupManager::InitCpusetTasksFds(UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_MAX]) +{ + cpusetTasksFds[SCHED_POLICY_CPU_DEFAULT] = UniqueFd(open(CG_CPUSET_DEFAULT_TASKS_PATH.data(), O_RDWR)); + cpusetTasksFds[SCHED_POLICY_CPU_BACKGROUND] = UniqueFd(open(CG_CPUSET_BACKGROUND_TASKS_PATH.data(), O_RDWR)); + if (cpusetTasksFds[SCHED_POLICY_CPU_DEFAULT].Get() < 0 || cpusetTasksFds[SCHED_POLICY_CPU_BACKGROUND].Get() < 0) { + APP_LOGE("cannot open cpuset cgroups %{public}d.", errno); + return false; + } + + cpusetTasksFds_[SCHED_POLICY_CPU_DEFAULT] = cpusetTasksFds[SCHED_POLICY_CPU_DEFAULT].Release(); + cpusetTasksFds_[SCHED_POLICY_CPU_BACKGROUND] = cpusetTasksFds[SCHED_POLICY_CPU_BACKGROUND].Release(); + return true; +} + +bool CgroupManager::InitCpuctlTasksFds(UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_MAX]) +{ + cpuctlTasksFds[SCHED_POLICY_CPU_DEFAULT] = UniqueFd(open(CG_CPUCTL_DEFAULT_TASKS_PATH.data(), O_RDWR)); + cpuctlTasksFds[SCHED_POLICY_CPU_BACKGROUND] = UniqueFd(open(CG_CPUCTL_BACKGROUND_TASKS_PATH.data(), O_RDWR)); + if (cpuctlTasksFds[SCHED_POLICY_CPU_DEFAULT].Get() < 0 || cpuctlTasksFds[SCHED_POLICY_CPU_BACKGROUND].Get() < 0) { + APP_LOGE("cannot open cpuctl cgroups %{public}d.", errno); + return false; + } + + cpuctlTasksFds_[SCHED_POLICY_CPU_DEFAULT] = cpuctlTasksFds[SCHED_POLICY_CPU_DEFAULT].Release(); + cpuctlTasksFds_[SCHED_POLICY_CPU_BACKGROUND] = cpuctlTasksFds[SCHED_POLICY_CPU_BACKGROUND].Release(); + return true; +} + +bool CgroupManager::InitFreezerTasksFds(UniqueFd freezerTasksFds[SCHED_POLICY_FREEZER_MAX]) +{ + freezerTasksFds[SCHED_POLICY_FREEZER_FROZEN] = UniqueFd(open(CG_FREEZER_FROZEN_TASKS_PATH.data(), O_RDWR)); + freezerTasksFds[SCHED_POLICY_FREEZER_THAWED] = UniqueFd(open(CG_FREEZER_THAWED_TASKS_PATH.data(), O_RDWR)); + if (freezerTasksFds[SCHED_POLICY_FREEZER_FROZEN].Get() < 0 || + freezerTasksFds[SCHED_POLICY_FREEZER_THAWED].Get() < 0) { + APP_LOGE("cannot open freezer cgroups %{public}d.", errno); + return false; + } + + freezerTasksFds_[SCHED_POLICY_FREEZER_FROZEN] = freezerTasksFds[SCHED_POLICY_FREEZER_FROZEN].Release(); + freezerTasksFds_[SCHED_POLICY_FREEZER_THAWED] = freezerTasksFds[SCHED_POLICY_FREEZER_THAWED].Release(); + return true; +} + +bool CgroupManager::InitMemoryEventControlFd(UniqueFd &memoryEventControlFd) +{ + memoryEventControlFd = UniqueFd(open(CG_MEM_EVTCTL_PATH.data(), O_WRONLY)); + if (memoryEventControlFd.Get() < 0) { + APP_LOGE("failed to open memory event control node %{public}d.", errno); + return false; + } + + memoryEventControlFd_ = memoryEventControlFd.Release(); + return true; +} + +bool CgroupManager::InitMemoryEventFds(UniqueFd memoryEventFds[LOW_MEMORY_LEVEL_MAX]) +{ + memoryEventFds[LOW_MEMORY_LEVEL_LOW] = UniqueFd(eventfd(0, EFD_NONBLOCK)); + memoryEventFds[LOW_MEMORY_LEVEL_MEDIUM] = UniqueFd(eventfd(0, EFD_NONBLOCK)); + memoryEventFds[LOW_MEMORY_LEVEL_CRITICAL] = UniqueFd(eventfd(0, EFD_NONBLOCK)); + if (memoryEventFds[LOW_MEMORY_LEVEL_LOW].Get() < 0 || memoryEventFds[LOW_MEMORY_LEVEL_MEDIUM].Get() < 0 || + memoryEventFds[LOW_MEMORY_LEVEL_CRITICAL].Get() < 0) { + APP_LOGE("failed to create memory eventfd %{public}d.", errno); + return false; + } + + memoryEventFds_[LOW_MEMORY_LEVEL_LOW] = memoryEventFds[LOW_MEMORY_LEVEL_LOW].Release(); + memoryEventFds_[LOW_MEMORY_LEVEL_MEDIUM] = memoryEventFds[LOW_MEMORY_LEVEL_MEDIUM].Release(); + memoryEventFds_[LOW_MEMORY_LEVEL_CRITICAL] = memoryEventFds[LOW_MEMORY_LEVEL_CRITICAL].Release(); + return true; +} + +bool CgroupManager::InitMemoryPressureFds(UniqueFd memoryPressureFds[LOW_MEMORY_LEVEL_MAX]) +{ + memoryPressureFds[LOW_MEMORY_LEVEL_LOW] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH.data(), O_RDONLY)); + memoryPressureFds[LOW_MEMORY_LEVEL_MEDIUM] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH.data(), O_RDONLY)); + memoryPressureFds[LOW_MEMORY_LEVEL_CRITICAL] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH.data(), O_RDONLY)); + if (memoryPressureFds[LOW_MEMORY_LEVEL_LOW].Get() < 0 || memoryPressureFds[LOW_MEMORY_LEVEL_MEDIUM].Get() < 0 || + memoryPressureFds[LOW_MEMORY_LEVEL_CRITICAL].Get() < 0) { + APP_LOGE("failed to open memory pressure fd %{public}d.", errno); + return false; + } + + memoryPressureFds_[LOW_MEMORY_LEVEL_LOW] = memoryPressureFds[LOW_MEMORY_LEVEL_LOW].Release(); + memoryPressureFds_[LOW_MEMORY_LEVEL_MEDIUM] = memoryPressureFds[LOW_MEMORY_LEVEL_MEDIUM].Release(); + memoryPressureFds_[LOW_MEMORY_LEVEL_CRITICAL] = memoryPressureFds[LOW_MEMORY_LEVEL_CRITICAL].Release(); + return true; +} + +bool CgroupManager::SetCpusetSubsystem(const int tid, const SchedPolicy schedPolicy) +{ + int fd = cpusetTasksFds_[schedPolicy]; + if (fd < 0) { + APP_LOGE("invalid cpuset fd for policy %{public}d.", schedPolicy); + return false; + } + + int ret = WriteValue(fd, tid); + if (ret < 0) { + APP_LOGE("write cpuset tid failed %{public}d.", errno); + return false; + } + + return true; +} + +bool CgroupManager::SetCpuctlSubsystem(const int tid, const SchedPolicy schedPolicy) +{ + int fd = cpuctlTasksFds_[schedPolicy]; + if (fd < 0) { + APP_LOGE("invalid cpuctl fd for policy %{public}d.", schedPolicy); + return false; + } + + int ret = WriteValue(fd, tid); + if (ret < 0) { + APP_LOGE("write cpuctl tid failed %{public}d.", errno); + return false; + } + + return true; +} + +bool CgroupManager::SetFreezerSubsystem(const int tid, const SchedPolicyFreezer state) +{ + int fd = freezerTasksFds_[state]; + if (fd < 0) { + APP_LOGE("invalid freezer fd for state %{public}d.", state); + return false; + } + + int ret = WriteValue(fd, tid); + if (ret < 0) { + APP_LOGE("write freezer tid failed %{public}d.", errno); + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/kernel_system_memory_info.h b/services/appmgr/src/kernel_system_memory_info.h new file mode 100644 index 0000000000000000000000000000000000000000..066742242b21cba2a23849ce34b996d1de058a56 --- /dev/null +++ b/services/appmgr/src/kernel_system_memory_info.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_KERNEL_SYSTEM_MEMORY_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_KERNEL_SYSTEM_MEMORY_INFO_H + +#include + +namespace OHOS { +namespace AppExecFwk { +namespace SystemEnv { +class KernelSystemMemoryInfo { +public: + KernelSystemMemoryInfo() = default; + ~KernelSystemMemoryInfo() = default; + + void Init(std::map &memInfo); + + int64_t GetMemTotal() const; + int64_t GetMemFree() const; + int64_t GetMemAvailable() const; + int64_t GetBuffers() const; + int64_t GetCached() const; + int64_t GetSwapCached() const; + +private: + int64_t memTotal_ = 0; + int64_t memFree_ = 0; + int64_t memAvailable_ = 0; + int64_t buffers_ = 0; + int64_t cached_ = 0; + int64_t swapCached_ = 0; +}; +} // namespace SystemEnv +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_KERNEL_SYSTEM_MEMORY_INFO_H \ No newline at end of file diff --git a/services/appmgr/src/lmks/lmks_main.cpp b/services/appmgr/src/lmks/lmks_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e90fead4a50319e18c46d784f08bc90bb40ec9f7 --- /dev/null +++ b/services/appmgr/src/lmks/lmks_main.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "lmks_server.h" + +int main(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + OHOS::LMKS::LmksServer lmksServer; + lmksServer.StartServer(); + + return 0; +} diff --git a/services/appmgr/src/lmks/lmks_server.cpp b/services/appmgr/src/lmks/lmks_server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a657f58d22dddf47a6cdd2b402e210185d9644c --- /dev/null +++ b/services/appmgr/src/lmks/lmks_server.cpp @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "lmks_server.h" + +#include +#include +#include +#include +#include + +#include "hilog/log.h" +#include "securec.h" + +namespace OHOS { +namespace LMKS { +namespace { +#ifdef __MUSL__ +const std::string LMKS_SOCKET_NAME = "/dev/unix/socket/lmks"; +#else +const std::string LMKS_SOCKET_NAME = "/dev/socket/lmks"; +#endif +constexpr uint32_t LISTEN_CLIENTS = 5; // 5: max num of clients +constexpr uint32_t WAIT_DELAY_US = 100 * 1000; // 100ms + +constexpr int LMKS_CMD_TARGET = 0; +constexpr int LMKS_CMD_PROCPRIO = 1; +constexpr int LMKS_CMD_PROCREMOVE = 2; +constexpr int LMKS_CMD_PROCPURGE = 3; +constexpr uid_t LMKS_ID_ROOT = 0; // chown owner +constexpr gid_t LMKS_ID_SYSTEM = 1000; // chown group +constexpr mode_t SOCKET_PERM = 0666; // root system can read and write lmks socket +constexpr struct timeval SOCKET_TIMEOUT = {5, 0}; // 5, 0: { 5 sec, 0 msec } for timeout +} // namespace + +using namespace OHOS::HiviewDFX; +static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "LmksServer"}; + +LmksServer::LmksServer() : isStart_(false), socketFd_(-1), socketAddrLen_(0), lmksUtils_(nullptr) +{ + memset_s(&socketAddr_, sizeof(socketAddr_), 0, sizeof(socketAddr_)); +} + +LmksServer::~LmksServer() +{ + CloseSocket(); +} + +void LmksServer::StartServer() +{ + if (isStart_) { + HiLog::Error(LABEL, "Lmks server has started."); + return; + } + + if (RegisterSocket() != 0) { + HiLog::Error(LABEL, "Register error."); + return; + } + + isStart_ = true; + if (lmksUtils_ == nullptr) { + lmksUtils_ = std::make_shared(); + } + + while (1) { + int connectFd = WaitConnection(); + if (connectFd < 0) { + usleep(WAIT_DELAY_US); + continue; + } + + LMKS_PACKET cmds; + int len = RecvSocketMessage(connectFd, (void *)cmds, sizeof(cmds)); + if (len <= 0) { + HiLog::Error(LABEL, "Failed to read socket message, len %{public}d", len); + close(connectFd); + continue; + } + + ProcessMessage(connectFd, cmds, len); + } + + // close socket + CloseSocket(); +} + +int LmksServer::RegisterSocket() +{ + if (socketFd_ > 0) { + HiLog::Error(LABEL, "Lmks server has already register."); + return -1; + } + + socketFd_ = socket(AF_LOCAL, SOCK_SEQPACKET, 0); + if (socketFd_ < 0) { + HiLog::Error(LABEL, "Failed to create socket, err %{public}s", strerror(errno)); + return (-errno); + } + + if (memset_s(&socketAddr_, sizeof(socketAddr_), 0, sizeof(socketAddr_)) != 0) { + HiLog::Error(LABEL, "Failed to memset socket addr, err %{public}s", strerror(errno)); + return (-errno); + } + + if (strcpy_s(socketAddr_.sun_path, sizeof(socketAddr_.sun_path), LMKS_SOCKET_NAME.c_str()) != 0) { + HiLog::Error(LABEL, "Failed to snprint32_tf_s socket addr, err %{public}s", strerror(errno)); + return (-errno); + } + + socketAddr_.sun_family = AF_LOCAL; + socketAddrLen_ = offsetof(struct sockaddr_un, sun_path) + LMKS_SOCKET_NAME.length() + 1; + + if ((unlink(socketAddr_.sun_path) != 0) && (errno != ENOENT)) { + HiLog::Error(LABEL, "Failed to unlink, err %{public}s", strerror(errno)); + return (-errno); + } + + int reuseAddr = 0; + if ((setsockopt(socketFd_, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0) || + (setsockopt(socketFd_, SOL_SOCKET, SO_RCVTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) != 0) || + (setsockopt(socketFd_, SOL_SOCKET, SO_SNDTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) != 0)) { + HiLog::Error(LABEL, "Failed to set opt of socket %d, err %{public}s", socketFd_, strerror(errno)); + return (-errno); + } + + if (bind(socketFd_, reinterpret_cast(&socketAddr_), socketAddrLen_) < 0) { + HiLog::Error(LABEL, "Failed to bind socket fd %d, err %{public}s", socketFd_, strerror(errno)); + return (-errno); + } + + if (chown(socketAddr_.sun_path, LMKS_ID_ROOT, LMKS_ID_SYSTEM)) { + HiLog::Error(LABEL, "Failed to chown socket. err %{public}s", strerror(errno)); + return (-errno); + } + + if (chmod(socketAddr_.sun_path, SOCKET_PERM)) { + HiLog::Error(LABEL, "Failed to chmod socket. err %{public}s", strerror(errno)); + if ((unlink(socketAddr_.sun_path) != 0) && (errno != ENOENT)) { + HiLog::Error(LABEL, "Failed to unlink, err %{public}s", strerror(errno)); + } + return (-errno); + } + + if (listen(socketFd_, LISTEN_CLIENTS) != 0) { + HiLog::Error(LABEL, "Failed to listen socket fd %d, err %{public}s", socketFd_, strerror(errno)); + return (-errno); + } + + return 0; +} + +int LmksServer::WaitConnection() +{ + if (socketFd_ < 0) { + HiLog::Error(LABEL, "lmks server not register."); + return -1; + } + + struct sockaddr_un clientAddr; + socklen_t clientLen = sizeof(clientAddr); + + if (memset_s(&clientAddr, clientLen, 0, clientLen) != 0) { + HiLog::Warn(LABEL, "Failed to memset client addr, err %{public}s", strerror(errno)); + } + + int connFd = accept(socketFd_, reinterpret_cast(&clientAddr), &clientLen); + if (connFd < 0) { + HiLog::Warn(LABEL, "Accept warning %{public}s", strerror(errno)); + return (-errno); + } + + if ((setsockopt(connFd, SOL_SOCKET, SO_RCVTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) < 0) || + (setsockopt(connFd, SOL_SOCKET, SO_SNDTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) < 0)) { + HiLog::Error(LABEL, "Failed to set opt of Connection %d, err %{public}s", connFd, strerror(errno)); + close(connFd); + return (-errno); + } + + return connFd; +} + +void LmksServer::CloseSocket() +{ + if (socketFd_ >= 0) { + HiLog::Debug(LABEL, "Closed socket with fd %d", socketFd_); + close(socketFd_); + socketFd_ = -1; + } +} + +int LmksServer::SendSocketMessage(int connectFd, const void *buf, int len) +{ + if (connectFd < 0 || len <= 0 || buf == nullptr) { + HiLog::Error(LABEL, "Invalid args: connect %d, len %d, buf might be nullptr", connectFd, len); + return -1; + } + + ssize_t rLen = TEMP_FAILURE_RETRY(send(connectFd, buf, len, 0)); + if (rLen < 0) { + HiLog::Error(LABEL, "Send message from fd %d error %zd: %s", connectFd, rLen, strerror(errno)); + return (-errno); + } + + return rLen; +} + +int LmksServer::RecvSocketMessage(int connectFd, void *buf, int len) +{ + if (connectFd < 0 || len <= 0 || buf == nullptr) { + HiLog::Error(LABEL, "Invalid args: connect %d, len %d, buf might be nullptr", connectFd, len); + return -1; + } + + if (memset_s(buf, len, 0, len) != 0) { + HiLog::Error(LABEL, "Failed to memset read buf err %{public}s", strerror(errno)); + return (-errno); + } + + ssize_t rLen = TEMP_FAILURE_RETRY(recv(connectFd, buf, len, 0)); + if (rLen < 0) { + HiLog::Error(LABEL, "Read message from fd %d error %zd: %s", connectFd, rLen, strerror(errno)); + return (-errno); + } + + return rLen; +} + +void LmksServer::ProcessMessage(int connectFd, LMKS_PACKET cmds, int len) +{ + if (!isStart_ || (lmksUtils_ == nullptr)) { + HiLog::Error( + LABEL, "Lmks server not start isStart_ %{public}d lmksUtils_%{public}p", isStart_, lmksUtils_.get()); + close(connectFd); + return; + } + + if (connectFd < 0 || len <= 0) { + HiLog::Error(LABEL, "Invalid args: len %d, connectFd %d", len, connectFd); + close(connectFd); + return; + } + + int ret = -1; + pid_t pid = 0; + + switch (cmds[0]) { + case LMKS_CMD_TARGET: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_TARGET "); + break; + case LMKS_CMD_PROCPRIO: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCPRIO"); + break; + case LMKS_CMD_PROCREMOVE: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCREMOVE"); + pid = cmds[1]; + ret = lmksUtils_->RemoveProcess(pid); + if (SendSocketMessage(connectFd, &ret, sizeof(ret)) <= 0) { + HiLog::Error(LABEL, "Failed to return the result of remove process"); + } + break; + case LMKS_CMD_PROCPURGE: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCPURGE"); + break; + default: + HiLog::Error(LABEL, "Wrong cmd %d", cmds[0]); + break; + } + + // close connect fd. + close(connectFd); +} +} // namespace LMKS +} // namespace OHOS diff --git a/services/appmgr/src/lmks/lmks_utils.cpp b/services/appmgr/src/lmks/lmks_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a1833a30f7ef6e35545cc3eb438986b3d1f4efa --- /dev/null +++ b/services/appmgr/src/lmks/lmks_utils.cpp @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "lmks_utils.h" + +#include +#include +#include +#include + +#include "hilog/log.h" +#include "securec.h" + +namespace OHOS { +namespace LMKS { +namespace { +constexpr int PROC_PATH_MAX = 256; +constexpr int PROC_LINE_MAX = 128; +} // namespace + +using namespace OHOS::HiviewDFX; +static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "LmksUtils"}; + +LmksUtils::LmksUtils() +{} + +LmksUtils::~LmksUtils() +{} + +int LmksUtils::RemoveProcess(pid_t pid) +{ + auto procName = GetProcName(pid); + if (procName.empty()) { + HiLog::Error(LABEL, "pid %{public}d process name emptry", pid); + return -1; + } + + auto procSize = GetProcSize(pid); + if (procSize <= 0) { + HiLog::Error(LABEL, "pid %{public}d process size error", pid); + return -1; + } + + // kill process + int ret = kill(pid, SIGKILL); + if (ret) { + HiLog::Warn(LABEL, "kill pid %{public}d err %{public}s", pid, strerror(errno)); + return (-errno); + } else { + HiLog::Info( + LABEL, "kill pid %{public}d success, name %{public}s size %{public}d", pid, procName.c_str(), procSize); + } + + return 0; +} + +std::string LmksUtils::GetProcName(pid_t pid) +{ + std::string name = ""; + + if (pid < 1) { + HiLog::Warn(LABEL, "invalid pid %{public}d.", pid); + return name; + } + + char path[PROC_PATH_MAX]; + char line[PROC_LINE_MAX]; + int fd = -1; + ssize_t ret = -1; + + if (memset_s(path, sizeof(path), 0x00, sizeof(path)) != 0) { + HiLog::Error(LABEL, "memset_s path err %{public}s", strerror(errno)); + return name; + } + + if (memset_s(line, sizeof(line), 0x00, sizeof(line)) != 0) { + HiLog::Error(LABEL, "memset_s line err %{public}s", strerror(errno)); + return name; + } + + if (snprintf_s(path, PROC_PATH_MAX, PROC_PATH_MAX - 1, "/proc/%d/cmdline", pid) < 0) { + HiLog::Error(LABEL, "snprintf_s cmdline err %{public}s", strerror(errno)); + return name; + } + + fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd == -1) { + HiLog::Error(LABEL, "open path[%{public}s] err %{public}s", path, strerror(errno)); + return name; + } + + ret = ReadAll(fd, line, sizeof(line) - 1); + if (ret < 0) { + close(fd); + return name; + } + + if (strlen(line) + 1 <= PROC_LINE_MAX && strlen(line) != 0) { + name = line; + } else { + HiLog::Error(LABEL, "cmdline no data"); + } + + close(fd); + return name; +} + +int LmksUtils::GetProcSize(pid_t pid) +{ + int rss = 0; + + if (pid <= 0) { + HiLog::Error(LABEL, "invalid pid %{public}d.", pid); + return rss; + } + + char path[PROC_PATH_MAX]; + char line[PROC_LINE_MAX]; + int fd = -1; + int total = -1; + ssize_t ret = -1; + + if (memset_s(path, sizeof(path), 0x00, sizeof(path)) != 0) { + HiLog::Error(LABEL, "memset_s path err %{public}s", strerror(errno)); + return -1; + } + + if (memset_s(line, sizeof(line), 0x00, sizeof(line)) != 0) { + HiLog::Error(LABEL, "memset_s line err %{public}s", strerror(errno)); + return -1; + } + + if (snprintf_s(path, PROC_PATH_MAX, PROC_PATH_MAX - 1, "/proc/%d/statm", pid) < 0) { + HiLog::Error(LABEL, "snprintf_s statm err %{public}s", strerror(errno)); + return rss; + } + + fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd == -1) { + HiLog::Error(LABEL, "open path[%{public}s] err %{public}s", path, strerror(errno)); + return -1; + } + + ret = ReadAll(fd, line, sizeof(line) - 1); + if (ret < 0) { + close(fd); + return -1; + } + + if ((strlen(line) + 1 <= PROC_LINE_MAX && strlen(line) != 0) && (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { + HiLog::Info(LABEL, "pid %{public}d total %{public}d rss %{public}d", pid, total, rss); + } else { + HiLog::Error(LABEL, "strlen or sscanf_s err %{public}s", strerror(errno)); + rss = 0; + } + + close(fd); + return rss; +} + +ssize_t LmksUtils::ReadAll(int fd, char *buf, size_t maxLen) +{ + ssize_t ret = 0; + off_t offSet = 0; + + while (maxLen > 0) { + ssize_t rc = TEMP_FAILURE_RETRY(pread(fd, buf, maxLen, offSet)); + if (rc == 0) { + break; + } + if (rc == -1) { + HiLog::Error(LABEL, "pread err %{public}s", strerror(errno)); + return -1; + } + ret += rc; + buf += rc; + offSet += rc; + maxLen -= rc; + } + + return ret; +} +} // namespace LMKS +} // namespace OHOS diff --git a/services/appmgr/src/lmks_client.cpp b/services/appmgr/src/lmks_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7a7d49f5769fd4f8335036a292c9d6579a5033e --- /dev/null +++ b/services/appmgr/src/lmks_client.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "lmks_client.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "event_handler.h" +#include "securec.h" +#include "unique_fd.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +constexpr int LMKS_SOCKET_TIMEOUT = 3; + +constexpr size_t LMKS_START_VALUE = 1; +constexpr size_t LMKS_MULTIPLE = 2; +constexpr size_t LMKS_MAX_TARGETS = 6; + +constexpr int LMKS_CMD_TARGET = 0; +constexpr int LMKS_CMD_PROCPRIO = 1; +constexpr int LMKS_CMD_PROCREMOVE = 2; +constexpr int LMKS_CMD_PROCPURGE = 3; + +constexpr int APP_OOM_ADJ_MIN = -1000; +constexpr int APP_OOM_ADJ_MAX = 1000; +constexpr int LMKS_SOCKET_PATH_MAX = 108; + +constexpr std::string_view LMKS_SOCKET_PATH("/dev/socket/lmks"); +static_assert(LMKS_SOCKET_PATH.size() < LMKS_SOCKET_PATH_MAX); +} // namespace + +LmksClient::LmksClient() : socket_(-1) +{} + +LmksClient::~LmksClient() +{ + if (IsOpen()) { + Close(); + } +} + +int32_t LmksClient::Open() +{ + APP_LOGI("connecting lmks."); + + if (socket_ >= 0) { + APP_LOGE("already connected."); + return -1; + } + + UniqueFd sk(socket(PF_LOCAL, SOCK_SEQPACKET, 0)); + if (sk.Get() < 0) { + APP_LOGE("failed to create local socket %{public}d.", errno); + return (-errno); + } + + struct timeval timeOut = {.tv_sec = LMKS_SOCKET_TIMEOUT, .tv_usec = 0}; + int fd = sk.Get(); + if (fd < 0) { + APP_LOGE("fd is negative."); + return -1; + } + if ((setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeOut, sizeof(timeOut)) != 0) || + (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeOut, sizeof(timeOut)) != 0)) { + APP_LOGE("failed to set local socket timeout %{public}s.", strerror(errno)); + return (-errno); + } + + struct sockaddr_un addr; + int32_t ret; + ret = memset_s(&addr, sizeof(addr), 0, sizeof(addr)); + if (ret != EOK) { + APP_LOGE("failed to clear local socket addr."); + return ret; + } + + ret = memcpy_s(addr.sun_path, LMKS_SOCKET_PATH_MAX, LMKS_SOCKET_PATH.data(), LMKS_SOCKET_PATH.size()); + if (ret != EOK) { + APP_LOGE("failed to make local socket path."); + return ret; + } + + addr.sun_family = AF_LOCAL; + socklen_t addrLen = offsetof(struct sockaddr_un, sun_path) + LMKS_SOCKET_PATH.size() + 1; + if (connect(sk, reinterpret_cast(&addr), addrLen) < 0) { + APP_LOGE("failed to connect to lmks %{public}s.", strerror(errno)); + return (-errno); + } + + socket_ = sk.Release(); + + return ERR_OK; +} + +void LmksClient::Close() +{ + APP_LOGI("closing lmks."); + + if (socket_ < 0) { + APP_LOGE("not connected."); + return; + } + + close(socket_); + socket_ = -1; +} + +bool LmksClient::IsOpen() const +{ + return socket_ >= 0; +} + +int32_t LmksClient::Target(const Targets &targets) +{ + APP_LOGI("Target enter"); + + if (targets.empty() || targets.size() > LMKS_MAX_TARGETS) { + APP_LOGE("empty target or too many targets. %{public}zu", targets.size()); + return (-EINVAL); + } + + int i = 0; + int32_t buf[LMKS_START_VALUE + LMKS_MULTIPLE * LMKS_MAX_TARGETS]; + buf[i++] = LMKS_CMD_TARGET; + + for (auto target : targets) { + if (target.first < 0 || !CheckOomAdj(target.second)) { + APP_LOGE("invalid target: %{public}d %{public}d", target.first, target.second); + return (-EINVAL); + } + buf[i++] = target.first; + buf[i++] = target.second; + } + + return Write(buf, i * sizeof(int32_t)) ? ERR_OK : -1; +} + +int32_t LmksClient::ProcPrio(pid_t pid, uid_t uid, int oomAdj) +{ + APP_LOGI("ProcPrio enter"); + + if (pid < 0 || uid < 0 || !CheckOomAdj(oomAdj)) { + APP_LOGE("invalid parameter: %{public}d %{public}d %{public}d.", pid, uid, oomAdj); + return (-EINVAL); + } + + int32_t buf[4] = {LMKS_CMD_PROCPRIO, pid, uid, oomAdj}; + + return Write(buf, sizeof(buf)) ? ERR_OK : -1; +} + +int32_t LmksClient::ProcRemove(pid_t pid) +{ + APP_LOGI("ProcRemove enter"); + + if (pid < 1) { + APP_LOGE("invalid pid %{public}d.", pid); + return (-EINVAL); + } + + int32_t buf[2] = {LMKS_CMD_PROCREMOVE, pid}; + if (!Write(buf, sizeof(buf))) { + APP_LOGE("failed to write"); + return -1; + } + + LmksClientMsg msg; + if (!Read(msg.resultBuf, sizeof(int32_t))) { + APP_LOGE("failed to read"); + return -1; + } + + if (msg.result != 0) { + APP_LOGE("failed to remove process"); + return -1; + } + + APP_LOGI("success to remove process"); + return 0; +} + +bool LmksClient::ProcPurge() +{ + APP_LOGI("ProcPurge enter"); + + int32_t cmd = LMKS_CMD_PROCPURGE; + + return Write(reinterpret_cast(&cmd), sizeof(cmd)); +} + +bool LmksClient::CheckOomAdj(int v) +{ + return (APP_OOM_ADJ_MIN <= v && v <= APP_OOM_ADJ_MAX); +} + +bool LmksClient::Write(const void *buf, size_t len) +{ + if (buf == nullptr || len < 1) { + APP_LOGE("invalid parameter."); + return false; + } + + constexpr int retryTimes = 5; + for (int i = 0; i < retryTimes; ++i) { + if (socket_ < 0 && !Open()) { + std::this_thread::yield(); + continue; + } + int rLen = TEMP_FAILURE_RETRY(send(socket_, buf, len, 0)); + if (rLen <= 0) { + APP_LOGE("failed to send data to lmks err %{public}s.", strerror(errno)); + Close(); + std::this_thread::yield(); + } else { + return true; + } + } + + return false; +} + +bool LmksClient::Read(void *buf, size_t len) +{ + if (buf == nullptr || len < 1) { + APP_LOGE("invalid parameter. len %zu", len); + return false; + } + + constexpr int retryTimes = 5; + for (int i = 0; i < retryTimes; ++i) { + if (socket_ < 0 && !Open()) { + std::this_thread::yield(); + continue; + } + int rLen = TEMP_FAILURE_RETRY(recv(socket_, buf, len, 0)); + if (rLen <= 0) { + APP_LOGE("failed to recv data from lmks err %{public}s.", strerror(errno)); + Close(); + std::this_thread::yield(); + } else { + return true; + } + } + + return false; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/module_running_record.cpp b/services/appmgr/src/module_running_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c9e9b927bf5c322addea1be0f081399e305e5fd --- /dev/null +++ b/services/appmgr/src/module_running_record.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "module_running_record.h" +#include "app_log_wrapper.h" +#include "app_mgr_service_inner.h" + +namespace OHOS { +namespace AppExecFwk { +ModuleRunningRecord::ModuleRunningRecord( + const std::shared_ptr &info, const std::shared_ptr &eventHandler) + : appInfo_(info), eventHandler_(eventHandler) +{} + +ModuleRunningRecord::~ModuleRunningRecord() +{} + +void ModuleRunningRecord::Init(const HapModuleInfo &info) +{ + owenInfo_ = info; + owenState_ = ModuleRecordState::INITIALIZED_STATE; +} + +const std::string &ModuleRunningRecord::GetModuleName() const +{ + return owenInfo_.moduleName; +} + +const std::shared_ptr ModuleRunningRecord::GetAppInfo() +{ + return appInfo_; +} + +std::shared_ptr ModuleRunningRecord::GetAbilityRunningRecordByToken( + const sptr &token) const +{ + if (!token) { + APP_LOGE("token is null"); + return nullptr; + } + const auto &iter = abilities_.find(token); + if (iter != abilities_.end()) { + return iter->second; + } + return nullptr; +} + +std::shared_ptr ModuleRunningRecord::AddAbility( + const sptr &token, const std::shared_ptr &abilityInfo) +{ + APP_LOGI("Add ability."); + if (!token || !abilityInfo) { + APP_LOGE("Param abilityInfo or token is null"); + return nullptr; + } + if (GetAbilityRunningRecordByToken(token)) { + APP_LOGE("AbilityRecord already exists and no need to add"); + return nullptr; + } + auto abilityRecord = std::make_shared(abilityInfo, token); + abilities_.emplace(token, abilityRecord); + return abilityRecord; +} + +bool ModuleRunningRecord::IsLastAbilityRecord(const sptr &token) +{ + APP_LOGI("Is last ability record."); + if (!token) { + APP_LOGE("token is nullptr"); + return false; + } + + return ((abilities_.size() == 1) && (abilities_.find(token) != abilities_.end())); +} + +const std::map, std::shared_ptr> &ModuleRunningRecord::GetAbilities() + const +{ + return abilities_; +} + +std::shared_ptr ModuleRunningRecord::GetAbilityByTerminateLists( + const sptr &token) const +{ + APP_LOGI("Get ability by terminateLists."); + if (!token) { + APP_LOGE("token is null"); + return nullptr; + } + const auto &iter = terminateAbilitys_.find(token); + if (iter != terminateAbilitys_.end()) { + return iter->second; + } + return nullptr; +} + +void ModuleRunningRecord::ClearAbility(const std::shared_ptr &record) +{ + APP_LOGI("Clear ability."); + if (!record) { + APP_LOGE("Param record is null"); + return; + } + if (!GetAbilityRunningRecordByToken(record->GetToken())) { + APP_LOGE("Param record is not exist"); + return; + } + abilities_.erase(record->GetToken()); +} + +std::shared_ptr ModuleRunningRecord::GetAbilityRunningRecord(const std::string &abilityName) const +{ + APP_LOGI("Get ability running record by ability name."); + const auto &iter = std::find_if(abilities_.begin(), abilities_.end(), [&abilityName](const auto &pair) { + return pair.second->GetName() == abilityName; + }); + return ((iter == abilities_.end()) ? nullptr : iter->second); +} + +std::shared_ptr ModuleRunningRecord::GetAbilityRunningRecord(const int64_t eventId) const +{ + APP_LOGI("Get ability running record by eventId."); + const auto &iter = std::find_if(abilities_.begin(), abilities_.end(), [eventId](const auto &pair) { + return pair.second->GetEventId() == eventId; + }); + if (iter != abilities_.end()) { + return iter->second; + } + + const auto &finder = std::find_if(terminateAbilitys_.begin(), + terminateAbilitys_.end(), + [eventId](const auto &pair) { return pair.second->GetEventId() == eventId; }); + if (finder != terminateAbilitys_.end()) { + return finder->second; + } + return nullptr; +} + +void ModuleRunningRecord::OnAbilityStateChanged( + const std::shared_ptr &ability, const AbilityState state) +{ + APP_LOGI("On ability state changed."); + if (!ability) { + APP_LOGE("ability is null"); + return; + } + AbilityState oldState = ability->GetState(); + ability->SetState(state); + OptimizerAbilityStateChanged(ability, oldState); + APP_LOGI("OnAbilityStateChanged oldState:%{public}d, state:%{public}d", oldState, state); + auto serviceInner = appMgrServiceInner_.lock(); + if (serviceInner) { + serviceInner->OnAbilityStateChanged(ability, state); + } +} + +void ModuleRunningRecord::OptimizerAbilityStateChanged( + const std::shared_ptr &ability, const AbilityState state) +{ + APP_LOGI("Optimizer ability state changed."); + auto serviceInner = appMgrServiceInner_.lock(); + if (serviceInner) { + serviceInner->OptimizerAbilityStateChanged(ability, state); + } +} + +void ModuleRunningRecord::LaunchAbility(const std::shared_ptr &ability) +{ + APP_LOGI("Launch ability."); + if (!ability || !ability->GetToken()) { + APP_LOGE("null abilityRecord or abilityToken"); + return; + } + const auto &iter = abilities_.find(ability->GetToken()); + if (iter != abilities_.end() && appLifeCycleDeal_->GetApplicationClient()) { + APP_LOGI("ScheduleLaunchAbility ability:%{public}s", ability->GetName().c_str()); + appLifeCycleDeal_->LaunchAbility(ability); + ability->SetState(AbilityState::ABILITY_STATE_READY); + OptimizerAbilityStateChanged(ability, AbilityState::ABILITY_STATE_CREATE); + } +} + +void ModuleRunningRecord::LaunchPendingAbilities() +{ + APP_LOGI("Launch pending abilities."); + + if (abilities_.empty()) { + APP_LOGE("abilities_ is empty"); + return; + } + + for (auto item : abilities_) { + APP_LOGI("state : %{public}d", item.second->GetState()); + if (item.second->GetState() == AbilityState::ABILITY_STATE_CREATE) { + LaunchAbility(item.second); + } + } +} + +void ModuleRunningRecord::TerminateAbility(const sptr &token, const bool isForce) +{ + APP_LOGI("Terminate ability."); + auto abilityRecord = GetAbilityRunningRecordByToken(token); + if (!abilityRecord) { + APP_LOGE("abilityRecord is nullptr"); + return; + } + + terminateAbilitys_.emplace(token, abilityRecord); + abilities_.erase(token); + + SendEvent( + AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG, AMSEventHandler::TERMINATE_ABILITY_TIMEOUT, abilityRecord); + + if (!isForce) { + auto curAbilityState = abilityRecord->GetState(); + if (curAbilityState != AbilityState::ABILITY_STATE_BACKGROUND) { + APP_LOGE("current state(%{public}d) error", static_cast(curAbilityState)); + return; + } + } + + OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED); + if (appLifeCycleDeal_) { + appLifeCycleDeal_->ScheduleCleanAbility(token); + } else { + APP_LOGE("appLifeCycleDeal_ is null"); + } + + APP_LOGI("ModuleRunningRecord::TerminateAbility end"); +} + +void ModuleRunningRecord::SendEvent( + uint32_t msg, int64_t timeOut, const std::shared_ptr &abilityRecord) +{ + APP_LOGI("Send event"); + if (!eventHandler_) { + APP_LOGE("eventHandler_ is nullptr"); + return; + } + + AppRunningRecord::appEventId_++; + abilityRecord->SetEventId(AppRunningRecord::appEventId_); + eventHandler_->SendEvent(msg, AppRunningRecord::appEventId_, timeOut); +} + +void ModuleRunningRecord::AbilityTerminated(const sptr &token) +{ + APP_LOGI("Ability terminated."); + if (!token) { + APP_LOGE("token is null"); + return; + } + + if (!eventHandler_) { + APP_LOGE("eventHandler_ is nullptr"); + return; + } + + auto abilityRecord = GetAbilityByTerminateLists(token); + if (!abilityRecord) { + APP_LOGE("ModuleRunningRecord::AbilityTerminated can not find ability record"); + return; + } + + eventHandler_->RemoveEvent(AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG, abilityRecord->GetEventId()); + terminateAbilitys_.erase(token); +} + +void ModuleRunningRecord::SetAppMgrServiceInner(const std::weak_ptr &inner) +{ + appMgrServiceInner_ = inner; +} + +ModuleRecordState ModuleRunningRecord::GetModuleRecordState() +{ + return owenState_; +} + +void ModuleRunningRecord::SetModuleRecordState(const ModuleRecordState &state) +{ + owenState_ = state; +} + +void ModuleRunningRecord::GetHapModuleInfo(HapModuleInfo &info) +{ + info = owenInfo_; +} + +void ModuleRunningRecord::SetApplicationClient(std::shared_ptr &appLifeCycleDeal) +{ + appLifeCycleDeal_ = appLifeCycleDeal; +} + +ModuleRecordState ModuleRunningRecord::GetState() const +{ + return owenState_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/process_optimizer.cpp b/services/appmgr/src/process_optimizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..534f4cd5df5ef3a33d34a0a6106f08d85d64d772 --- /dev/null +++ b/services/appmgr/src/process_optimizer.cpp @@ -0,0 +1,711 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "process_optimizer.h" + +#include +#include +#include +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std::placeholders; + +namespace { +constexpr auto APP_SUSPEND_TIMER_NAME_PREFIX = "AppSuspendTimer"; + +constexpr int APP_OOM_ADJ_SYSTEM = -100; +// foreground process oom_adj +constexpr int APP_OOM_ADJ_FOREGROUND = 0; + +// visible process oom_adj +constexpr int APP_OOM_ADJ_VISIBLE_MIN = 1; +constexpr int APP_OOM_ADJ_VISIBLE_MAX = 199; +constexpr int APP_OOM_ADJ_VISIBLE_MAX_VALUE = 1 * 1024; + +// preceptible process oom_adj +constexpr int APP_OOM_ADJ_PERCEPTIBLE_MIN = 200; +constexpr int APP_OOM_ADJ_PERCEPTIBLE_MAX = 399; +constexpr int APP_OOM_ADJ_PERCEPTIBLE_MAX_VALUE = 4 * 1024; + +// background process oom_adj +constexpr int APP_OOM_ADJ_BACKGROUND_MIN = 400; +constexpr int APP_OOM_ADJ_BACKGROUND_MAX = 599; +constexpr int APP_OOM_ADJ_BACKGROUND_MAX_VALUE = 16 * 1024; + +// suspend process oom_adj +constexpr int APP_OOM_ADJ_SUSPEND_MIN = 600; +constexpr int APP_OOM_ADJ_SUSPEND_MAX = 799; +constexpr int APP_OOM_ADJ_SUSPEND_MAX_VALUE = 24 * 1024; + +// empty process oom_adj +[[maybe_unused]] constexpr int APP_OOM_ADJ_EMPTY_MIN = 800; +constexpr int APP_OOM_ADJ_EMPTY_MAX = 999; +constexpr int APP_OOM_ADJ_EMPTY_MAX_VALUE = 32 * 1024; + +constexpr int APP_OOM_ADJ_UNKNOWN = 1000; +constexpr int APP_OOM_ADJ_UNKNOWN_VALUE = 64 * 1024; + +constexpr std::string_view SYSTEM_UI_BUNDLE_NAME = "com.ohos.systemui"; + +constexpr int TIME_ADVANCE_RATE = 1000; + +// pressure level low +constexpr int LMKS_OOM_ADJ_LOW = 800; +// pressure level medium +constexpr int LMKS_OOM_ADJ_MEDIUM = 600; +// pressure level critical +constexpr int LMKS_OOM_ADJ_CRITICAL = 0; +constexpr int G_MEMORY_LEVEL[] = {LMKS_OOM_ADJ_LOW, LMKS_OOM_ADJ_MEDIUM, LMKS_OOM_ADJ_CRITICAL}; +} // namespace + +ProcessOptimizer::ProcessOptimizer(const LmksClientPtr &lmksClient, int suspendTimeout) + : lmksClient_(lmksClient), suspendTimeout_(suspendTimeout) +{} + +ProcessOptimizer::~ProcessOptimizer() +{ + APP_LOGI("ProcessOptimizer destructed"); + DelayedSingleton::GetInstance()->LowMemoryAlert = nullptr; + if (lmksClient_) { + lmksClient_->ProcPurge(); + } +} + +bool ProcessOptimizer::Init() +{ + APP_LOGI("initializing..."); + + if (suspendTimeout_ < 0) { + APP_LOGE("invalid suspend timeout."); + return false; + } + + if (eventHandler_) { + APP_LOGE("already inited."); + return false; + } + + // Initializing cgroup manager. + if (!DelayedSingleton::GetInstance()->IsInited()) { + APP_LOGW("cgroup manager not inited."); + if (!DelayedSingleton::GetInstance()->Init()) { + APP_LOGE("cannot init cgroup manager."); + return false; + } + } + + if (DelayedSingleton::GetInstance()->LowMemoryAlert) { + APP_LOGW("cgroup manager 'LowMemoryWarning' already registered."); + } + + DelayedSingleton::GetInstance()->LowMemoryAlert = + std::bind(&ProcessOptimizer::OnLowMemoryAlert, this, _1); + + // Initializing lmks. + LmksClientPtr lmksClientLocal = nullptr; + LmksClient::Targets targets = { + {APP_OOM_ADJ_VISIBLE_MAX_VALUE, APP_OOM_ADJ_VISIBLE_MAX}, + {APP_OOM_ADJ_PERCEPTIBLE_MAX_VALUE, APP_OOM_ADJ_PERCEPTIBLE_MAX}, + {APP_OOM_ADJ_BACKGROUND_MAX_VALUE, APP_OOM_ADJ_BACKGROUND_MAX}, + {APP_OOM_ADJ_SUSPEND_MAX_VALUE, APP_OOM_ADJ_SUSPEND_MAX}, + {APP_OOM_ADJ_EMPTY_MAX_VALUE, APP_OOM_ADJ_EMPTY_MAX}, + {APP_OOM_ADJ_UNKNOWN_VALUE, APP_OOM_ADJ_UNKNOWN}, + }; + + lmksClientLocal.swap(lmksClient_); + if (!lmksClientLocal) { + lmksClientLocal = std::make_shared(); + if (!lmksClientLocal) { + APP_LOGE("failed to create lmks client."); + return false; + } + } + + if (!lmksClientLocal->IsOpen()) { + if (lmksClientLocal->Open()) { + APP_LOGE("cannot open lmks connection."); + return false; + } + } + + if (lmksClientLocal->Target(targets) != ERR_OK) { + // print warning when lmks server not implement. + APP_LOGW("cannot init lmks."); + } + lmksClient_ = lmksClientLocal; + + // Save initialized states. + auto eventHandler = std::make_shared(EventRunner::Create()); + if (!eventHandler) { + APP_LOGE("no available event handler for current thread."); + return false; + } + + eventHandler_ = eventHandler; + + return true; +} + +void ProcessOptimizer::OnAppAdded(const AppPtr &app) +{ + if (!app) { + APP_LOGE("invalid app."); + return; + } + + if (app != appLru_.front()) { + auto it = std::find(appLru_.begin(), appLru_.end(), app); + if (it != appLru_.end()) { + APP_LOGE("app '%{public}s' already existed.", app->GetName().c_str()); + appLru_.erase(it); + } + if (app->GetState() == ApplicationState::APP_STATE_FOREGROUND) { + appLru_.push_front(app); + } else { + appLru_.push_back(app); + } + } + // Initial sched policy has been already set by appspawn. + UpdateAppOomAdj(app); +} + +void ProcessOptimizer::OnAppRemoved(const AppPtr &app) +{ + if (!app) { + APP_LOGE("invalid app."); + return; + } + + if (!lmksClient_) { + APP_LOGE("invalid lmks client."); + return; + } + + // remove timer + StopAppSuspendTimer(app); + + auto it = std::find(appLru_.begin(), appLru_.end(), app); + if (it != appLru_.end()) { + appLru_.erase(it); + } else { + APP_LOGE("app '%{public}s' is not existed.", app->GetName().c_str()); + } + + auto priorityObject = app->GetPriorityObject(); + if (!priorityObject) { + APP_LOGE("invalid priority object."); + return; + } + + if (lmksClient_->ProcRemove(priorityObject->GetPid()) != ERR_OK) { + APP_LOGE("failed to remove app '%{public}s'(%{publid}d) from lmks.", + app->GetName().c_str(), + priorityObject->GetPid()); + } +} + +void ProcessOptimizer::OnAppStateChanged(const AppPtr &app, const ApplicationState oldState) +{ + if (!app) { + APP_LOGE("invalid app."); + return; + } + + auto priorityObject = app->GetPriorityObject(); + if (!priorityObject) { + APP_LOGE("invalid priority object."); + return; + } + + auto curState = app->GetState(); + APP_LOGD("ability state changed to %{public}d.", curState); + if (curState == oldState) { + APP_LOGW("no change."); + return; + } + + if (curState == ApplicationState::APP_STATE_FOREGROUND) { + if (app != appLru_.front()) { + auto it = std::find(appLru_.begin(), appLru_.end(), app); + if (it != appLru_.end()) { + appLru_.erase(it); + } else { + APP_LOGE("app '%{public}s' is not existed.", app->GetName().c_str()); + } + appLru_.push_front(app); + } + } + + UpdateAppSchedPolicy(app); + UpdateAppOomAdj(app); + + // only background also no visible and no preceptible can freezer + if (curState == ApplicationState::APP_STATE_BACKGROUND && + (!priorityObject->GetVisibleStatus() && !priorityObject->GetPerceptibleStatus())) { + StartAppSuspendTimer(app); + } + + if (oldState == ApplicationState::APP_STATE_BACKGROUND && curState != ApplicationState::APP_STATE_SUSPENDED) { + StopAppSuspendTimer(app); + } +} + +void ProcessOptimizer::OnAbilityStarted(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + APP_LOGI("OnAbilityStarted."); +} + +void ProcessOptimizer::OnAbilityConnected(const AbilityPtr &ability, const AbilityPtr &targetAbility) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + if (!targetAbility) { + APP_LOGE("invalid targetAbility."); + return; + } + + APP_LOGI("OnAbilityConnected end."); +} + +void ProcessOptimizer::OnAbilityDisconnected(const AbilityPtr &ability, const AbilityPtr &targetAbility) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + if (!targetAbility) { + APP_LOGE("invalid targetAbility."); + return; + } + + APP_LOGI("OnAbilityDisconnected end."); +} + +void ProcessOptimizer::OnAbilityStateChanged(const AbilityPtr &ability, const AbilityState oldState) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + APP_LOGI("OnAbilityStateChanged end."); +} + +void ProcessOptimizer::OnAbilityVisibleChanged(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + APP_LOGI("OnAbilityVisibleChanged end."); +} + +void ProcessOptimizer::OnAbilityPerceptibleChanged(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + } + + APP_LOGI("OnAbilityPerceptibleChanged end."); +} + +void ProcessOptimizer::OnAbilityRemoved(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + APP_LOGI("OnAbilityRemoved end."); +} + +bool ProcessOptimizer::SetAppOomAdj(const AppPtr &app, int oomAdj) +{ + if (!app) { + APP_LOGE("invalid app."); + return false; + } + + if (!LmksClient::CheckOomAdj(oomAdj)) { + APP_LOGE("invalid oom adj %{public}d.", oomAdj); + return false; + } + + if (!lmksClient_) { + APP_LOGE("invalid lmks client."); + return false; + } + + auto priorityObject = app->GetPriorityObject(); + if (!priorityObject) { + APP_LOGE("invalid priority object."); + return false; + } + + if (priorityObject->GetCurAdj() == oomAdj) { + APP_LOGW("oom adj has no change."); + return true; + } + + if (lmksClient_->ProcPrio(priorityObject->GetPid(), app->GetUid(), oomAdj) != ERR_OK) { + // print warning when lmks server not implement. + APP_LOGW("lmks proc prio failed."); + } + + priorityObject->SetCurAdj(oomAdj); + + return true; +} + +bool ProcessOptimizer::SetAppSchedPolicy(const AppPtr &app, const CgroupManager::SchedPolicy schedPolicy) +{ + if (!app) { + APP_LOGE("invalid app."); + return false; + } + + auto priorityObject = app->GetPriorityObject(); + if (!priorityObject) { + APP_LOGE("invalid priority object."); + return false; + } + + auto oldSchedPolicy = priorityObject->GetCurCgroup(); + if (oldSchedPolicy == schedPolicy) { + APP_LOGW("no change."); + return true; + } + + bool result = + DelayedSingleton::GetInstance()->SetProcessSchedPolicy(priorityObject->GetPid(), schedPolicy); + if (result) { + priorityObject->SetCurCgroup(schedPolicy); + if (schedPolicy == CgroupManager::SCHED_POLICY_FREEZED) { + if (AppSuspended) { + AppSuspended(app); + } + } else if (oldSchedPolicy == CgroupManager::SCHED_POLICY_FREEZED) { + if (AppResumed) { + AppResumed(app); + } + } + } + + return result; +} + +void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel level) +{ + APP_LOGI("OnLowMemoryAlert level %{public}d", level); + // Find the oldest background app. + for (auto it(appLru_.rbegin()); it != appLru_.rend(); ++it) { + auto appRecord = (*it); + if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_BACKGROUND) { + APP_LOGI("OnLowMemoryAlert bundle:%{public}s, level:%{public}d", + appRecord->GetBundleName().c_str(), level); + AppLowMemoryAlert(*it, level); + break; + } + } + + // send pid which will be killed. + std::list::iterator iter = appLru_.begin(); + while (iter != appLru_.end()) { + auto appRecord = (*iter); + if (!appRecord) { + continue; + } + auto priorityObject = appRecord->GetPriorityObject(); + if (priorityObject != nullptr && priorityObject->GetCurAdj() >= G_MEMORY_LEVEL[level]) { + auto pid = priorityObject->GetPid(); + if (pid <= 0) { + APP_LOGE("pid %{public}d invalid", pid); + iter = appLru_.erase(iter); + continue; + } + + APP_LOGI("remove pid (%{publid}d) from lmks, bundle:%{public}s", pid, appRecord->GetBundleName().c_str()); + if (lmksClient_->ProcRemove(pid) == ERR_OK) { + iter = appLru_.erase(iter); + continue; + } + APP_LOGE("remove error, pid:%{publid}d, bundle:%{public}s", pid, appRecord->GetBundleName().c_str()); + } + iter++; + } +} + +bool ProcessOptimizer::UpdateAppOomAdj(const AppPtr &app) +{ + if (!app) { + APP_LOGE("invalid app."); + return false; + } + APP_LOGI("UpdateAppOomAdj bundleName[%{public}s] state[%{public}d] pid[%{public}d] curadj[%{public}d]", + app->GetBundleName().c_str(), + app->GetState(), + app->GetPriorityObject()->GetPid(), + app->GetPriorityObject()->GetCurAdj()); + + auto priorityObject = app->GetPriorityObject(); + if (!priorityObject) { + APP_LOGE("invalid priority object."); + return false; + } + // special set launcher and systemui adj + if (app->IsLauncherApp() || app->GetBundleName() == SYSTEM_UI_BUNDLE_NAME) { + return SetAppOomAdj(app, APP_OOM_ADJ_SYSTEM); + } + + auto state = app->GetState(); + if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_CREATE || + state == ApplicationState::APP_STATE_READY) { + return SetAppOomAdj(app, APP_OOM_ADJ_FOREGROUND); + } + + int oomAdj; + int oomAdjMax; + if (!GetAppOomAdj(app, state, oomAdj, oomAdjMax)) { + return false; + } + + for (auto curApp : appLru_) { + if (curApp->GetState() != state) { + continue; + } + // adj of launcher and systemui is always APP_OOM_ADJ_SYSTEM + if (curApp->IsLauncherApp() || curApp->GetBundleName() == SYSTEM_UI_BUNDLE_NAME) { + continue; + } + + SetAppOomAdj(curApp, oomAdj); + if (oomAdj < oomAdjMax) { + oomAdj += 1; + } + } + return true; +} + +bool ProcessOptimizer::GetAppOomAdj(const AppPtr &app, ApplicationState state, int &oomAdj, int &oomAdjMax) +{ + auto priorityObject = app->GetPriorityObject(); + if (!priorityObject) { + APP_LOGE("invalid priority object."); + return false; + } + + switch (state) { + case ApplicationState::APP_STATE_BACKGROUND: + oomAdj = APP_OOM_ADJ_BACKGROUND_MIN; + oomAdjMax = APP_OOM_ADJ_BACKGROUND_MAX; + + // perceptible oom_adj + if (priorityObject->GetPerceptibleStatus()) { + oomAdj = APP_OOM_ADJ_PERCEPTIBLE_MIN; + oomAdjMax = APP_OOM_ADJ_PERCEPTIBLE_MAX; + } + + // visible oom_adj + if (priorityObject->GetVisibleStatus()) { + oomAdj = APP_OOM_ADJ_VISIBLE_MIN; + oomAdjMax = APP_OOM_ADJ_VISIBLE_MAX; + } + break; + case ApplicationState::APP_STATE_SUSPENDED: + oomAdj = APP_OOM_ADJ_SUSPEND_MIN; + oomAdjMax = APP_OOM_ADJ_SUSPEND_MAX; + break; + default: + oomAdj = APP_OOM_ADJ_UNKNOWN; + oomAdjMax = APP_OOM_ADJ_UNKNOWN; + break; + } + return true; +} + +bool ProcessOptimizer::UpdateAppSchedPolicy(const AppPtr &app) +{ + if (!app) { + APP_LOGE("invalid app."); + return false; + } + + bool ret = false; + + switch (app->GetState()) { + case ApplicationState::APP_STATE_CREATE: + case ApplicationState::APP_STATE_READY: + case ApplicationState::APP_STATE_FOREGROUND: + ret = SetAppSchedPolicy(app, CgroupManager::SCHED_POLICY_DEFAULT); + break; + case ApplicationState::APP_STATE_BACKGROUND: + ret = SetAppSchedPolicy(app, CgroupManager::SCHED_POLICY_BACKGROUND); + break; + case ApplicationState::APP_STATE_SUSPENDED: + // SUSPEND state should be set in 'ProcessOptimizer::SuspendApp()' (to be specific, + // in 'AppSuspended' callback), and the sched policy has been set in it, so do nothing here. + ret = true; + break; + default: + ret = true; + break; + } + return ret; +} + +void ProcessOptimizer::StartAppSuspendTimer(const AppPtr &app) +{ + if (!app) { + APP_LOGE("invalid app."); + return; + } + + APP_LOGI("starting suspend timer for app '%{public}s'...", app->GetName().c_str()); + + if (!eventHandler_) { + APP_LOGE("invalid event handler."); + return; + } + + auto timerName = GetAppSuspendTimerName(app); + if (timerName.empty()) { + APP_LOGE("invalid suspend timer name."); + return; + } + + auto it = suspendTimers_.find(timerName); + if (it != suspendTimers_.end()) { + APP_LOGW("app '%{public}s' suspend timer already started.", app->GetName().c_str()); + return; + } + + suspendTimers_.emplace(timerName); + + eventHandler_->PostTask( + [=]() { + auto finder = suspendTimers_.find(timerName); + if (finder != suspendTimers_.end()) { + APP_LOGD("removing app '%{public}s' '%{public}s' suspend timer name...", + timerName.c_str(), + app->GetName().c_str()); + suspendTimers_.erase(finder); + } else { + APP_LOGE("invalid suspend timer for app '%{public}s' '%{public}s'.", + timerName.c_str(), + app->GetName().c_str()); + } + SuspendApp(app); + }, + timerName, + suspendTimeout_); +} + +void ProcessOptimizer::StopAppSuspendTimer(const AppPtr &app) +{ + if (!app) { + APP_LOGE("invalid app."); + return; + } + + APP_LOGI("stopping suspend timer for app '%{public}s'...", app->GetName().c_str()); + + if (!eventHandler_) { + APP_LOGE("invalid event handler."); + return; + } + + auto timerName = GetAppSuspendTimerName(app); + if (timerName.empty()) { + APP_LOGE("invalid suspend timer name."); + return; + } + + auto it = suspendTimers_.find(timerName); + if (it == suspendTimers_.end()) { + APP_LOGW("app '%{public}s' suspend timer not started.", app->GetName().c_str()); + return; + } + + suspendTimers_.erase(it); + eventHandler_->RemoveTask(timerName); +} + +void ProcessOptimizer::SuspendApp(const AppPtr &app) +{ + if (!app) { + APP_LOGE("invalid app."); + return; + } + + APP_LOGI("suspending app '%{public}s'...", app->GetName().c_str()); + + if (app->GetState() == ApplicationState::APP_STATE_SUSPENDED) { + APP_LOGE("app '%{public}s' already suspended.", app->GetName().c_str()); + return; + } + + if (!SetAppSchedPolicy(app, CgroupManager::SCHED_POLICY_FREEZED)) { + APP_LOGE("failed to suspend app '%s'.", app->GetName().c_str()); + } +} + +std::string ProcessOptimizer::GetAppSuspendTimerName(const AppPtr &app) +{ + std::string ret; + + if (app) { + auto priorityObject = app->GetPriorityObject(); + if (priorityObject) { + ret = APP_SUSPEND_TIMER_NAME_PREFIX + std::to_string(priorityObject->GetPid()); + } + } + + return ret; +} + +void ProcessOptimizer::SetAppFreezingTime(int time) +{ + APP_LOGE("input second time:[%{public}d]", time); + + if (time > APP_SUSPEND_TIMEOUT_MAX && time < 0) { + APP_LOGE("input time error."); + return; + } + + suspendTimeout_ = time; + // convert seconds to milliseconds + suspendTimeout_ *= TIME_ADVANCE_RATE; +} + +void ProcessOptimizer::GetAppFreezingTime(int &time) +{ + time = suspendTimeout_ / TIME_ADVANCE_RATE; + APP_LOGE("current freez time:[%{public}d]", time); + return; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/process_optimizer_uba.cpp b/services/appmgr/src/process_optimizer_uba.cpp new file mode 100644 index 0000000000000000000000000000000000000000..679243386a983b981c7362714d4e5f9e0485b5d6 --- /dev/null +++ b/services/appmgr/src/process_optimizer_uba.cpp @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "process_optimizer_uba.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +ProcessOptimizerUBA::BaseAbilityAction::BaseAbilityAction(const AbilityPtr &ability) + : time_(Clock::now()), name_(ability->GetName()) +{} + +ProcessOptimizerUBA::TimePoint ProcessOptimizerUBA::BaseAbilityAction::GetTime() const +{ + return time_; +} + +std::string ProcessOptimizerUBA::BaseAbilityAction::GetTimeString() const +{ + std::time_t tmp = Clock::to_time_t(time_); + char *pTime = std::ctime(&tmp); + return (pTime == nullptr) ? "" : std::string(pTime); +} + +const std::string &ProcessOptimizerUBA::BaseAbilityAction::GetName() const +{ + return name_; +} + +ProcessOptimizerUBA::StartAbilityAction::StartAbilityAction(const AbilityPtr &ability, const AbilityPtr &preAbility) + : BaseAbilityAction(ability), preName_(preAbility ? preAbility->GetName() : std::string()) +{} + +const std::string &ProcessOptimizerUBA::StartAbilityAction::GetPreName() const +{ + return preName_; +} + +ProcessOptimizerUBA::ConnectAbilityAction::ConnectAbilityAction( + const AbilityPtr &ability, const AbilityPtr &targetAbility) + : BaseAbilityAction(ability), targetName_(targetAbility->GetName()) +{} + +const std::string &ProcessOptimizerUBA::ConnectAbilityAction::GetTargetName() const +{ + return targetName_; +} + +ProcessOptimizerUBA::DisconnectAbilityAction::DisconnectAbilityAction( + const AbilityPtr &ability, const AbilityPtr &targetAbility) + : BaseAbilityAction(ability), targetName_(targetAbility->GetName()) +{} + +const std::string &ProcessOptimizerUBA::DisconnectAbilityAction::GetTargetName() const +{ + return targetName_; +} + +ProcessOptimizerUBA::ChangeAbilityStateAction::ChangeAbilityStateAction( + const AbilityPtr &ability, const AbilityState oldState) + : BaseAbilityAction(ability), oldState_(oldState), newState_(ability->GetState()) +{} + +AbilityState ProcessOptimizerUBA::ChangeAbilityStateAction::GetOldState() const +{ + return oldState_; +} + +AbilityState ProcessOptimizerUBA::ChangeAbilityStateAction::GetNewState() const +{ + return newState_; +} + +ProcessOptimizerUBA::ChangeAbilityVisible::ChangeAbilityVisible(const AbilityPtr &ability) + : BaseAbilityAction(ability){}; + +ProcessOptimizerUBA::ChangeAbilityPerceptible::ChangeAbilityPerceptible(const AbilityPtr &ability) + : BaseAbilityAction(ability){}; + +ProcessOptimizerUBA::RemoveAbilityAction::RemoveAbilityAction(const AbilityPtr &ability) : BaseAbilityAction(ability) +{} + +ProcessOptimizerUBA::ProcessOptimizerUBA( + const UbaServicePtr &ubaService, const LmksClientPtr &lmksClient, int suspendTimeout) + : ProcessOptimizer(lmksClient, suspendTimeout), ubaService_(ubaService), abilityActionCount_(0) +{ + APP_LOGI("ProcessOptimizerUBA ProcessOptimizerUBA start !"); +} + +ProcessOptimizerUBA::~ProcessOptimizerUBA() +{ + if (abilityActionCount_ > 0) { + CommitAbilityActions(); + } +} + +void ProcessOptimizerUBA::OnAppAdded(const AppPtr &app) +{ + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAppAdded(app); + } +} + +void ProcessOptimizerUBA::OnAppRemoved(const AppPtr &app) +{ + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAppRemoved(app); + } +} + +void ProcessOptimizerUBA::OnAppStateChanged(const AppPtr &app, const ApplicationState oldState) +{ + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAppStateChanged(app, oldState); + } +} + +void ProcessOptimizerUBA::OnAbilityStarted(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + AbilityPtr preAbility; + auto preToken = ability->GetPreToken(); + + if (GetAbilityByToken) { + // 'preAbility' can be a nullptr. + preAbility = GetAbilityByToken(preToken); + } else { + APP_LOGW(" 'GetAbilityByToken' is not registered."); + } + + RecordAbilityAction(ability, preAbility); + + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAbilityStarted(ability); + } +} + +void ProcessOptimizerUBA::OnAbilityConnected(const AbilityPtr &ability, const AbilityPtr &targetAbility) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + if (!targetAbility) { + APP_LOGE("invalid targetAbility."); + return; + } + + RecordAbilityAction(ability, targetAbility); + + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAbilityConnected(ability, targetAbility); + } +} + +void ProcessOptimizerUBA::OnAbilityDisconnected(const AbilityPtr &ability, const AbilityPtr &targetAbility) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + if (!targetAbility) { + APP_LOGE("invalid targetAbility."); + return; + } + + RecordAbilityAction(ability, targetAbility); + + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAbilityDisconnected(ability, targetAbility); + } +} + +void ProcessOptimizerUBA::OnAbilityStateChanged(const AbilityPtr &ability, const AbilityState oldState) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + RecordAbilityAction(ability, oldState); + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAbilityStateChanged(ability, oldState); + } +} + +void ProcessOptimizerUBA::OnAbilityVisibleChanged(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + RecordAbilityAction(ability); + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAbilityVisibleChanged(ability); + } +} + +void ProcessOptimizerUBA::OnAbilityPerceptibleChanged(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + RecordAbilityAction(ability); + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAbilityPerceptibleChanged(ability); + } +} + +void ProcessOptimizerUBA::OnAbilityRemoved(const AbilityPtr &ability) +{ + if (!ability) { + APP_LOGE("invalid ability."); + return; + } + + RecordAbilityAction(ability); + + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnAbilityRemoved(ability); + } +} + +void ProcessOptimizerUBA::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel level) +{ + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::OnLowMemoryAlert(level); + } +} + +void ProcessOptimizerUBA::CommitAbilityActions() +{ + auto n = abilityActionCount_; + abilityActionCount_ = 0; + auto ubaService = GetUbaService(); + if (!ubaService) { + APP_LOGE("uba is not available."); + return; + } + + APP_LOGI("committing %{public}zu actions...", n); + + for (size_t i = 0; i < n; ++i) { + auto &abilityAction = abilityActionCache_[i]; + + auto startAbilityAction = std::get_if(&abilityAction); + if (startAbilityAction) { + CommitStartAbilityAction(*startAbilityAction, i); + continue; + } + auto connectAbilityAction = std::get_if(&abilityAction); + if (connectAbilityAction) { + CommitConnectAbilityAction(*connectAbilityAction, i); + continue; + } + auto disconnectAbilityAction = std::get_if(&abilityAction); + if (disconnectAbilityAction) { + CommitDisconnectAbilityAction(*disconnectAbilityAction, i); + continue; + } + auto changedAbilityStateAction = std::get_if(&abilityAction); + if (changedAbilityStateAction) { + CommitChangedAbilityStateAction(*changedAbilityStateAction, i); + continue; + } + auto removeAbilityAction = std::get_if(&abilityAction); + if (removeAbilityAction) { + CommitRemoveAbilityAction(*removeAbilityAction, i); + continue; + } + } +} + +void ProcessOptimizerUBA::CommitStartAbilityAction(const StartAbilityAction& action, size_t index) +{ + APP_LOGI(" [%{public}zu] %{public}s ability '%{public}s' starts '%{public}s'", + index, + action.GetTimeString().c_str(), + action.GetPreName().c_str(), + action.GetName().c_str()); + // commit action +} + +void ProcessOptimizerUBA::CommitConnectAbilityAction(const ConnectAbilityAction& action, size_t index) +{ + APP_LOGI(" [%{public}zu] %{public}s ability '%{public}s' connect to '%{public}s'", + index, + action.GetTimeString().c_str(), + action.GetName().c_str(), + action.GetTargetName().c_str()); + // commit action +} + +void ProcessOptimizerUBA::CommitDisconnectAbilityAction(const DisconnectAbilityAction& action, size_t index) +{ + APP_LOGI(" [%{public}zu] %{public}s '%{public}s' ability disconnect with '%{public}s'", + index, + action.GetTimeString().c_str(), + action.GetName().c_str(), + action.GetTargetName().c_str()); + // commit action +} + +void ProcessOptimizerUBA::CommitChangedAbilityStateAction(const ChangeAbilityStateAction& action, size_t index) +{ + APP_LOGI(" [%{public}zu] %{public}s ability '%{public}s' state changed from %{public}d to %{public}d.", + index, + action.GetTimeString().c_str(), + action.GetName().c_str(), + action.GetOldState(), + action.GetNewState()); + // commit action +} + +void ProcessOptimizerUBA::CommitRemoveAbilityAction(const RemoveAbilityAction& action, size_t index) +{ + APP_LOGI(" [%{public}zu] %{public}s '%{public}s' removed.", + index, + action.GetTimeString().c_str(), + action.GetName().c_str()); + // commit action +} + +UbaServicePtr ProcessOptimizerUBA::GetUbaService() +{ + if (ubaService_) { + return ubaService_; + } + + // try to get uba service here. + return nullptr; +} + +void ProcessOptimizerUBA::SetAppFreezingTime(int time) +{ + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::SetAppFreezingTime(time); + } +} + +void ProcessOptimizerUBA::GetAppFreezingTime(int &time) +{ + auto ubaService = GetUbaService(); + if (ubaService) { + APP_LOGI("ubaService implement."); + } else { + ProcessOptimizer::GetAppFreezingTime(time); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/continuation/distributed/distributed_client.cpp b/services/appmgr/src/remote_client_manager.cpp similarity index 32% rename from frameworks/kits/ability/native/src/continuation/distributed/distributed_client.cpp rename to services/appmgr/src/remote_client_manager.cpp index 14bace8ba437af41dd6d23bacf0d5da6c320784e..711b395c0d57de2491df62c07cafaf88066a5ff5 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/distributed_client.cpp +++ b/services/appmgr/src/remote_client_manager.cpp @@ -12,76 +12,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "distributed_client.h" -#include "app_log_wrapper.h" -#include "if_system_ability_manager.h" -#include "ipc_skeleton.h" +#include "remote_client_manager.h" + #include "iservice_registry.h" #include "system_ability_definition.h" +#include "app_log_wrapper.h" + namespace OHOS { namespace AppExecFwk { -std::shared_ptr DistributedClient::instance_ = nullptr; -std::mutex DistributedClient::mutex_; - -std::shared_ptr DistributedClient::GetInstance() -{ - if (instance_ == nullptr) { - std::lock_guard lock(mutex_); - if (instance_ == nullptr) { - instance_ = std::make_shared(); - } - } - return instance_; -} - -DistributedClient::DistributedClient() +RemoteClientManager::RemoteClientManager() : appSpawnClient_(std::make_shared()) {} -DistributedClient::~DistributedClient() +RemoteClientManager::~RemoteClientManager() {} -ErrCode DistributedClient::Connect() +std::shared_ptr RemoteClientManager::GetSpawnClient() { - APP_LOGI("%{public}s called begin", __func__); - std::lock_guard lock(mutex_); - - if (remoteObject_ == nullptr) { - sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemManager == nullptr) { - APP_LOGE("%{public}s:fail to get System Ability Manager", __func__); - return GET_SYSTEM_ABILITY_SERVICE_FAILED; - } - remoteObject_ = systemManager->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); - if (remoteObject_ == nullptr) { - APP_LOGE("%{public}s:fail to get Distributed Ability Service", __func__); - return GET_DISTRIBUTED_ABILITY_SERVICE_FAILED; - } - } - - if (dmsProxy_ == nullptr) { - dmsProxy_ = std::make_shared(remoteObject_); + if (appSpawnClient_) { + return appSpawnClient_; } + return nullptr; +} - APP_LOGI("%{public}s called end", __func__); - return ERR_OK; +void RemoteClientManager::SetSpawnClient(const std::shared_ptr &appSpawnClient) +{ + appSpawnClient_ = appSpawnClient; } -ErrCode DistributedClient::NotifyCompleteContinuation( - const std::u16string &devId, int32_t sessionId, bool isSuccess, const sptr &reverseScheduler) +sptr RemoteClientManager::GetBundleManager() { - APP_LOGI("%{public}s called", __func__); - if (remoteObject_ == nullptr) { - ErrCode err = Connect(); - if (err != ERR_OK) { - return DISTRIBUTED_ABILITY_SERVICE_NOT_CONNECTED; + if (bundleManager_ == nullptr) { + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager != nullptr) { + bundleManager_ = + iface_cast(systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID)); + } else { + APP_LOGE("AppMgrServiceInner::GetBundleManager fail to get SAMGR"); } } + return bundleManager_; +} - // there need a params for reverseScheduler - dmsProxy_->NotifyCompleteContinuation(devId, sessionId, isSuccess); - return 0; +void RemoteClientManager::SetBundleManager(sptr bundleManager) +{ + bundleManager_ = bundleManager; } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/start_via_asan.cpp b/services/appmgr/src/start_via_asan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eaef73e15cb7cfe9f553add9dc370b066f4de19a --- /dev/null +++ b/services/appmgr/src/start_via_asan.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "start_via_asan.h" + +#include "app_log_wrapper.h" +#include "properties.h" + +namespace OHOS { +namespace AppExecFwk { +StartViaAsan::StartViaAsan() +{} + +StartViaAsan::~StartViaAsan() +{} + +bool StartViaAsan::IsAsanVersion(const std::string &name) const +{ + if (name.empty()) { + return false; + } + + std::string defaultWrapValue = ""; + std::string wrapAppName = "wrap." + name; + std::string propValue = GetProperty(wrapAppName, defaultWrapValue); + if (propValue != defaultWrapValue) { + APP_LOGI("%{public}s system prop set, value is %{public}s", wrapAppName.c_str(), propValue.c_str()); + return true; + } + APP_LOGI("%{public}s system prop not set", wrapAppName.c_str()); + return false; +} + +void StartViaAsan::GetAsanStartMsg(AppSpawnStartMsg &startMsg) const +{ + if (startMsg.arg.empty()) { + startMsg.arg = "wrap." + startMsg.procName; + } else { + startMsg.arg += " wrap." + startMsg.procName; + } + startMsg.argsNum++; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/system_environment_information.cpp b/services/appmgr/src/system_environment_information.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd50b8b03d1807449d30c54a66f07d4ab60fe095 --- /dev/null +++ b/services/appmgr/src/system_environment_information.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "system_environment_information.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "kernel_system_memory_info.h" +#include "securec.h" + +namespace OHOS { +namespace AppExecFwk { +namespace SystemEnv { +namespace { +static const int BYTES_KB = 1024; +} +void KernelSystemMemoryInfo::Init(std::map &memInfo) +{ + auto findData = [&] (const std::string& key) -> std::string { + auto iter = memInfo.find(key); + if (iter != memInfo.end()) { + APP_LOGD("key[%{public}s] data[%{public}s]", key.c_str(), iter->second.c_str()); + return iter->second; + } else { + APP_LOGE("key[%{public}s]", key.c_str()); + return std::string(""); + } + }; + + memTotal_ = std::stoll(findData(std::string("MemTotal"))) * BYTES_KB; + memFree_ = std::stoll(findData(std::string("MemFree"))) * BYTES_KB; + memAvailable_ = std::stoll(findData(std::string("MemAvailable"))) * BYTES_KB; + buffers_ = std::stoll(findData(std::string("Buffers"))) * BYTES_KB; + cached_ = std::stoll(findData(std::string("Cached"))) * BYTES_KB; + swapCached_ = std::stoll(findData(std::string("SwapCached"))) * BYTES_KB; +} + +int64_t KernelSystemMemoryInfo::GetMemTotal() const +{ + return memTotal_; +} + +int64_t KernelSystemMemoryInfo::GetMemFree() const +{ + return memFree_; +} + +int64_t KernelSystemMemoryInfo::GetMemAvailable() const +{ + return memAvailable_; +} + +int64_t KernelSystemMemoryInfo::GetBuffers() const +{ + return buffers_; +} + +int64_t KernelSystemMemoryInfo::GetCached() const +{ + return cached_; +} + +int64_t KernelSystemMemoryInfo::GetSwapCached() const +{ + return swapCached_; +} + +static void RequestSystemMemoryInfo(std::map &memInfo) +{ + std::regex rLabel("[\\w()]+"); + std::regex rData("\\d+"); + const int buffsize = 1024; + char buff[buffsize] = {0}; + + FILE *fp = popen("cat /proc/meminfo", "r"); + if (fp == nullptr) { + APP_LOGE("open meminfo failed"); + return; + } + + while (fgets(buff, sizeof(buff), fp) != nullptr) { + std::string strbuf(buff); + memset_s(buff, sizeof(buff), 0x00, sizeof(buff)); + std::smatch sm; + std::smatch smData; + bool flag = false; + flag = std::regex_search(strbuf, sm, rLabel); + if (!flag) { + APP_LOGE("open meminfo failed"); + continue; + } + std::string strLabel = sm[0]; + strbuf = sm.suffix().str(); + flag = std::regex_search(strbuf, sm, rData); + if (!flag) { + APP_LOGE("open meminfo failed"); + continue; + } + std::string strData = sm[0]; + memInfo[strLabel] = strData; + } + + pclose(fp); + fp = nullptr; +} + +void GetMemInfo(KernelSystemMemoryInfo &memInfo) +{ + std::map memListInfo; + RequestSystemMemoryInfo(memListInfo); + memInfo.Init(memListInfo); +} +} // namespace SystemEnv +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/src/system_environment_information.h b/services/appmgr/src/system_environment_information.h new file mode 100644 index 0000000000000000000000000000000000000000..81130d2fa8c35c37a2dbaa05e7daf45303cbfd08 --- /dev/null +++ b/services/appmgr/src/system_environment_information.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_SYSTEM_ENVIRONMENT_INFORMATION_H +#define FOUNDATION_APPEXECFWK_SERVICES_SYSTEM_ENVIRONMENT_INFORMATION_H + +#include "kernel_system_memory_info.h" + +namespace OHOS { +namespace AppExecFwk { +namespace SystemEnv { +void GetMemInfo(KernelSystemMemoryInfo &memInfo); +} // namespace SystemEnv +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_SYSTEM_ENVIRONMENT_INFORMATION_H \ No newline at end of file diff --git a/services/appmgr/test/BUILD.gn b/services/appmgr/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4da5d39b479fd84d3cb1c7f5785ad2d8f9080fbc --- /dev/null +++ b/services/appmgr/test/BUILD.gn @@ -0,0 +1,128 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("appmgr_test_config") { + configs = [ + "${services_path}/appmgr:appmgr_config", + "${aafwk_path}/interfaces/innerkits/app_manager:appmgr_sdk_config", + "${aafwk_path}/services/test:services_mock_ams_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base_sdk_config", + ] + + defines = [ + "APP_LOG_TAG = \"AppMgrService\"", + "LOG_DOMAIN = 0xD00111E", + ] + + include_dirs = [ "${services_path}/appmgr/test/mock/include" ] +} + +ohos_source_set("appmgr_test_source") { + testonly = true + + sources = [ + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_launch_data.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_process_data.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_record_id.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_host.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_state_callback_proxy.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_task_info.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/profile.cpp", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/application_info.cpp", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/bundle_user_info.cpp", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/element_name.cpp", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/running_process_info.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "${aafwk_path}/services/appmgr/include/lmks", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include", + ] + + public_configs = [ + ":appmgr_test_config", + "//utils/native/base:utils_config", + ] + + public_deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "//base/global/i18n_standard/frameworks/intl:intl_util", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + ] + + external_deps = [ + "bytrace_standard:bytrace_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ + "unittest/ams_ability_running_record_test:unittest", + "unittest/ams_app_death_recipient_test:unittest", + "unittest/ams_app_life_cycle_test:unittest", + "unittest/ams_app_mgr_client_test:unittest", + "unittest/ams_app_running_record_test:unittest", + "unittest/ams_app_state_callback_test:unittest", + "unittest/ams_app_workflow_test:unittest", + + # "unittest/ams_cgroup_manager_test:unittest", + "unittest/ams_ipc_interface_test:unittest", + + # "unittest/ams_lmks_client_test:unittest", + "unittest/ams_mgr_scheduler_test:unittest", + + # "unittest/ams_process_optimizer_test:unittest", + "unittest/ams_recent_app_list_test:unittest", + "unittest/ams_service_app_spawn_client_test:unittest", + "unittest/ams_service_app_spawn_msg_wrapper_test:unittest", + "unittest/ams_service_app_spawn_socket_test:unittest", + "unittest/ams_service_event_drive_test:unittest", + "unittest/ams_service_load_ability_process_test:unittest", + "unittest/ams_service_startup_test:unittest", + "unittest/app_mgr_service_event_handler_test:unittest", + ] +} diff --git a/services/appmgr/test/mock/include/mock_ability_token.h b/services/appmgr/test/mock/include/mock_ability_token.h new file mode 100644 index 0000000000000000000000000000000000000000..2a43c7d652a418eec9212b9f478f89def85c7847 --- /dev/null +++ b/services/appmgr/test/mock/include/mock_ability_token.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_ABILITY_TOKEN_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_ABILITY_TOKEN_H + +#include "nocopyable.h" +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +class IAbilityToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AbilityToken"); +}; +DECLARE_INTERFACE_DESCRIPTOR(u"IAbilityToken"); + +class MockAbilityToken : public IRemoteStub { +public: + MockAbilityToken() = default; + virtual ~MockAbilityToken() = default; + + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + return 0; + } + +private: + DISALLOW_COPY_AND_MOVE(MockAbilityToken); +}; + +class AbilityTokenProxy : public IRemoteProxy { +public: + explicit AbilityTokenProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~AbilityTokenProxy() = default; + +private: + DISALLOW_COPY_AND_MOVE(AbilityTokenProxy); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_ABILITY_TOKEN_H diff --git a/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h b/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..c4082c886801cec9c20b425ad972af134506042d --- /dev/null +++ b/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_MOCK_AMS_MGR_SCHEDULER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_MOCK_AMS_MGR_SCHEDULER_H + +#include "gmock/gmock.h" +#include "ams_mgr_scheduler.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAmsMgrScheduler : public AmsMgrStub { +public: + MOCK_METHOD4(LoadAbility, + void(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + MOCK_METHOD5(AbilityBehaviorAnalysis, + void(const sptr &token, const sptr &preToken, + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState)); + MOCK_METHOD1(TerminateAbility, void(const sptr &token)); + MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); + MOCK_METHOD0(Reset, void()); + MOCK_METHOD1(KillProcessByAbilityToken, void(const sptr &token)); + MOCK_METHOD1(KillProcessesByUserId, void(int32_t userId)); + MOCK_METHOD2(KillProcessWithAccount, int(const std::string &, const int)); + MOCK_METHOD1(KillApplication, int32_t(const std::string &bundleName)); + MOCK_METHOD2(KillApplicationByUid, int(const std::string &, const int uid)); + MOCK_METHOD0(IsReady, bool()); + MOCK_METHOD1(AbilityAttachTimeOut, void(const sptr &token)); + MOCK_METHOD1(PrepareTerminate, void(const sptr &token)); + MOCK_METHOD4(CompelVerifyPermission, int(const std::string &permission, int pid, int uid, std::string &message)); + MOCK_METHOD2(GetRunningProcessInfoByToken, + void(const sptr &token, OHOS::AppExecFwk::RunningProcessInfo &info)); + MOCK_METHOD2(StartSpecifiedAbility, void(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)); + MOCK_METHOD1(RegisterStartSpecifiedAbilityResponse, void(const sptr &response)); + MOCK_METHOD1(UpdateConfiguration, void(const AppExecFwk::Configuration &)); + MOCK_METHOD1(GetConfiguration, int(AppExecFwk::Configuration &)); + + MockAmsMgrScheduler() : AmsMgrStub() {}; + virtual ~MockAmsMgrScheduler(){}; + virtual void RegisterAppStateCallback(const sptr &callback) override + { + callback->OnAbilityRequestDone(nullptr, AbilityState::ABILITY_STATE_BACKGROUND); + AppProcessData appProcessData; + callback->OnAppStateChanged(appProcessData); + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service.h b/services/appmgr/test/mock/include/mock_app_mgr_service.h new file mode 100644 index 0000000000000000000000000000000000000000..7447c7551abc2593434e5ec6bc1af6ae090d515e --- /dev/null +++ b/services/appmgr/test/mock/include/mock_app_mgr_service.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_COMMON_TEST_MOCK_MOCK_APP_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_SERVICES_COMMON_TEST_MOCK_MOCK_APP_MGR_SERVICE_H + +#include "gmock/gmock.h" +#include "semaphore_ex.h" +#include "app_mgr_stub.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppMgrService : public AppMgrStub { +public: + MOCK_METHOD4(LoadAbility, + void(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + MOCK_METHOD1(TerminateAbility, void(const sptr &token)); + MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); + MOCK_METHOD1(AttachApplication, void(const sptr &app)); + MOCK_METHOD1(ApplicationForegrounded, void(const int32_t recordId)); + MOCK_METHOD1(ApplicationBackgrounded, void(const int32_t recordId)); + MOCK_METHOD1(ApplicationTerminated, void(const int32_t recordId)); + MOCK_METHOD2(CheckPermission, int32_t(const int32_t recordId, const std::string &permission)); + MOCK_METHOD1(AbilityCleaned, void(const sptr &token)); + MOCK_METHOD1(KillApplication, int32_t(const std::string &appName)); + MOCK_METHOD2(KillApplicationByUid, int(const std::string &, const int uid)); + MOCK_METHOD1(IsBackgroundRunningRestricted, int(const std::string &bundleName)); + MOCK_METHOD1(GetAllRunningProcesses, int(std::vector &info)); + MOCK_METHOD2(GetProcessRunningInfosByUserId, int(std::vector &info, int32_t userId)); + MOCK_METHOD0(GetAmsMgr, sptr()); + MOCK_METHOD1(GetAppFreezingTime, void(int &time)); + MOCK_METHOD1(SetAppFreezingTime, void(int time)); + MOCK_METHOD1(ClearUpApplicationData, int32_t(const std::string &bundleName)); + MOCK_METHOD2(GetSystemMemoryAttr, void(SystemMemoryAttr &memoryInfo, std::string &strConfig)); + MOCK_METHOD0(StartupResidentProcess, void()); + MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId)); + MOCK_METHOD1(RegisterApplicationStateObserver, int32_t(const sptr &observer)); + MOCK_METHOD1(UnregisterApplicationStateObserver, int32_t(const sptr &observer)); + MOCK_METHOD3(ScheduleAcceptWantDone, + void(const int32_t recordId, const AAFwk::Want &want, const std::string &flag)); + + virtual int StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, + const BundleInfo &bundleInfo) + { + return 0; + } + + virtual void RegisterAppStateCallback(const sptr &callback) + { + callback_ = callback; + } + + int32_t CheckPermissionImpl([[maybe_unused]] const int32_t recordId, const std::string &data) + { + data_ = data; + return 0; + } + + void KillApplicationImpl(const std::string &data) + { + data_ = data; + } + + const std::string &GetData() const + { + return data_; + } + + void Wait() + { + sem_.Wait(); + } + + void Post() + { + sem_.Post(); + } + + void UpdateState() const + { + if (!callback_) { + return; + } + AppProcessData processData; + processData.pid = 1; + processData.appState = ApplicationState::APP_STATE_BEGIN; + callback_->OnAppStateChanged(processData); + } + + void Terminate(const sptr &token) const + { + if (!callback_) { + return; + } + AbilityState st = AbilityState::ABILITY_STATE_BEGIN; + callback_->OnAbilityRequestDone(token, st); + } +private: + Semaphore sem_; + std::string data_; + sptr callback_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_COMMON_TEST_MOCK_MOCK_APP_MGR_SERVICE_H diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h new file mode 100644 index 0000000000000000000000000000000000000000..5b0ceb1b50b0174807e1aebc8929968dcfca069e --- /dev/null +++ b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_MGR_SERVICE_INNER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_MGR_SERVICE_INNER_H + +#include "gmock/gmock.h" +#include "app_log_wrapper.h" +#include "semaphore_ex.h" +#include "app_mgr_service_inner.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppMgrServiceInner : public AppMgrServiceInner { +public: + MockAppMgrServiceInner() : lock_(0) + {} + virtual ~MockAppMgrServiceInner() + {} + + MOCK_METHOD4(LoadAbility, + void(const sptr &token, const sptr &preToken, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + MOCK_METHOD2(AttachApplication, void(const pid_t pid, const sptr &app)); + MOCK_METHOD1(ApplicationForegrounded, void(const int32_t recordId)); + MOCK_METHOD1(ApplicationBackgrounded, void(const int32_t recordId)); + MOCK_METHOD1(ApplicationTerminated, void(const int32_t recordId)); + MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); + MOCK_METHOD1(TerminateAbility, void(const sptr &token)); + MOCK_METHOD1(KillApplication, int32_t(const std::string &bundleName)); + MOCK_METHOD2(KillApplicationByUid, int(const std::string &, const int uid)); + MOCK_METHOD1(AbilityTerminated, void(const sptr &token)); + MOCK_METHOD3(ClearUpApplicationData, void(const std::string &, const int32_t, const pid_t)); + MOCK_METHOD1(IsBackgroundRunningRestricted, int32_t(const std::string &)); + MOCK_METHOD1(GetAllRunningProcesses, int32_t(std::vector &)); + MOCK_METHOD1(RegisterAppStateCallback, void(const sptr &callback)); + MOCK_METHOD0(StopAllProcess, void()); + MOCK_CONST_METHOD0(QueryAppSpawnConnectionState, SpawnConnectionState()); + MOCK_CONST_METHOD2(AddAppDeathRecipient, void(const pid_t pid, const sptr &appDeathRecipient)); + MOCK_METHOD1(KillProcessByAbilityToken, void(const sptr &token)); + MOCK_METHOD1(KillProcessesByUserId, void(int32_t userId)); + MOCK_METHOD5(AbilityBehaviorAnalysis, + void(const sptr &token, const sptr &preToken, const int32_t visibility, + const int32_t perceptibility, const int32_t connectionState)); + MOCK_METHOD2(OptimizerAbilityStateChanged, + void(const std::shared_ptr &ability, const AbilityState state)); + MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId)); + void Post() + { + if (currentCount_ > 1) { + currentCount_--; + } else { + lock_.Post(); + currentCount_ = count_; + } + } + // for mock function return int32_t + int32_t Post4Int() + { + if (currentCount_ > 1) { + currentCount_--; + } else { + lock_.Post(); + currentCount_ = count_; + } + return 0; + } + + void Wait() + { + lock_.Wait(); + } + + void SetWaitCount(const int waitCount) + { + count_ = waitCount; + currentCount_ = waitCount; + } + + int32_t OpenAppSpawnConnection() override + { + return 0; + } + +private: + Semaphore lock_; + int32_t count_ = 1; + int32_t currentCount_ = 1; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_MGR_SERVICE_INNER_H diff --git a/services/appmgr/test/mock/include/mock_app_scheduler.h b/services/appmgr/test/mock/include/mock_app_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..b3e90820909acd251eb12d2d96749d449009fe97 --- /dev/null +++ b/services/appmgr/test/mock/include/mock_app_scheduler.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_AMS_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_AMS_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_H + +#include "gmock/gmock.h" +#include "refbase.h" +#include "iremote_object.h" +#include "app_scheduler_host.h" +#include "app_launch_data.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppScheduler : public AppSchedulerHost { +public: + MockAppScheduler(){}; + virtual ~MockAppScheduler(){}; + MOCK_METHOD0(ScheduleForegroundApplication, void()); + MOCK_METHOD0(ScheduleBackgroundApplication, void()); + MOCK_METHOD0(ScheduleTerminateApplication, void()); + MOCK_METHOD2(ScheduleLaunchApplication, void(const AppLaunchData &, const Configuration &config)); + MOCK_METHOD2(ScheduleLaunchAbility, void(const AbilityInfo &, const sptr &)); + MOCK_METHOD1(ScheduleCleanAbility, void(const sptr &)); + MOCK_METHOD1(ScheduleProfileChanged, void(const Profile &)); + MOCK_METHOD1(ScheduleConfigurationUpdated, void(const Configuration &config)); + MOCK_METHOD1(ScheduleShrinkMemory, void(const int)); + MOCK_METHOD0(ScheduleLowMemory, void()); + MOCK_METHOD0(ScheduleProcessSecurityExit, void()); + MOCK_METHOD1(ScheduleAbilityStage, void(const HapModuleInfo &)); + MOCK_METHOD2(ScheduleAcceptWant, void(const AAFwk::Want &want, const std::string &moduleName)); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_AMS_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_CLIENT_H diff --git a/services/appmgr/test/mock/include/mock_app_service_mgr.h b/services/appmgr/test/mock/include/mock_app_service_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..1f9980fb636d9a76178b6003b2b4429bd6b3bb89 --- /dev/null +++ b/services/appmgr/test/mock/include/mock_app_service_mgr.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_SERVICE_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_SERVICE_MGR_H + +#include "iremote_object.h" +#include "app_log_wrapper.h" +#include "app_service_manager.h" +#include "mock_app_mgr_service.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppServiceMgr : public AppServiceManager { +public: + MockAppServiceMgr() = default; + virtual ~MockAppServiceMgr() = default; + + virtual sptr GetAppMgrService() const override + { + APP_LOGD("Mock MockAppServiceMgr GetAppMgrService called"); + return new MockAppMgrService(); + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_SERVICE_MGR_H \ No newline at end of file diff --git a/services/appmgr/test/mock/include/mock_app_spawn_client.h b/services/appmgr/test/mock/include/mock_app_spawn_client.h new file mode 100644 index 0000000000000000000000000000000000000000..62a5e60e43d5a4b11e393d65996f16fa2a88438d --- /dev/null +++ b/services/appmgr/test/mock/include/mock_app_spawn_client.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_CLIENT_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_CLIENT_H + +#include "gmock/gmock.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppSpawnClient : public AppSpawnClient { +public: + MockAppSpawnClient() + {} + virtual ~MockAppSpawnClient() + {} + MOCK_METHOD2(StartProcess, ErrCode(const AppSpawnStartMsg &startMsg, pid_t &pid)); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_CLIENT_H diff --git a/services/appmgr/test/mock/include/mock_app_spawn_socket.h b/services/appmgr/test/mock/include/mock_app_spawn_socket.h new file mode 100644 index 0000000000000000000000000000000000000000..4a14ec5ee108c0857ada0934989c1e03131a748a --- /dev/null +++ b/services/appmgr/test/mock/include/mock_app_spawn_socket.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_SOCKET_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_SOCKET_H + +#include "gmock/gmock.h" +#include "app_spawn_socket.h" +#include "app_spawn_msg_wrapper.h" +#include "securec.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppSpawnSocket : public AppSpawnSocket { +public: + MockAppSpawnSocket() = default; + virtual ~MockAppSpawnSocket() = default; + + MOCK_METHOD0(OpenAppSpawnConnection, ErrCode()); + MOCK_METHOD0(CloseAppSpawnConnection, void()); + MOCK_METHOD2(WriteMessage, ErrCode(const void *buf, const int32_t len)); + MOCK_METHOD2(ReadMessage, ErrCode(void *buf, int32_t len)); + ErrCode ReadImpl(void *buf, [[maybe_unused]] int32_t len) + { + if (buf == nullptr) { + return ERR_NO_MEMORY; + } + AppSpawnPidMsg msg; + msg.pid = expectPid_; + if (memcpy_s(buf, sizeof(msg), msg.pidBuf, sizeof(msg)) != 0) { + return ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED; + } + return ERR_OK; + } + + void SetExpectPid(int32_t expectPid) + { + expectPid_ = expectPid; + } + +private: + int32_t expectPid_ = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_SOCKET_H diff --git a/services/appmgr/test/mock/include/mock_application.h b/services/appmgr/test/mock/include/mock_application.h new file mode 100644 index 0000000000000000000000000000000000000000..eae33a3870ac6f31f3d764340d1019b132a680d9 --- /dev/null +++ b/services/appmgr/test/mock/include/mock_application.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APPLICATION_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APPLICATION_H + +#include "gmock/gmock.h" +#include "semaphore_ex.h" +#include "app_scheduler_host.h" + +namespace OHOS { +namespace AppExecFwk { +class MockApplication : public AppSchedulerHost { +public: + MOCK_METHOD0(ScheduleForegroundApplication, void()); + MOCK_METHOD0(ScheduleBackgroundApplication, void()); + MOCK_METHOD0(ScheduleTerminateApplication, void()); + MOCK_METHOD1(ScheduleShrinkMemory, void(const int)); + MOCK_METHOD0(ScheduleLowMemory, void()); + MOCK_METHOD2(ScheduleLaunchApplication, void(const AppLaunchData &, const Configuration &config)); + MOCK_METHOD2(ScheduleLaunchAbility, void(const AbilityInfo &, const sptr &)); + MOCK_METHOD1(ScheduleCleanAbility, void(const sptr &)); + MOCK_METHOD1(ScheduleProfileChanged, void(const Profile &)); + MOCK_METHOD1(ScheduleConfigurationUpdated, void(const Configuration &)); + MOCK_METHOD0(ScheduleProcessSecurityExit, void()); + MOCK_METHOD1(ScheduleAbilityStage, void(const HapModuleInfo &)); + MOCK_METHOD2(ScheduleAcceptWant, void(const AAFwk::Want &want, const std::string &moduleName)); + + void Post() + { + lock_.Post(); + } + + void Wait() + { + lock_.Wait(); + } + + void ShrinkMemory(const int level) + { + shrinkLevel_ = level; + lock_.Post(); + } + + int GetShrinkLevel() const + { + return shrinkLevel_; + } + + void LaunchApplication(const AppLaunchData &launchData, const Configuration &config) + { + launchData_ = launchData; + lock_.Post(); + } + + bool CompareAppLaunchData(const AppLaunchData &launchData) const + { + if (launchData_.GetApplicationInfo().name != launchData.GetApplicationInfo().name) { + return false; + } + if (launchData_.GetProfile().GetName() != launchData.GetProfile().GetName()) { + return false; + } + if (launchData_.GetProcessInfo().GetProcessName() != launchData.GetProcessInfo().GetProcessName()) { + return false; + } + return true; + } + + void LaunchAbility(const AbilityInfo &info, const sptr &) + { + abilityInfo_ = info; + lock_.Post(); + } + + bool CompareAbilityInfo(const AbilityInfo &info) const + { + return (info.name == abilityInfo_.name); + } + + void ProfileChanged(const Profile &profile) + { + profile_ = profile; + lock_.Post(); + } + + bool CompareProfile(const Profile &profile) const + { + return (profile.GetName() == profile_.GetName()); + } + +private: + Semaphore lock_; + volatile int shrinkLevel_ = 0; + AppLaunchData launchData_; + AbilityInfo abilityInfo_; + Profile profile_; + // Configuration configuration_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APPLICATION_H diff --git a/services/appmgr/test/mock/include/mock_bundle_manager.h b/services/appmgr/test/mock/include/mock_bundle_manager.h new file mode 100755 index 0000000000000000000000000000000000000000..8a12f9ad9ab41ae72f8d92f04902220038b4af49 --- /dev/null +++ b/services/appmgr/test/mock/include/mock_bundle_manager.h @@ -0,0 +1,470 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H +#define OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H + +#include +#include "gmock/gmock.h" +#include "ability_info.h" +#include "application_info.h" +#include "ohos/aafwk/content/want.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "bundle_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string COM_OHOS_HELLO = "com.ohos.test.helloworld"; +const int32_t APPLICATION_NUMHELLO = 104; +const std::string COM_OHOS_SPECIAL = "com.ohos.test.special"; +} // namespace +class BundleMgrProxy : public IRemoteProxy { +public: + explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + virtual ~BundleMgrProxy() + {} + MOCK_METHOD3( + CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + bool(const std::string &bundleName, const std::string &permission, const int userId)); + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); + MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(QueryAbilityInfosByUri, bool(const std::string &abilityUri, std::vector &abilityInfos)); + MOCK_METHOD2(RemoveClonedBundle, bool(const std::string &bundleName, const int32_t uid)); + MOCK_METHOD1(BundleClone, bool(const std::string &bundleName)); + MOCK_METHOD3(GetBundleGidsByUid, bool(const std::string &bundleName, const int &uid, std::vector &gids)); + MOCK_METHOD1(CheckBundleNameInAllowList, bool(const std::string &bundleName)); + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; + std::string GetAppType(const std::string &bundleName) override; + + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + }; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool QueryAbilityInfosForClone(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override + { + return true; + }; + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override + { + return true; + }; + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override + { + return 0; + }; + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override + { + return ""; + }; + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + return true; + }; + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override + { + return true; + }; + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + }; + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + int appUid = 2100; + GTEST_LOG_(INFO) << "QueryKeepAliveBundleInfos()"; + ApplicationInfo info; + info.name = "KeepAliveApp"; + info.bundleName = "KeepAliveApplication"; + info.uid = appUid; + + BundleInfo bundleInfo; + bundleInfo.applicationInfo = info; + HapModuleInfo hapModuleInfo; + hapModuleInfo.name = "Module"; + HapModuleInfo hapModuleInfo1; + hapModuleInfo1.name = "Module1"; + bundleInfo.hapModuleInfos.push_back(hapModuleInfo); + bundleInfo.hapModuleInfos.push_back(hapModuleInfo1); + + bundleInfos.push_back(bundleInfo); + GTEST_LOG_(INFO) << "bundleInfos size : "< &permissionDefs) override + { + return true; + }; + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + }; + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + }; + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + }; + virtual bool IsSafeMode() override + { + return true; + }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override + { + return true; + }; + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + }; + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override + { + return true; + }; + virtual sptr GetBundleInstaller() override + { + return nullptr; + }; + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyAbilityLifeStatus(const std::string &bundleName, + const std::string &abilityName, const int64_t launchTime, const int uid = 0) override + { + return true; + } + + virtual int CheckPermissionByUid( + const std::string &bundleName, const std::string &permission, const int userId) override + { + return 0; + } + virtual bool GetDistributedBundleInfo( + const std::string &networkId, int32_t userId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) + { + return true; + } +}; + +class BundleMgrStub : public IRemoteStub { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +}; + +class BundleMgrService : public BundleMgrStub { +public: + MOCK_METHOD2(GetUidByBundleName, int(const std::string &bundleName, const int userId)); + MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); + MOCK_METHOD2(CheckPermission, int(const std::string &bundleName, const std::string &permission)); + MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); + MOCK_METHOD3(CanRequestPermission, + bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + bool(const std::string &bundleName, const std::string &permission, const int userId)); + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); + MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(QueryAbilityInfosByUri, bool(const std::string &abilityUri, std::vector &abilityInfos)); + MOCK_METHOD2(RemoveClonedBundle, bool(const std::string &bundleName, const int32_t uid)); + MOCK_METHOD1(BundleClone, bool(const std::string &bundleName)); + MOCK_METHOD1(CheckBundleNameInAllowList, bool(const std::string &bundleName)); + MOCK_METHOD3(CheckPermissionByUid, + int(const std::string &bundleName, const std::string &permission, const int userId)); + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; + + std::string GetAppType(const std::string &bundleName) override; + + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + }; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool QueryAbilityInfosForClone(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override; + bool GetBundleGidsByUid( + const std::string &bundleName, const int &uid, std::vector &gids) override; + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + return true; + }; + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override; + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + }; + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + }; + // obtains information about an application bundle contained in a ohos Ability Package (HAP). + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + }; + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo); + // obtains the Want for starting the main ability of an application based on the given bundle name. + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + }; + // checks whether the publickeys of two bundles are the same. + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + }; + // checks whether a specified bundle has been granted a specific permission. + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + }; + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + }; + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + }; + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + }; + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + }; + virtual bool IsSafeMode() override + { + return true; + }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; + + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + }; + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override + { + return true; + }; + virtual sptr GetBundleInstaller() override + { + return nullptr; + }; + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } + virtual bool IsApplicationEnabled(const std::string &bundleName) override + { + return true; + }; + virtual bool CheckIsSystemAppByUid(const int uid) override + { + return true; + }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + }; + virtual bool GetAllFormsInfo(std::vector &formInfos) override + { + return true; + } + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfos) override + { + return true; + } + virtual bool GetFormsInfoByModule( + const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) override + { + return true; + } + virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) override + { + return true; + } + virtual bool GetAllCommonEventInfo(const std::string &eventKey, + std::vector &commonEventInfos) override + { + return true; + } + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyAbilityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) override + { + return true; + } + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + int appUid = 2100; + GTEST_LOG_(INFO) << "QueryKeepAliveBundleInfos()"; + ApplicationInfo info; + info.name = "KeepAliveApp"; + info.bundleName = "KeepAliveApplication"; + info.uid = appUid; + + BundleInfo bundleInfo; + bundleInfo.applicationInfo = info; + HapModuleInfo hapModuleInfo; + hapModuleInfo.name = "Module"; + HapModuleInfo hapModuleInfo1; + hapModuleInfo1.name = "Module1"; + bundleInfo.hapModuleInfos.push_back(hapModuleInfo); + bundleInfo.hapModuleInfos.push_back(hapModuleInfo1); + + bundleInfos.push_back(bundleInfo); + GTEST_LOG_(INFO) << "bundleInfos size : "< bundleInfos_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H diff --git a/services/appmgr/test/mock/include/mock_iapp_state_callback.h b/services/appmgr/test/mock/include/mock_iapp_state_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..b566e76d64e5f9e9cee7d6a67d91616c7734ab19 --- /dev/null +++ b/services/appmgr/test/mock/include/mock_iapp_state_callback.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_COMMON_TEST_MOCK_IAPP_STATE_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_COMMON_TEST_MOCK_IAPP_STATE_CALLBACK_H + +#include "gmock/gmock.h" +#include "app_mgr_constants.h" +#include "app_state_callback_host.h" +#include "app_process_data.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppStateCallback : public AppStateCallbackHost { +public: + MockAppStateCallback() + {} + virtual ~MockAppStateCallback() + {} + + MOCK_METHOD1(OnAppStateChanged, void(const AppProcessData &)); + MOCK_METHOD2(OnAbilityRequestDone, void(const sptr &, const AbilityState)); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_COMMON_TEST_MOCK_IAPP_STATE_CALLBACK_H \ No newline at end of file diff --git a/services/appmgr/test/mock/include/sys_mgr_client.h b/services/appmgr/test/mock/include/sys_mgr_client.h new file mode 100644 index 0000000000000000000000000000000000000000..28825f943636011555bb4137d8703bc64703db86 --- /dev/null +++ b/services/appmgr/test/mock/include/sys_mgr_client.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OS_AAFWK_SYS_MRG_CLIENT_H +#define OHOS_OS_AAFWK_SYS_MRG_CLIENT_H + +#include +#include +#include +#include +#include "if_system_ability_manager.h" +#include "iremote_object.h" +#include "singleton.h" + +namespace OHOS { +namespace AppExecFwk { +class SysMrgClient { + DECLARE_DELAYED_SINGLETON(SysMrgClient) +public: + /** + * + * Get the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility which want to get. + */ + sptr GetSystemAbility(const int32_t systemAbilityId); + + /** + * + * Register the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility which want to register. + * @param broker The systemAbility which want to be registered. + */ + void RegisterSystemAbility(const int32_t systemAbilityId, sptr broker); + + /** + * + * Unregister the systemAbility by ID. + * + * @param systemAbilityId The ID of systemAbility which want to unregister. + */ + void UnregisterSystemAbility(const int32_t systemAbilityId); + +private: + OHOS::sptr sm_; + std::mutex saMutex_; + std::unordered_map> servicesMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_OS_AAFWK_SYS_MRG_CLIENT_H diff --git a/services/appmgr/test/mock/include/system_ability.h b/services/appmgr/test/mock/include/system_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..2973db76b797bc183c745266ace92d001247276f --- /dev/null +++ b/services/appmgr/test/mock/include/system_ability.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_SYSTEM_ABILITY_H +#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_SYSTEM_ABILITY_H + +#include "hilog/log.h" +#include "iremote_object.h" + +namespace OHOS { +#define REGISTER_SYSTEM_ABILITY_BY_ID(a, b, c) +#define REGISTER_SYSTEM_ABILITY(abilityClassName, abilityId, runOnCreate) +#define DECLEAR_SYSTEM_ABILITY(className) +static constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0xD001100, "MockSystemAbility"}; + +class SystemAbility { +protected: + virtual void OnStart() + { + HiviewDFX::HiLog::Debug(LABEL, "Mock SystemAbility OnStart called"); + } + + virtual void OnStop() + { + HiviewDFX::HiLog::Debug(LABEL, "Mock SystemAbility OnStop called"); + } + + bool Publish(sptr systemAbility) + { + HiviewDFX::HiLog::Debug(LABEL, "Mock SystemAbility Publish called"); + systemAbility.ForceSetRefPtr(nullptr); + // For test just mock to return true + return true; + } + + SystemAbility(bool runOnCreate = false) + { + HiviewDFX::HiLog::Debug(LABEL, "Mock SystemAbility default Creator called %d", runOnCreate); + } + + SystemAbility(const int32_t serviceId, bool runOnCreate = false) + { + HiviewDFX::HiLog::Debug(LABEL, "Mock SystemAbility Creator called %d", runOnCreate); + } + + virtual ~SystemAbility() + { + HiviewDFX::HiLog::Debug(LABEL, "Mock SystemAbility Destructor called"); + } +}; +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_SYSTEM_ABILITY_H diff --git a/services/appmgr/test/mock/src/cgroup_manager.cpp b/services/appmgr/test/mock/src/cgroup_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c6659f6db420deb9601a48687298a8f05f2340f --- /dev/null +++ b/services/appmgr/test/mock/src/cgroup_manager.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "cgroup_manager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "app_log_wrapper.h" +#include "event_handler.h" +#include "securec.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +class ScopeGuard final { +public: + using Function = std::function; + +public: + explicit ScopeGuard(Function fn) : fn_(fn), dismissed_(false) + {} + + ~ScopeGuard() + { + if (!dismissed_) { + fn_(); + } + } + +public: + void Dismiss() + { + dismissed_ = true; + } + +private: + Function fn_; + bool dismissed_ = false; +}; +} // namespace + +CgroupManager::CgroupManager() : memoryEventControlFd_(-1) +{} + +CgroupManager::~CgroupManager() +{} + +bool CgroupManager::Init() +{ + APP_LOGD("Init start."); + return true; +} + +bool CgroupManager::IsInited() const +{ + APP_LOGD("IsInited start."); + return true; +} + +bool CgroupManager::SetThreadSchedPolicy(int tid, SchedPolicy schedPolicy) +{ + APP_LOGD("SetThreadSchedPolicy start."); + return true; +} + +bool CgroupManager::SetProcessSchedPolicy(int pid, SchedPolicy schedPolicy) +{ + APP_LOGD("SetProcessSchedPolicy start."); + return true; +} + +void CgroupManager::OnReadable(int32_t fd) +{ + APP_LOGD("OnReadable start."); + return; +} + +bool CgroupManager::RegisterLowMemoryMonitor(const int memoryEventFds[LOW_MEMORY_LEVEL_MAX], + const int memoryPressureFds[LOW_MEMORY_LEVEL_MAX], const int memoryEventControlFd, const LowMemoryLevel level, + const std::shared_ptr &eventHandler) +{ + APP_LOGD("RegisterLowMemoryMonitor start."); + return true; +} + +bool CgroupManager::InitCpusetTasksFds(UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_MAX]) +{ + APP_LOGD("InitCpusetTasksFds start."); + return true; +} + +bool CgroupManager::InitCpuctlTasksFds(UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_MAX]) +{ + APP_LOGD("InitCpuctlTasksFds start."); + return true; +} + +bool CgroupManager::InitFreezerTasksFds(UniqueFd freezerTasksFds[SCHED_POLICY_FREEZER_MAX]) +{ + APP_LOGD("InitFreezerTasksFds start."); + return true; +} + +bool CgroupManager::InitMemoryEventControlFd(UniqueFd &memoryEventControlFd) +{ + APP_LOGD("InitMemoryEventControlFd start."); + return true; +} + +bool CgroupManager::InitMemoryEventFds(UniqueFd memoryEventFds[LOW_MEMORY_LEVEL_MAX]) +{ + APP_LOGD("InitMemoryEventFds start."); + return true; +} + +bool CgroupManager::InitMemoryPressureFds(UniqueFd memoryPressureFds[LOW_MEMORY_LEVEL_MAX]) +{ + APP_LOGD("InitMemoryPressureFds start."); + return true; +} + +bool CgroupManager::SetCpusetSubsystem(const int tid, const SchedPolicy schedPolicy) +{ + APP_LOGD("SetCpusetSubsystem start."); + return true; +} + +bool CgroupManager::SetCpuctlSubsystem(const int tid, const SchedPolicy schedPolicy) +{ + APP_LOGD("SetCpuctlSubsystem start."); + return true; +} + +bool CgroupManager::SetFreezerSubsystem(const int tid, const SchedPolicyFreezer state) +{ + APP_LOGD("SetFreezerSubsystem start."); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/mock/src/mock_bundle_manager.cpp b/services/appmgr/test/mock/src/mock_bundle_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..562ad2b5c03a7068f6f2e11662a4e38e7b508365 --- /dev/null +++ b/services/appmgr/test/mock/src/mock_bundle_manager.cpp @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "mock_bundle_manager.h" + +#include "ability_info.h" +#include "application_info.h" + +namespace OHOS { +namespace AppExecFwk { +bool BundleMgrProxy::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) +{ + ElementName eleName = want.GetElement(); + if (eleName.GetBundleName().empty()) { + return false; + } + abilityInfo.visible = true; + abilityInfo.name = eleName.GetAbilityName(); + abilityInfo.bundleName = eleName.GetBundleName(); + abilityInfo.applicationName = "Helloworld"; + return true; +} + +bool BundleMgrProxy::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) +{ + return false; +} + +bool BundleMgrProxy::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + if (appName.empty()) { + return false; + } + appInfo.name = "Helloworld"; + appInfo.bundleName = "com.ohos.hiworld"; + return true; +} + +std::string BundleMgrProxy::GetAppType(const std::string &bundleName) +{ + GTEST_LOG_(INFO) << " BundleMgrProxy::GetAppTyp"; + return "system"; +} + +int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + return 0; +} + +BundleMgrService::BundleMgrService() +{ + MakingPackageData(); +} + +bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) +{ + ElementName elementName = want.GetElement(); + if (elementName.GetBundleName().empty()) { + return false; + } + if (std::string::npos != elementName.GetBundleName().find("service")) { + abilityInfo.type = AppExecFwk::AbilityType::SERVICE; + } + abilityInfo.visible = true; + abilityInfo.name = elementName.GetAbilityName(); + abilityInfo.bundleName = elementName.GetBundleName(); + abilityInfo.applicationName = elementName.GetBundleName(); + if (want.HasEntity(Want::ENTITY_HOME) && want.GetAction() == Want::ACTION_HOME) { + abilityInfo.applicationInfo.isLauncherApp = true; + } else { + abilityInfo.applicationInfo.isLauncherApp = false; + } + return true; +} + +bool BundleMgrService::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) +{ + return false; +} + +bool BundleMgrService::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + if (appName.empty()) { + return false; + } + appInfo.name = "Helloworld"; + appInfo.bundleName = "com.ohos.hiworld"; + return true; +} + +std::string BundleMgrService::GetAppType(const std::string &bundleName) +{ + GTEST_LOG_(INFO) << " BundleMgrService::GetAppType"; + return "system"; +} + +bool BundleMgrService::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) +{ + GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo"; + hapModuleInfo.name = "Captain"; + return true; +} + +bool BundleMgrProxy::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) +{ + GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo"; + hapModuleInfo.name = "Captain"; + return true; +} + +bool BundleMgrService::GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) +{ + int32_t userUid = 10001; + int32_t userGid = 10001; + bundleInfo.uid = userUid; + bundleInfo.gid = userGid; + int index1 = 101; + int index2 = 102; + int index3 = 103; + int index4 = 104; + if (bundleName == COM_OHOS_HELLO + std::to_string(index1) || + bundleName == COM_OHOS_HELLO + std::to_string(index2)) { + bundleInfo.jointUserId = "join"; + bundleInfo.appId = bundleName + "_xxx"; + } + if (bundleName == COM_OHOS_HELLO + std::to_string(index3) || + bundleName == COM_OHOS_HELLO + std::to_string(index4)) { + bundleInfo.jointUserId = ""; + bundleInfo.appId = bundleName + "_xxx"; + } + return true; +} +bool BundleMgrService::GetBundleGids(const std::string &bundleName, std::vector &gids) +{ + int32_t userGid1 = 10001; + int32_t userGid2 = 10002; + int32_t userGid3 = 10003; + gids.push_back(userGid1); + gids.push_back(userGid2); + gids.push_back(userGid3); + return true; +} + +bool BundleMgrService::GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) +{ + bundleInfos = bundleInfos_; + return true; +} + +bool BundleMgrService::GetBundleGidsByUid( + const std::string &bundleName, const int &uid, std::vector &gids) +{ + return true; +} + +void BundleMgrService::PushTestHelloIndexAbility(int index) +{ + AbilityInfo info; + info.name = "com.ohos.test.helloworld.MainAbility"; + info.bundleName = COM_OHOS_HELLO + std::to_string(index); + info.applicationInfo.bundleName = COM_OHOS_HELLO + std::to_string(index); + info.applicationName = "helloworld"; + info.applicationInfo.name = "helloworld"; + info.process = "p1"; + info.applicationInfo.uid = -1; + info.deviceId = "deviceId"; + info.visible = true; + + BundleInfo bundleInfo; + bundleInfo.name = COM_OHOS_HELLO + std::to_string(index); + bundleInfo.uid = info.applicationInfo.uid; + bundleInfo.abilityInfos.emplace_back(info); + bundleInfo.applicationInfo = info.applicationInfo; + bundleInfos_.emplace_back(bundleInfo); +} + +void BundleMgrService::PushTestSpecialAbility() +{ + AbilityInfo info; + info.name = "com.ohos.test.helloworld.MainAbility"; + info.bundleName = COM_OHOS_SPECIAL; + info.applicationInfo.bundleName = COM_OHOS_SPECIAL; + info.applicationName = "helloworld"; + info.applicationInfo.name = "helloworld"; + info.process = "p1"; + info.applicationInfo.uid = -1; + info.deviceId = "deviceId"; + info.visible = true; + + BundleInfo bundleInfo; + bundleInfo.name = COM_OHOS_SPECIAL; + bundleInfo.uid = info.applicationInfo.uid; + bundleInfo.abilityInfos.emplace_back(info); + bundleInfo.applicationInfo = info.applicationInfo; + bundleInfos_.emplace_back(bundleInfo); +} + +void BundleMgrService::PushTestHelloAbility() +{ + AbilityInfo info; + info.name = "com.ohos.test.helloworld.MainAbility"; + info.bundleName = COM_OHOS_HELLO; + info.applicationInfo.bundleName = COM_OHOS_HELLO; + info.applicationName = "helloworld"; + info.applicationInfo.name = "helloworld"; + info.process = "p1"; + info.applicationInfo.uid = -1; + info.deviceId = "deviceId"; + info.visible = true; + + BundleInfo bundleInfo; + bundleInfo.name = COM_OHOS_HELLO; + bundleInfo.uid = info.applicationInfo.uid; + bundleInfo.abilityInfos.emplace_back(info); + bundleInfo.applicationInfo = info.applicationInfo; + bundleInfos_.emplace_back(bundleInfo); +} + +void BundleMgrService::MakingPackageData() +{ + PushTestSpecialAbility(); + PushTestHelloAbility(); + MakingResidentProcData(); + for (int i = 0; i<= APPLICATION_NUMHELLO; i++) { + PushTestHelloIndexAbility(i); + } +} + +void BundleMgrService::MakingResidentProcData() +{ + int appUid = 2100; + GTEST_LOG_(INFO) << "MakingResidentProcData()"; + BundleInfo bundleInfo; + bundleInfo.uid = appUid; + bundleInfo.name = "KeepAliveApplication"; + + bundleInfos_.emplace_back(bundleInfo); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp b/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9fb2e2d837c1ad52322581df68c8d645e5df331 --- /dev/null +++ b/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "sys_mgr_client.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +sptr SysMrgClient::GetSystemAbility(const int32_t systemAbilityId) +{ + if (servicesMap_[systemAbilityId] == nullptr) { + OHOS::sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + HILOG_ERROR("%s:fail to get Registry", __func__); + return nullptr; + } + OHOS::sptr object = systemAbilityManager->GetSystemAbility(systemAbilityId); + servicesMap_[systemAbilityId] = object; + } + return servicesMap_[systemAbilityId]; +} + +void SysMrgClient::RegisterSystemAbility(const int32_t systemAbilityId, sptr broker) +{ + servicesMap_[systemAbilityId] = broker; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn b/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..75e91bb61b607923d1d5cbe9c76f1a51edfe197c --- /dev/null +++ b/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsAbilityRunningRecordTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/inclide", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + ] + + sources += [ "ams_ability_running_record_test.cpp" ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/services/appmgr:libams", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsAbilityRunningRecordTest" ] +} diff --git a/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp b/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..632838ca199e3e02d8fbb734a60f11afe05ff666 --- /dev/null +++ b/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp @@ -0,0 +1,680 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_service_inner.h" +#include "ability_running_record.h" +#include +#include "app_running_record.h" +#include "app_scheduler_host.h" +#include "app_log_wrapper.h" +#include "mock_ability_token.h" +#include "mock_application.h" + +using namespace testing::ext; +using testing::_; +namespace OHOS { +namespace AppExecFwk { +class AmsAbilityRunningRecordTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + static const std::string GetTestAppName() + { + return "test_app_name"; + } + static const std::string GetTestAbilityName() + { + return "test_ability_name"; + } + static const std::string GetAnotherTestAbilityName() + { + return "another_test_ability_name"; + } + static const std::string GetProcessName() + { + return "AmsAbilityRunningRecordTest"; + } + + std::shared_ptr GetTestAppRunningRecord(); + sptr GetMockedAppSchedulerClient(); + +protected: + sptr client_; + sptr mockedAppClient_; + std::shared_ptr testAppRecord_; + std::shared_ptr serviceInner_ = nullptr; + std::shared_ptr handler_ = nullptr; +}; + +void AmsAbilityRunningRecordTest::SetUpTestCase() +{} + +void AmsAbilityRunningRecordTest::TearDownTestCase() +{} + +void AmsAbilityRunningRecordTest::SetUp() +{ + mockedAppClient_ = new MockApplication(); + auto runner = EventRunner::Create("AmsAppLifeCycleModuleTest"); + serviceInner_ = std::make_shared(); + handler_ = std::make_shared(runner, serviceInner_); +} + +void AmsAbilityRunningRecordTest::TearDown() +{ + testAppRecord_.reset(); +} + +sptr AmsAbilityRunningRecordTest::GetMockedAppSchedulerClient() +{ + if (!client_) { + client_ = iface_cast(mockedAppClient_.GetRefPtr()); + } + return client_; +} + +std::shared_ptr AmsAbilityRunningRecordTest::GetTestAppRunningRecord() +{ + if (!testAppRecord_) { + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + testAppRecord_ = std::make_shared(appInfo, AppRecordId::Create(), GetProcessName()); + testAppRecord_->SetApplicationClient(GetMockedAppSchedulerClient()); + testAppRecord_->SetEventHandler(handler_); + } + return testAppRecord_; +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Create AbilityRunningRecord using correct args. + * EnvConditions: NA + * CaseDescription: Verify the function AddAbility can create AbilityRunningRecord add add to AppRunningRecord. + */ +HWTEST_F(AmsAbilityRunningRecordTest, CreateAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGD("CreateAbilityRunningRecord_001 start."); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appRunningRecord = GetTestAppRunningRecord(); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_EQ(abilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + APP_LOGD("CreateAbilityRunningRecord_001 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Create AbilityRunningRecord using null args. + * EnvConditions: NA + * CaseDescription: Verify the function AddAbility works but does not take effect using nullptr parameter. + */ +HWTEST_F(AmsAbilityRunningRecordTest, CreateAbilityRunningRecord_002, TestSize.Level1) +{ + APP_LOGD("CreateAbilityRunningRecord_002 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, nullptr, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRunningRecord == nullptr); + APP_LOGD("CreateAbilityRunningRecord_002 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Create AbilityRunningRecord that already exists. + * EnvConditions: NA + * CaseDescription: Verify the function AddAbility does not take effect when abilityRunningRecord already exists. + */ +HWTEST_F(AmsAbilityRunningRecordTest, CreateAbilityRunningRecord_003, TestSize.Level1) +{ + APP_LOGD("CreateAbilityRunningRecord_003 start."); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appRunningRecord = GetTestAppRunningRecord(); + sptr token = new MockAbilityToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecordFirst = moduleRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRunningRecordFirst != nullptr); + EXPECT_EQ(abilityRunningRecordFirst, appRunningRecord->GetAbilityRunningRecordByToken(token)); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecordSecond = moduleRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRunningRecordSecond == abilityRunningRecordFirst); + APP_LOGD("CreateAbilityRunningRecord_003 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update the state of AbilityRunningRecord using correct args. + * EnvConditions: NA + * CaseDescription: Verify the function UpdateAbilityState can update the state of AbilityRunningRecord correctly. + */ +HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGD("UpdateAbilityRunningRecord_001 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_TRUE(abilityRunningRecord != nullptr); + abilityRunningRecord->SetState(AbilityState::ABILITY_STATE_READY); + appRunningRecord->SetState(ApplicationState::APP_STATE_READY); + + EXPECT_CALL(*mockedAppClient_, ScheduleForegroundApplication()).Times(1); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_FOREGROUND); + appRunningRecord->PopForegroundingAbilityTokens(); + EXPECT_EQ(abilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_FOREGROUND) << "execute fail!"; + + appRunningRecord->SetState(ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*mockedAppClient_, ScheduleBackgroundApplication()).Times(1); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(abilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_BACKGROUND) << "execute fail!"; + APP_LOGD("UpdateAbilityRunningRecord_001 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update the state of AbilityRunningRecord using incorrect args. + * EnvConditions: NA + * CaseDescription: Verify the function UpdateAbilityState works but does not take effect using incorrect value. + */ +HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_002, TestSize.Level1) +{ + APP_LOGD("UpdateAbilityRunningRecord_002 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + sptr token = new MockAbilityToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRunningRecord != nullptr); + + AbilityState state = abilityRunningRecord->GetState(); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_END); + EXPECT_EQ(abilityRunningRecord->GetState(), state); + EXPECT_NE(abilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_END); + APP_LOGD("UpdateAbilityRunningRecord_002 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update the state of AbilityRunningRecord using nullptr. + * EnvConditions: NA + * CaseDescription: Verify the function UpdateAbilityState works but does not take effect using nullptr parameter. + */ +HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_003, TestSize.Level1) +{ + APP_LOGD("UpdateAbilityRunningRecord_003 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRunningRecord != nullptr); + + AbilityState state = abilityRunningRecord->GetState(); + + appRunningRecord->UpdateAbilityState(nullptr, AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(abilityRunningRecord->GetState(), state); + APP_LOGD("UpdateAbilityRunningRecord_003 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update the state of AbilityRunningRecord that does not exist. + * EnvConditions: NA + * CaseDescription: Verify the function UpdateAbilityState cannot change the state of AbilityRunningRecord + * that does not exist. + */ +HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_004, TestSize.Level1) +{ + APP_LOGD("UpdateAbilityRunningRecord_004 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + sptr token = new MockAbilityToken(); + + auto anotherAbilityInfo = std::make_shared(); + anotherAbilityInfo->name = GetAnotherTestAbilityName(); + sptr token2 = new MockAbilityToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRunningRecord != nullptr); + + AbilityState state = abilityRunningRecord->GetState(); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token2) == nullptr); + appRunningRecord->UpdateAbilityState(token2, AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(abilityRunningRecord->GetState(), state); + APP_LOGD("UpdateAbilityRunningRecord_004 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update one state of AbilityRunningRecords as foreground. + * EnvConditions: NA + * CaseDescription: Verify if there is at least one state of AbilityRunningRecords is foreground, + * the state of application should be changed to foreground. + */ +HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_005, TestSize.Level1) +{ + APP_LOGD("UpdateAbilityRunningRecord_005 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto anotherAbilityInfo = std::make_shared(); + anotherAbilityInfo->name = GetAnotherTestAbilityName(); + sptr token = new MockAbilityToken(); + sptr anotherToken = new MockAbilityToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); + + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(anotherAbilityRunningRecord != nullptr); + anotherAbilityRunningRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); + appRunningRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*mockedAppClient_, ScheduleForegroundApplication()).Times(1); + appRunningRecord->UpdateAbilityState(anotherToken, AbilityState::ABILITY_STATE_FOREGROUND); + APP_LOGD("UpdateAbilityRunningRecord_005 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update all states of AbilityRunningRecords as background. + * EnvConditions: NA + * CaseDescription: Verify if all states of AbilityRunningRecords are background, the state of application should be + * changed to background. + */ +HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_006, TestSize.Level1) +{ + APP_LOGD("UpdateAbilityRunningRecord_006 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto anotherAbilityInfo = std::make_shared(); + anotherAbilityInfo->name = GetAnotherTestAbilityName(); + sptr token = new MockAbilityToken(); + sptr anotherToken = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(anotherAbilityRunningRecord != nullptr); + anotherAbilityRunningRecord->SetState(AbilityState::ABILITY_STATE_FOREGROUND); + appRunningRecord->SetState(ApplicationState::APP_STATE_FOREGROUND); + abilityRunningRecord->SetState(AbilityState::ABILITY_STATE_FOREGROUND); + + EXPECT_CALL(*mockedAppClient_, ScheduleBackgroundApplication()).Times(1); + appRunningRecord->UpdateAbilityState(anotherToken, AbilityState::ABILITY_STATE_FOREGROUND); + + auto abilities = appRunningRecord->GetAbilities(); + for (auto iter = abilities.begin(); iter != abilities.end(); iter++) { + appRunningRecord->UpdateAbilityState(iter->second->GetToken(), AbilityState::ABILITY_STATE_BACKGROUND); + } + APP_LOGD("UpdateAbilityRunningRecord_006 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update all states of AbilityRunningRecords as terminate. + * EnvConditions: NA + * CaseDescription: Verify if all states of AbilityRunningRecords are terminate, the state of application should be + * changed to terminate. + */ +HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_007, TestSize.Level1) +{ + APP_LOGD("UpdateAbilityRunningRecord_007 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto anotherAbilityInfo = std::make_shared(); + anotherAbilityInfo->name = GetAnotherTestAbilityName(); + sptr token = new MockAbilityToken(); + sptr anotherToken = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(anotherAbilityRunningRecord != nullptr); + anotherAbilityRunningRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); + appRunningRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + abilityRunningRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); + + EXPECT_CALL(*mockedAppClient_, ScheduleTerminateApplication()).Times(1); + EXPECT_CALL(*mockedAppClient_, ScheduleCleanAbility(_)).Times(2); + auto abilities = appRunningRecord->GetAbilities(); + for (auto iter = abilities.begin(); iter != abilities.end(); iter++) { + appRunningRecord->TerminateAbility(iter->second->GetToken(), false); + appRunningRecord->AbilityTerminated(iter->second->GetToken()); + } + APP_LOGD("UpdateAbilityRunningRecord_007 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Delete AbilityRunningRecord using correct args. + * EnvConditions: NA + * CaseDescription: Verify the function ClearAbility can delete AbilityRunningRecord. + */ +HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGD("DeleteAbilityRunningRecord_001 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + + appRunningRecord->ClearAbility(abilityRunningRecord); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) == nullptr); + APP_LOGD("DeleteAbilityRunningRecord_001 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Delete AbilityRunningRecord using null args. + * EnvConditions: NA + * CaseDescription: Verify the function ClearAbility works but does not take effect using nullptr parameter. + */ +HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_002, TestSize.Level1) +{ + APP_LOGD("DeleteAbilityRunningRecord_002 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + + appRunningRecord->ClearAbility(nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + APP_LOGD("DeleteAbilityRunningRecord_002 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Delete AbilityRunningRecord that does not exist. + * EnvConditions: NA + * CaseDescription: Verify the function ClearAbility cannot delete AbilityRunningRecord that does not exist. + */ +HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_003, TestSize.Level1) +{ + APP_LOGD("DeleteAbilityRunningRecord_003 start."); + auto appRunningRecord = GetTestAppRunningRecord(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto anotherAbilityInfo = std::make_shared(); + anotherAbilityInfo->name = GetAnotherTestAbilityName(); + sptr token = new MockAbilityToken(); + sptr anotherToken = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); + + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(anotherAbilityRunningRecord != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(anotherToken) != nullptr); + + appRunningRecord->ClearAbility(anotherAbilityRunningRecord); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(anotherToken) == nullptr); + + appRunningRecord->ClearAbility(anotherAbilityRunningRecord); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(anotherToken) == nullptr); + APP_LOGD("DeleteAbilityRunningRecord_003 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: IsSameState + * FunctionPoints: Check state is same or different. + * EnvConditions: NA + * CaseDescription: Verify the function IsSameState judge the exact state value. + */ +HWTEST_F(AmsAbilityRunningRecordTest, IsSameState_001, TestSize.Level1) +{ + APP_LOGD("IsSameState_001 start."); + + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + sptr token = new MockAbilityToken(); + std::shared_ptr abilityRunningRecord = + std::make_shared(abilityInfo, token); + + abilityRunningRecord->SetState(AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(false, abilityRunningRecord->IsSameState(AbilityState::ABILITY_STATE_BACKGROUND)); + EXPECT_EQ(true, abilityRunningRecord->IsSameState(AbilityState::ABILITY_STATE_FOREGROUND)); + + APP_LOGD("IsSameState_001 end."); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Create AbilityRunningRecord using correct args. + * EnvConditions: NA + * CaseDescription: Verify the function AddAbility can create AbilityRunningRecord add add to AppRunningRecord. + */ +HWTEST_F(AmsAbilityRunningRecordTest, SetGetAbilityRecord_001, TestSize.Level1) +{ + APP_LOGD("SetGetAbilityRecord_001 start."); + + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appRunningRecord = GetTestAppRunningRecord(); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_TRUE(abilityRunningRecord != nullptr); + abilityRunningRecord->SetVisibility(1); + abilityRunningRecord->SetPerceptibility(1); + abilityRunningRecord->SetConnectionState(1); + + EXPECT_EQ(abilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + + auto testRecord = appRunningRecord->GetAbilityRunningRecordByToken(token); + EXPECT_EQ(1, testRecord->GetVisibility()); + EXPECT_EQ(1, testRecord->GetPerceptibility()); + EXPECT_EQ(1, testRecord->GetConnectionState()); + + APP_LOGD("SetGetAbilityRecord_001 end."); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..359b7c19aad4a9d033416efa86bce9c170e73dcc --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AppDeathRecipientTest") { + module_out_path = module_output_path + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", + "${services_path}/appmgr/src/app_lifecycle_deal.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_process_manager.cpp", + "${services_path}/appmgr/src/app_running_manager.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/src/cgroup_manager.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/module_running_record.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + "${services_path}/appmgr/src/process_optimizer_uba.cpp", + "${services_path}/appmgr/src/remote_client_manager.cpp", + "${services_path}/appmgr/test/mock/src/mock_bundle_manager.cpp", + ] + + include_dirs = [ + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources += [ "ams_app_death_recipient_test.cpp" ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AppDeathRecipientTest" ] +} diff --git a/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp b/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d87a6d53b79f04fb4a6683060f739e00993ecb61 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_death_recipient.h" +#include "app_mgr_service_inner.h" +#undef private +#include +#include "app_log_wrapper.h" +#include "app_mgr_service_inner.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" +#include "iremote_object.h" +#include "mock_bundle_manager.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; + +namespace OHOS { +namespace AppExecFwk { +class AppDeathRecipientTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +public: + const std::shared_ptr GetAbilityInfoByIndex(const int32_t index) const; + const std::shared_ptr GetApplicationByIndex(const int32_t index) const; + const std::shared_ptr GetAppRunningRecordByIndex(const int32_t index) const; + sptr GetApp(int32_t pid, int size); + +public: + std::shared_ptr handler_; + std::shared_ptr appMgrServiceInner_; + sptr appDeathRecipientObject_; + OHOS::sptr mockToken_; + OHOS::sptr mockBundleMgr; +}; + +static void WaitUntilTaskFinished(std::shared_ptr handler) +{ + if (!handler) { + return; + } + + const uint32_t MAX_RETRY_COUNT = 1000; + const uint32_t SLEEP_TIME = 1000; + uint32_t count = 0; + std::atomic taskCalled(false); + auto f = [&taskCalled]() { taskCalled.store(true); }; + if (handler->PostTask(f)) { + while (!taskCalled.load()) { + ++count; + // if delay more than 1 second, break + if (count >= MAX_RETRY_COUNT) { + break; + } + + usleep(SLEEP_TIME); + } + } +} + +void AppDeathRecipientTest::SetUpTestCase() +{} + +void AppDeathRecipientTest::TearDownTestCase() +{} + +void AppDeathRecipientTest::SetUp() +{ + auto runner = EventRunner::Create("AppDeathRecipientTest"); + appMgrServiceInner_ = std::make_shared(); + + handler_ = std::make_shared(runner, appMgrServiceInner_); + + appDeathRecipientObject_ = new (std::nothrow) AppDeathRecipient(); + + mockBundleMgr = new (std::nothrow) BundleMgrService(); + appMgrServiceInner_->SetBundleManager(mockBundleMgr); +} + +void AppDeathRecipientTest::TearDown() +{} + +const std::shared_ptr AppDeathRecipientTest::GetAbilityInfoByIndex(const int32_t index) const +{ + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "AppDeathRecipientTest_ability" + std::to_string(index); + abilityInfo->applicationName = "com.ohos.test.helloworld" + std::to_string(index); + abilityInfo->applicationInfo.bundleName = "com.ohos.test.helloworld" + std::to_string(index); + return abilityInfo; +} + +const std::shared_ptr AppDeathRecipientTest::GetApplicationByIndex(const int32_t index) const +{ + std::shared_ptr appInfo = std::make_shared(); + appInfo->name = "com.ohos.test.helloworld" + std::to_string(index); + appInfo->bundleName = "com.ohos.test.helloworld" + std::to_string(index); + return appInfo; +} + +const std::shared_ptr AppDeathRecipientTest::GetAppRunningRecordByIndex(const int32_t index) const +{ + auto appInfo = GetApplicationByIndex(index); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appRecord = appMgrServiceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, appInfo->uid, bundleInfo); + + EXPECT_NE(nullptr, appRecord); + return appRecord; +} + +sptr AppDeathRecipientTest::GetApp(int32_t pid, int size) +{ + auto abilityInfo = GetAbilityInfoByIndex(pid); + auto appInfo = GetApplicationByIndex(pid); + sptr token = new MockAbilityToken(); + + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + std::shared_ptr mockClientstr(mockClientPtr); + appMgrServiceInner_->SetAppSpawnClient(mockClientstr); + + appMgrServiceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + + auto appRecord = GetAppRunningRecordByIndex(pid); + + EXPECT_EQ(size, static_cast(appMgrServiceInner_->GetRecentAppList().size())); + + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + + return client->AsObject(); +} + +/* + * Feature: Ams + * Function: SetEventHandler ande SetAppMgrServiceInner. + * SubFunction: AppDeathRecipient + * FunctionPoints: initialization + * EnvConditions: have to an application + * CaseDescription: How to set parameters + */ + +HWTEST_F(AppDeathRecipientTest, AppDeathRecipient_001, TestSize.Level1) +{ + APP_LOGI("AppDeathRecipient_001 start"); + appDeathRecipientObject_->SetEventHandler(handler_); + EXPECT_TRUE(appDeathRecipientObject_->handler_.lock() != nullptr); + + appDeathRecipientObject_->SetAppMgrServiceInner(appMgrServiceInner_); + EXPECT_TRUE(appDeathRecipientObject_->appMgrServiceInner_.lock() != nullptr); + APP_LOGI("AppDeathRecipient_001 end"); +} + +/* + * Feature: Ams + * Function: OnRemoteDied + * SubFunction: AppDeathRecipient + * FunctionPoints: Applied death notification + * EnvConditions: have to an application + * CaseDescription: Call back the death notification of the notification application + */ +HWTEST_F(AppDeathRecipientTest, AppDeathRecipient_002, TestSize.Level1) +{ + pid_t pid1 = 24; + pid_t pid2 = 25; + + sptr appOne = GetApp(pid1, 1); + + sptr appTwo = GetApp(pid2, 2); + + appDeathRecipientObject_->SetEventHandler(handler_); + appDeathRecipientObject_->SetAppMgrServiceInner(appMgrServiceInner_); + appDeathRecipientObject_->OnRemoteDied(appOne); + + WaitUntilTaskFinished(handler_); + EXPECT_EQ(1, static_cast(appDeathRecipientObject_->appMgrServiceInner_.lock()->GetRecentAppList().size())); + + appDeathRecipientObject_->OnRemoteDied(appTwo); + + WaitUntilTaskFinished(handler_); + EXPECT_EQ(0, static_cast(appDeathRecipientObject_->appMgrServiceInner_.lock()->GetRecentAppList().size())); + APP_LOGI("AppDeathRecipient_002 start"); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ba84cbcf5290ada75854d19490d8eb59f5da69b0 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn @@ -0,0 +1,81 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsAppLifeCycleTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_lifecycle_deal.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_process_manager.cpp", + "${services_path}/appmgr/src/app_running_manager.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/src/cgroup_manager.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/module_running_record.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + "${services_path}/appmgr/src/process_optimizer_uba.cpp", + "${services_path}/appmgr/src/remote_client_manager.cpp", + "${services_path}/appmgr/test/mock/src/mock_bundle_manager.cpp", + ] + + sources += [ "ams_app_life_cycle_test.cpp" ] + + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsAppLifeCycleTest" ] +} diff --git a/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b4ebe05821c043a7d64bb327103a09bc60bf6a5 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp @@ -0,0 +1,2236 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ +#define private public +#include "app_mgr_service_inner.h" +#undef private + +#include +#include +#include "iremote_object.h" +#include "refbase.h" +#include "app_launch_data.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" +#include "mock_app_spawn_socket.h" +#include "mock_iapp_state_callback.h" +#include "mock_bundle_manager.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; +namespace OHOS { +namespace AppExecFwk { +struct TestApplicationPreRecord { + TestApplicationPreRecord(const std::shared_ptr &firstAbilityRecord, + const std::shared_ptr &appRecord, const sptr &mockAppScheduler) + : firstAbilityRecord_(firstAbilityRecord), appRecord_(appRecord), mockAppScheduler_(mockAppScheduler) + {} + virtual ~TestApplicationPreRecord() + {} + + std::shared_ptr firstAbilityRecord_; + std::shared_ptr appRecord_; + sptr mockAppScheduler_ = nullptr; +}; +class AmsAppLifeCycleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr StartProcessAndLoadAbility(const sptr &token, + const sptr &preToken, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo, const pid_t newPid) const; + + std::shared_ptr LoadTestAbility(const sptr &token, + const sptr &preToken, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo); + + sptr GetMockToken() const; + std::shared_ptr GetAbilityInfoByIndex(const std::string &index) const; + std::shared_ptr GetApplication() const; + TestApplicationPreRecord PrepareLoadTestAbilityAndApp(const ApplicationState currentAppState) const; + TestApplicationPreRecord CreateTestApplicationRecord( + const AbilityState abilityState, const ApplicationState appState) const; + std::shared_ptr CreateTestApplicationAndSetState(const ApplicationState appState) const; + sptr AddApplicationClient(const std::shared_ptr &appRecord) const; + void TestUpdateAbilityStateWhenAbilityIsUnLoaded(const AbilityState changingState) const; + void TestUpdateAbilityStateWhenAbilityIsCreate( + const AbilityState changingState, const ApplicationState curAppState) const; + void TestUpdateAbilityStateToBackgroundWhenAbilityIsReady(const ApplicationState curAppState) const; + void TestUpdateAbilityStateToBackgroundWhenAbilityIsBackground(const ApplicationState curAppState); + void TestTerminateAbilityWhenAbilityIsNotBackground( + const AbilityState curAbilityState, const ApplicationState curAppState) const; + std::shared_ptr AddNewAbility( + const std::shared_ptr &appRecord, const std::string &index) const; + std::shared_ptr AddNewAbility( + const std::shared_ptr &appRecord, const std::string &index, const int uid) const; + +protected: + std::shared_ptr serviceInner_; + sptr mock_token_ = nullptr; + sptr mockBundleMgr = nullptr; + std::shared_ptr handler_ = nullptr; + sptr mockAppStateCallbackStub_ = nullptr; +}; + +void AmsAppLifeCycleTest::SetUpTestCase() +{} + +void AmsAppLifeCycleTest::TearDownTestCase() +{} + +void AmsAppLifeCycleTest::SetUp() +{ + serviceInner_.reset(new (std::nothrow) AppMgrServiceInner()); + mock_token_ = new (std::nothrow) MockAbilityToken(); + mockBundleMgr = new (std::nothrow) BundleMgrService(); + serviceInner_->SetBundleManager(mockBundleMgr); + + auto runner = EventRunner::Create("AmsAppLifeCycleTest"); + handler_ = std::make_shared(runner, serviceInner_); + serviceInner_->SetEventHandler(handler_); +} + +void AmsAppLifeCycleTest::TearDown() +{} + +std::shared_ptr AmsAppLifeCycleTest::StartProcessAndLoadAbility(const sptr &token, + const sptr &preToken, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo, const pid_t newPid) const +{ + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(newPid), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(mockClientPtr); + + serviceInner_->LoadAbility(token, preToken, abilityInfo, appInfo); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + auto record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, appInfo->uid, bundleInfo); + EXPECT_EQ(record->GetPriorityObject()->GetPid(), newPid); + return record; +} + +sptr AmsAppLifeCycleTest::GetMockToken() const +{ + return mock_token_; +} + +std::shared_ptr AmsAppLifeCycleTest::GetAbilityInfoByIndex(const std::string &index) const +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = "test_ability" + index; + abilityInfo->applicationName = "com.ohos.test.helloworld"; + abilityInfo->process = "com.ohos.test.helloworld"; + abilityInfo->applicationInfo.bundleName = "com.ohos.test.helloworld"; + return abilityInfo; +} + +std::shared_ptr AmsAppLifeCycleTest::GetApplication() const +{ + auto appInfo = std::make_shared(); + appInfo->name = "com.ohos.test.helloworld"; + appInfo->bundleName = "com.ohos.test.helloworld"; + return appInfo; +} + +// load the first ability and create his parent app, then set app a state +TestApplicationPreRecord AmsAppLifeCycleTest::PrepareLoadTestAbilityAndApp(const ApplicationState currentAppState) const +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + EXPECT_EQ(AbilityState::ABILITY_STATE_CREATE, abilityRecord->GetState()); + appRecord->SetState(currentAppState); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + TestApplicationPreRecord testAppPreRecord(abilityRecord, appRecord, mockAppScheduler); + return testAppPreRecord; +} + +// create one application that include one ability, and set state +TestApplicationPreRecord AmsAppLifeCycleTest::CreateTestApplicationRecord( + const AbilityState abilityState, const ApplicationState appState) const +{ + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, "com.ohos.test.helloworld", bundleInfo, hapModuleInfo); + + appRecord->SetEventHandler(handler_); + EXPECT_NE(appRecord, nullptr); + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_NE(abilityRecord, nullptr); + abilityRecord->SetState(abilityState); + appRecord->SetState(appState); + sptr mockAppScheduler = AddApplicationClient(appRecord); + + TestApplicationPreRecord testAppPreRecord(abilityRecord, appRecord, mockAppScheduler); + return testAppPreRecord; +} + +std::shared_ptr AmsAppLifeCycleTest::CreateTestApplicationAndSetState( + const ApplicationState appState) const +{ + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, "AmsAppLifeCycleTest", bundleInfo, hapModuleInfo); + + EXPECT_NE(appRecord, nullptr); + appRecord->SetEventHandler(handler_); + appRecord->SetState(appState); + return appRecord; +} + +sptr AmsAppLifeCycleTest::AddApplicationClient( + const std::shared_ptr &appRecord) const +{ + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + return mockAppScheduler; +} + +void AmsAppLifeCycleTest::TestUpdateAbilityStateWhenAbilityIsUnLoaded(const AbilityState changingState) const +{ + sptr token = GetMockToken(); + serviceInner_->UpdateAbilityState(token, changingState); + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(token); + EXPECT_EQ(appRecord, nullptr); +} + +void AmsAppLifeCycleTest::TestUpdateAbilityStateWhenAbilityIsCreate( + const AbilityState changingState, const ApplicationState curAppState) const +{ + auto testAppPreRecord = CreateTestApplicationRecord(AbilityState::ABILITY_STATE_CREATE, curAppState); + auto abilityState = testAppPreRecord.firstAbilityRecord_->GetState(); + + serviceInner_->UpdateAbilityState(GetMockToken(), changingState); + EXPECT_EQ(abilityState, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(curAppState, testAppPreRecord.appRecord_->GetState()); +} + +void AmsAppLifeCycleTest::TestUpdateAbilityStateToBackgroundWhenAbilityIsReady(const ApplicationState curAppState) const +{ + auto testAppPreRecord = CreateTestApplicationRecord(AbilityState::ABILITY_STATE_READY, curAppState); + + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(curAppState, testAppPreRecord.appRecord_->GetState()); +} + +void AmsAppLifeCycleTest::TestUpdateAbilityStateToBackgroundWhenAbilityIsBackground(const ApplicationState curAppState) +{ + auto testAppPreRecord = CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, curAppState); + + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(curAppState, testAppPreRecord.appRecord_->GetState()); +} + +void AmsAppLifeCycleTest::TestTerminateAbilityWhenAbilityIsNotBackground( + const AbilityState curAbilityState, const ApplicationState curAppState) const +{ + auto testAppPreRecord = CreateTestApplicationRecord(curAbilityState, curAppState); + + serviceInner_->TerminateAbility(GetMockToken()); + EXPECT_EQ(curAbilityState, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(curAppState, testAppPreRecord.appRecord_->GetState()); +} + +std::shared_ptr AmsAppLifeCycleTest::AddNewAbility( + const std::shared_ptr &appRecord, const std::string &index) const +{ + auto newAbilityInfo = GetAbilityInfoByIndex(index); + sptr newToken = new (std::nothrow) MockAbilityToken(); + serviceInner_->LoadAbility(newToken, nullptr, newAbilityInfo, GetApplication()); + auto newAbilityRecord = appRecord->GetAbilityRunningRecordByToken(newToken); + EXPECT_NE(newAbilityRecord, nullptr); + return newAbilityRecord; +} + +std::shared_ptr AmsAppLifeCycleTest::AddNewAbility( + const std::shared_ptr &appRecord, const std::string &index, const int uid) const +{ + auto newAbilityInfo = GetAbilityInfoByIndex(index); + newAbilityInfo->applicationInfo.uid = uid; + auto app = GetApplication(); + app->uid = uid; + sptr newToken = new (std::nothrow) MockAbilityToken(); + serviceInner_->LoadAbility(newToken, nullptr, newAbilityInfo, app); + auto newAbilityRecord = appRecord->GetAbilityRunningRecordByToken(newToken); + EXPECT_NE(newAbilityRecord, nullptr); + return newAbilityRecord; +} + +/* + * Feature: AMS + * Function: AppLifeCycle::CreateAppRunningRecord + * SubFunction: bundleMgr CheckPermission + * FunctionPoints: UnsuspendApplication + * CaseDescription: Check if there is background operation permission + */ +HWTEST_F(AmsAppLifeCycleTest, RemoveAppFromRecentList_001, TestSize.Level1) +{ + RecordQueryResult result; + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, 100); + appRecord->SetApplicationClient(client); + + EXPECT_TRUE(appRecord); + int size = serviceInner_->GetRecentAppList().size(); + EXPECT_EQ(size, 1); + EXPECT_FALSE(result.appExists); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = "test_ability_1"; + abilityInfo2->applicationName = "com.ohos.test.special"; + abilityInfo2->process = "com.ohos.test.special"; + abilityInfo2->applicationInfo.bundleName = "com.ohos.test.special"; + + auto appInfo2 = std::make_shared(); + appInfo2->name = "com.ohos.test.special"; + appInfo2->bundleName = "com.ohos.test.special"; + sptr token2 = GetMockToken(); + + auto appRecord2 = StartProcessAndLoadAbility(token2, nullptr, abilityInfo2, appInfo2, 101); + appRecord2->SetApplicationClient(client); + EXPECT_TRUE(appRecord2); + size = serviceInner_->GetRecentAppList().size(); + EXPECT_EQ(size, 2); + EXPECT_FALSE(result.appExists); + + // remove the first + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + serviceInner_->RemoveAppFromRecentList(appRecord->GetName(), appRecord->GetName()); + sleep(1); + size = serviceInner_->GetRecentAppList().size(); + EXPECT_EQ(size, 1); + + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + serviceInner_->RemoveAppFromRecentList(appRecord2->GetName(), appRecord2->GetName()); + sleep(3); + + auto list = serviceInner_->GetRecentAppList(); + size = list.size(); + EXPECT_EQ(size, 0); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Init + * FunctionPoints: Init + * CaseDescription: test application init process + */ +HWTEST_F(AmsAppLifeCycleTest, Init_001, TestSize.Level1) +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto record = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + + serviceInner_->AttachApplication(NEW_PID, client); + EXPECT_NE(record->GetApplicationClient(), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_READY, record->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: LoadAbility + * CaseDescription: LoadAbility when ability is loaded. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_001, TestSize.Level1) +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + AbilityState abilityState = abilityRecord->GetState(); + ApplicationState appState = appRecord->GetState(); + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(abilityState, abilityRecord->GetState()); + EXPECT_EQ(appState, appRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: LoadAbility + * CaseDescription: LoadAbility when ability and application is not created. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_002, TestSize.Level1) +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + + serviceInner_->AttachApplication(NEW_PID, client); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, abilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_READY, appRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: LoadAbility + * CaseDescription: Load ability when ability is not created but application is create. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_003, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_CREATE); + + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_CREATE, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_CREATE, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: LoadAbility + * CaseDescription: Load ability when ability is not created but application is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_004, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_READY); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_READY, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: LoadAbility + * CaseDescription: Load ability when ability is not created but application is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_005, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: LoadAbility + * CaseDescription: Load ability when ability is not created but application is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_006, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_BACKGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: LoadAbility + * CaseDescription: Load ability when ability is not created but application is suspended. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_007, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_SUSPENDED); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is not loaded. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_008, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsUnLoaded(AbilityState::ABILITY_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability and app is create. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_009, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_CREATE); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is create but app is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_010, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is create but app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_011, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is create but app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_012, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_BACKGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability and app is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_013, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppPreRecord.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is ready and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_014, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_FOREGROUND); + + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is ready and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_015, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppPreRecord.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_016, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is background and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_017, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_FOREGROUND); + + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_018, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppPreRecord.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to foreground + * CaseDescription: Update ability state to foreground when ability is background and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_019, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_SUSPENDED); + + EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppPreRecord.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is not loaded. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_020, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsUnLoaded(AbilityState::ABILITY_STATE_BACKGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability and app is create. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_021, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_CREATE); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is create but app is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_022, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is create but app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_023, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is create but app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_024, TestSize.Level1) +{ + TestUpdateAbilityStateWhenAbilityIsCreate( + AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability and app is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_025, TestSize.Level1) +{ + TestUpdateAbilityStateToBackgroundWhenAbilityIsReady(ApplicationState::APP_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is ready and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_026, TestSize.Level1) +{ + TestUpdateAbilityStateToBackgroundWhenAbilityIsReady(ApplicationState::APP_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is ready and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_027, TestSize.Level1) +{ + TestUpdateAbilityStateToBackgroundWhenAbilityIsReady(ApplicationState::APP_STATE_BACKGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_028, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppPreRecord.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when multiple ability. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_029, TestSize.Level1) +{ + auto testAppPreRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + auto newAbilityInfo = GetAbilityInfoByIndex("1"); + sptr newToken = new MockAbilityToken(); + + auto appInfo = GetApplication(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + testAppPreRecord.appRecord_->AddModule(appInfo, newAbilityInfo, newToken, hapModuleInfo); + auto moduleRecord = + testAppPreRecord.appRecord_->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto newAbilityRecord = moduleRecord->GetAbilityRunningRecordByToken(newToken); + newAbilityRecord->SetState(AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_NE(newAbilityRecord, nullptr); + + serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is background and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_030, TestSize.Level1) +{ + TestUpdateAbilityStateToBackgroundWhenAbilityIsBackground(ApplicationState::APP_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is background and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_031, TestSize.Level1) +{ + TestUpdateAbilityStateToBackgroundWhenAbilityIsBackground(ApplicationState::APP_STATE_BACKGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Update ability state to background + * CaseDescription: Update ability state to background when ability is background and app is suspended. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_032, TestSize.Level1) +{ + TestUpdateAbilityStateToBackgroundWhenAbilityIsBackground(ApplicationState::APP_STATE_SUSPENDED); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is unload. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_033, TestSize.Level1) +{ + serviceInner_->TerminateAbility(GetMockToken()); + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(GetMockToken()); + EXPECT_EQ(appRecord, nullptr); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability and app is create. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_034, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_CREATE, ApplicationState::APP_STATE_CREATE); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is create and app is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_035, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_CREATE, ApplicationState::APP_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is create and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_036, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_CREATE, ApplicationState::APP_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is create and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_037, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_CREATE, ApplicationState::APP_STATE_BACKGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability and app is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_038, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is ready and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_039, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is ready and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_040, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_BACKGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_041, TestSize.Level1) +{ + TestTerminateAbilityWhenAbilityIsNotBackground( + AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is background and app is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_042, TestSize.Level1) +{ + auto testAppRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1", -1); + newAbilityRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + serviceInner_->TerminateAbility(newAbilityRecord->GetToken()); + serviceInner_->AbilityTerminated(newAbilityRecord->GetToken()); + auto abilityRecord = testAppRecord.appRecord_->GetAbilityRunningRecordByToken(newAbilityRecord->GetToken()); + EXPECT_EQ(nullptr, abilityRecord); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_043, TestSize.Level1) +{ + auto testAppRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + serviceInner_->TerminateAbility(GetMockToken()); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + serviceInner_->AbilityTerminated(GetMockToken()); + auto abilityRecord = testAppRecord.appRecord_->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_EQ(nullptr, abilityRecord); + + serviceInner_->ApplicationTerminated(testAppRecord.appRecord_->GetRecordId()); + auto appInfo = GetApplication(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, appInfo->uid, bundleInfo); + EXPECT_EQ(nullptr, appRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when multiple abilities and app is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_044, TestSize.Level1) +{ + auto testAppRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1", -1); + newAbilityRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + serviceInner_->TerminateAbility(GetMockToken()); + serviceInner_->AbilityTerminated(GetMockToken()); + auto abilityRecord = testAppRecord.appRecord_->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_EQ(nullptr, abilityRecord); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when ability is background and app is suspended. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_045, TestSize.Level1) +{ + auto testAppRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_SUSPENDED); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + serviceInner_->TerminateAbility(GetMockToken()); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + serviceInner_->AbilityTerminated(GetMockToken()); + auto abilityRecord = testAppRecord.appRecord_->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_EQ(nullptr, abilityRecord); + + serviceInner_->ApplicationTerminated(testAppRecord.appRecord_->GetRecordId()); + + auto appInfo = GetApplication(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, appInfo->uid, bundleInfo); + EXPECT_EQ(nullptr, appRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Terminate ability + * CaseDescription: Terminate ability when multiple abilities is backgroung and app is suspended. + */ +HWTEST_F(AmsAppLifeCycleTest, Schedule_046, TestSize.Level1) +{ + auto testAppRecord = + CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_SUSPENDED); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1", -1); + newAbilityRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_SUSPENDED); + + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + serviceInner_->TerminateAbility(GetMockToken()); + serviceInner_->AbilityTerminated(GetMockToken()); + auto abilityRecord = testAppRecord.appRecord_->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_EQ(nullptr, abilityRecord); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationForegrounded + * CaseDescription: Verify application can not change to foreground if application is create. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_001, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_CREATE); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationForegrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_CREATE, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationForegrounded + * CaseDescription: Verify application can change to foreground if application is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_002, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_READY); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationForegrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationForegrounded + * CaseDescription: Verify application can not change to foreground if application is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_003, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_FOREGROUND); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationForegrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationForegrounded + * CaseDescription: Verify application can change to foreground if application is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_004, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_BACKGROUND); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationForegrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationForegrounded + * CaseDescription: Verify application can change to foregrounded if application is not exist. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_005, TestSize.Level1) +{ + int32_t appRecordId = AppRecordId::Create(); + + serviceInner_->ApplicationForegrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_EQ(nullptr, testAppRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationBackgrounded + * CaseDescription: Verify application can not change to background if application is create. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_006, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_CREATE); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationBackgrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_CREATE, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationBackgrounded + * CaseDescription: Verify application can change to background if application is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_007, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_FOREGROUND); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationBackgrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationBackgrounded + * CaseDescription: Verify application can not change to background if application is ready. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_008, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_READY); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationBackgrounded(appRecord->GetRecordId()); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecord->GetRecordId()); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_READY, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationBackgrounded + * CaseDescription: Verify application can not change to background if application is not exist. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_009, TestSize.Level1) +{ + int32_t appRecordId = AppRecordId::Create(); + + serviceInner_->ApplicationBackgrounded(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_EQ(nullptr, testAppRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationTerminated + * CaseDescription: Verify application can change to terminate if application is background. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_010, TestSize.Level1) +{ + auto testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_BACKGROUND); + serviceInner_->AbilityTerminated(GetMockToken()); + serviceInner_->ApplicationTerminated(testAppRecord.appRecord_->GetRecordId()); + auto appRecord = serviceInner_->GetAppRunningRecordByAppRecordId(testAppRecord.appRecord_->GetRecordId()); + if (appRecord) { + EXPECT_FALSE(appRecord->IsLauncherApp()); + } +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationTerminated + * CaseDescription: Verify application can not change to terminate if application is foreground. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_011, TestSize.Level1) +{ + auto appRecord = CreateTestApplicationAndSetState(ApplicationState::APP_STATE_FOREGROUND); + int32_t appRecordId = appRecord->GetRecordId(); + EXPECT_TRUE(appRecordId > 0); + + serviceInner_->ApplicationTerminated(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_NE(nullptr, testAppRecord); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: ApplicationTerminated + * CaseDescription: Verify application can not change to foregrounded if application is not exist. + */ +HWTEST_F(AmsAppLifeCycleTest, Process_012, TestSize.Level1) +{ + int32_t appRecordId = AppRecordId::Create(); + serviceInner_->ApplicationTerminated(appRecordId); + auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); + EXPECT_EQ(nullptr, testAppRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: AppMgrService stop + * CaseDescription: Verify if AppMgrService stop successfully. + */ +HWTEST_F(AmsAppLifeCycleTest, Stop_001, TestSize.Level1) +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + AbilityState abilityState = abilityRecord->GetState(); + ApplicationState appState = appRecord->GetState(); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(abilityState, abilityRecord->GetState()); + EXPECT_EQ(appState, appRecord->GetState()); + + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, serviceInner_->QueryAppSpawnConnectionState()); + int32_t size = serviceInner_->GetRecordMap().size(); + EXPECT_EQ(1, size); + serviceInner_->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, serviceInner_->QueryAppSpawnConnectionState()); + size = serviceInner_->GetRecordMap().size(); + EXPECT_EQ(0, size); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: AppMgrService stop + * CaseDescription: Verify if AppMgrService stop successfully. + */ +HWTEST_F(AmsAppLifeCycleTest, Stop_002, TestSize.Level1) +{ + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + serviceInner_->SetAppSpawnClient(appSpawnClient); + serviceInner_->OpenAppSpawnConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, serviceInner_->QueryAppSpawnConnectionState()); + int32_t size = serviceInner_->GetRecordMap().size(); + EXPECT_EQ(0, size); + + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + serviceInner_->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, serviceInner_->QueryAppSpawnConnectionState()); + size = serviceInner_->GetRecordMap().size(); + EXPECT_EQ(0, size); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: AppMgrService stop + * CaseDescription: Verify if AppMgrService stop successfully. + */ +HWTEST_F(AmsAppLifeCycleTest, Stop_003, TestSize.Level1) +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + AbilityState abilityState = abilityRecord->GetState(); + ApplicationState appState = appRecord->GetState(); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(abilityState, abilityRecord->GetState()); + EXPECT_EQ(appState, appRecord->GetState()); + + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + serviceInner_->SetAppSpawnClient(appSpawnClient); + serviceInner_->OpenAppSpawnConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, serviceInner_->QueryAppSpawnConnectionState()); + int32_t size = serviceInner_->GetRecordMap().size(); + EXPECT_EQ(1, size); + + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + serviceInner_->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, serviceInner_->QueryAppSpawnConnectionState()); + size = serviceInner_->GetRecordMap().size(); + EXPECT_EQ(0, size); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Kill application + * CaseDescription: Verify if AppMgrService Kill by appname fail. + */ +HWTEST_F(AmsAppLifeCycleTest, KillApplication_001, TestSize.Level1) +{ + int result = serviceInner_->KillApplication("hwei.ss.bb"); + EXPECT_EQ(ERR_OK, result); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Kill application + * CaseDescription: Verify if AppMgrService Kill by appname successfully. + */ +HWTEST_F(AmsAppLifeCycleTest, KillApplication_002, TestSize.Level1) +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(NEW_PID), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(mockClientPtr); + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, appInfo->uid, bundleInfo); + EXPECT_EQ(appRecord->GetPriorityObject()->GetPid(), NEW_PID); + + pid_t pid = fork(); + if (pid > 0) { + appRecord->GetPriorityObject()->SetPid(pid); + } + + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + + int ret = serviceInner_->KillApplication(abilityInfo->applicationName); + EXPECT_EQ(ERR_OK, ret); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Kill application + * CaseDescription: Verify if AppMgrService Kill by pid successfully. + */ +HWTEST_F(AmsAppLifeCycleTest, KillProcessByPid001, TestSize.Level1) +{ + pid_t pid = fork(); + + if (pid > 0) { + int32_t ret = serviceInner_->KillProcessByPid(pid); + EXPECT_EQ(ERR_OK, ret); + } + + if (pid == 0) { + int32_t ret = serviceInner_->KillProcessByPid(pid); + EXPECT_EQ(-1, ret); + } +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Kill application + * CaseDescription: Verify if AppMgrService Kill by pid fail. + */ +HWTEST_F(AmsAppLifeCycleTest, KillProcessByPid002, TestSize.Level1) +{ + int32_t ret = serviceInner_->KillProcessByPid(-1); + EXPECT_EQ(-1, ret); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Register App State Callback + * CaseDescription: Verify if AppMgrService Register Callback. + */ +HWTEST_F(AmsAppLifeCycleTest, Callback001, TestSize.Level1) +{ + sptr mockCallback(new MockAppStateCallback()); + sptr callback = iface_cast(mockCallback); + serviceInner_->RegisterAppStateCallback(callback); + + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(2); + + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Register App State Callback + * CaseDescription: Verify if AppMgrService Register Callback. + */ +HWTEST_F(AmsAppLifeCycleTest, Callback002, TestSize.Level1) +{ + sptr mockCallback(new MockAppStateCallback()); + sptr callback = iface_cast(mockCallback); + serviceInner_->RegisterAppStateCallback(callback); + + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(0); + + serviceInner_->OnAppStateChanged(nullptr, ApplicationState::APP_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Register Ability State Callback + * CaseDescription: Verify if AppMgrService Register Callback. + */ +HWTEST_F(AmsAppLifeCycleTest, Callback003, TestSize.Level1) +{ + sptr mockCallback(new MockAppStateCallback()); + sptr callback = iface_cast(mockCallback); + + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + auto ability = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(ability, nullptr); + + serviceInner_->RegisterAppStateCallback(callback); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Register Ability State Callback + * CaseDescription: Verify if AppMgrService Register Callback. + */ +HWTEST_F(AmsAppLifeCycleTest, Callback004, TestSize.Level1) +{ + sptr mockCallback(new MockAppStateCallback()); + sptr callback = iface_cast(mockCallback); + serviceInner_->RegisterAppStateCallback(callback); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(0); + serviceInner_->OnAbilityStateChanged(nullptr, AbilityState::ABILITY_STATE_READY); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Register Ability State Changed + * CaseDescription: Verify if AppMgrService Ability State Changed Callback. + */ +HWTEST_F(AmsAppLifeCycleTest, AbilityStateChanged001, TestSize.Level1) +{ + sptr mockCallback(new MockAppStateCallback()); + sptr callback = iface_cast(mockCallback); + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + auto ability = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(ability, nullptr); + serviceInner_->RegisterAppStateCallback(callback); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BEGIN); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_CREATE); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_READY); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_TERMINATED); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + serviceInner_->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_END); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Register App State Changed + * CaseDescription: Verify if AppMgrService App State Changed Callback. + */ +HWTEST_F(AmsAppLifeCycleTest, AppStateChanged001, TestSize.Level1) +{ + sptr mockCallback(new MockAppStateCallback()); + sptr callback = iface_cast(mockCallback); + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_NE(appRecord, nullptr); + serviceInner_->RegisterAppStateCallback(callback); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BEGIN); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_READY); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + serviceInner_->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_END); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: UnsuspendApplication + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_BACKGROUND + */ +HWTEST_F(AmsAppLifeCycleTest, Unsuspend_001, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_BACKGROUND); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_SUSPENDED); + EXPECT_EQ(ApplicationState::APP_STATE_SUSPENDED, testAppRecord.appRecord_->GetState()); + serviceInner_->UnsuspendApplication(testAppRecord.appRecord_); + EXPECT_EQ(ApplicationState::APP_STATE_SUSPENDED, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: UnsuspendApplication + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_SUSPENDED(apprecord is nullptr) + */ +HWTEST_F(AmsAppLifeCycleTest, Unsuspend_002, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_BACKGROUND); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_SUSPENDED); + EXPECT_EQ(ApplicationState::APP_STATE_SUSPENDED, testAppRecord.appRecord_->GetState()); + serviceInner_->UnsuspendApplication(nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_SUSPENDED, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: suspendApplication + * FunctionPoints: suspendApplication + * CaseDescription: test application state is APP_STATE_SUSPENDED + */ +HWTEST_F(AmsAppLifeCycleTest, Suspend_001, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_BACKGROUND); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_SUSPENDED); + EXPECT_EQ(ApplicationState::APP_STATE_SUSPENDED, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: UnsuspendApplication + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_BACKGROUND(apprecord is nullptr) + */ +HWTEST_F(AmsAppLifeCycleTest, Suspend_002, TestSize.Level1) +{ + TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); + testAppRecord.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); + testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_BACKGROUND); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); + serviceInner_->UnsuspendApplication(nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: UnsuspendApplication + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_BACKGROUND(apprecord is nullptr) + */ +HWTEST_F(AmsAppLifeCycleTest, AbilityBehaviorAnalysis_001, TestSize.Level1) +{ + const pid_t NEW_PID = 1234; + auto abilityInfo = GetAbilityInfoByIndex("110"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_TRUE(appRecord != nullptr); + + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRecord != nullptr); + EXPECT_EQ(0, abilityRecord->GetVisibility()); + EXPECT_EQ(0, abilityRecord->GetPerceptibility()); + EXPECT_EQ(0, abilityRecord->GetConnectionState()); + + EXPECT_TRUE(serviceInner_); + serviceInner_->AbilityBehaviorAnalysis(token, nullptr, 1, 1, 1); + + auto abilityRecordAfter = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRecordAfter != nullptr); + EXPECT_EQ(1, abilityRecordAfter->GetVisibility()); + EXPECT_EQ(1, abilityRecordAfter->GetPerceptibility()); + EXPECT_EQ(1, abilityRecordAfter->GetConnectionState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: UnsuspendApplication + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_BACKGROUND(apprecord is nullptr) + */ +HWTEST_F(AmsAppLifeCycleTest, AbilityBehaviorAnalysis_002, TestSize.Level1) +{ + const pid_t NEW_PID = 1234; + auto abilityInfo = GetAbilityInfoByIndex("110"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + EXPECT_TRUE(appRecord != nullptr); + + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRecord != nullptr); + EXPECT_EQ(0, abilityRecord->GetVisibility()); + EXPECT_EQ(0, abilityRecord->GetPerceptibility()); + EXPECT_EQ(0, abilityRecord->GetConnectionState()); + + EXPECT_TRUE(serviceInner_); + serviceInner_->AbilityBehaviorAnalysis(nullptr, nullptr, 1, 1, 1); + + auto abilityRecordAfter = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRecordAfter != nullptr); + EXPECT_NE(1, abilityRecordAfter->GetVisibility()); + EXPECT_NE(1, abilityRecordAfter->GetPerceptibility()); + EXPECT_NE(1, abilityRecordAfter->GetConnectionState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: UnsuspendApplication + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_BACKGROUND(apprecord is nullptr) + */ +HWTEST_F(AmsAppLifeCycleTest, ClearUpApplicationData_001, TestSize.Level1) +{ + const pid_t NEW_PID = 1234; + auto abilityInfo = GetAbilityInfoByIndex("110"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, NEW_PID); + + // pid < 0 + appRecord->SetUid(101); + EXPECT_CALL(*mockBundleMgr, CleanBundleDataFiles(_, _)).Times(0); + serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), appRecord->GetUid(), 0); + + // uid < 0 + EXPECT_CALL(*mockBundleMgr, CleanBundleDataFiles(_, _)).Times(0); + serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), -1, NEW_PID); + + EXPECT_CALL(*mockBundleMgr, CleanBundleDataFiles(_, _)).Times(1).WillOnce(Return(101)); + + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + + serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), appRecord->GetUid(), NEW_PID); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ClearUpApplicationData + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_BACKGROUND(apprecord is nullptr) + */ +HWTEST_F(AmsAppLifeCycleTest, ClearUpApplicationData_002, TestSize.Level1) +{ + auto abilityInfo = GetAbilityInfoByIndex("110"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + int32_t pid = fork(); + + if (pid > 0) { + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, pid); + + EXPECT_CALL(*mockBundleMgr, CleanBundleDataFiles(_, _)).Times(1).WillOnce(Return(101)); + appRecord->SetUid(101); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), appRecord->GetUid(), pid); + } +} + +/* + * Feature: AMS + * Function: AppLifeCycle::IsBackgroundRunningRestricted + * SubFunction: bundleMgr CheckPermission + * FunctionPoints: UnsuspendApplication + * CaseDescription: Check if there is background operation permission + */ +HWTEST_F(AmsAppLifeCycleTest, IsBackgroundRunningRestricted_001, TestSize.Level1) +{ + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr); + EXPECT_CALL(*bundleMgr, CheckPermission(_, _)).Times(1).WillOnce(Return(ERR_OK)); + EXPECT_EQ(ERR_OK, serviceInner_->IsBackgroundRunningRestricted("bundle")); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::CreateAppRunningRecord + * SubFunction: bundleMgr CheckPermission + * FunctionPoints: UnsuspendApplication + * CaseDescription: Check if there is background operation permission + */ +HWTEST_F(AmsAppLifeCycleTest, CreateAppRunningRecord_001, TestSize.Level1) +{ + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( + nullptr, nullptr, appInfo, abilityInfo, "test_app", bundleInfo, hapModuleInfo); + EXPECT_TRUE(appRecord); + appRecord = serviceInner_->CreateAppRunningRecord( + token, nullptr, nullptr, abilityInfo, "test_app", bundleInfo, hapModuleInfo); + EXPECT_FALSE(appRecord); + appRecord = + serviceInner_->CreateAppRunningRecord(token, nullptr, appInfo, nullptr, "test_app", bundleInfo, hapModuleInfo); + EXPECT_TRUE(appRecord); + appRecord = + serviceInner_->CreateAppRunningRecord(token, nullptr, appInfo, abilityInfo, "", bundleInfo, hapModuleInfo); + EXPECT_FALSE(appRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::CreateAppRunningRecord + * SubFunction: bundleMgr CheckPermission + * FunctionPoints: UnsuspendApplication + * CaseDescription: Check if there is background operation permission + */ +HWTEST_F(AmsAppLifeCycleTest, CheckAppRunningRecordIsExist_001, TestSize.Level1) +{ + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, appInfo->name, bundleInfo, hapModuleInfo); + EXPECT_TRUE(appRecord); + + auto appRecordProc = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, abilityInfo->applicationInfo.uid, bundleInfo); + EXPECT_TRUE(appRecordProc); + + EXPECT_EQ(appRecord->GetRecordId(), appRecordProc->GetRecordId()); + EXPECT_TRUE(appRecord->GetName() == appRecordProc->GetName()); + EXPECT_TRUE(appRecord->GetUid() == appRecordProc->GetUid()); + EXPECT_TRUE(appRecord->GetProcessName() == appRecordProc->GetProcessName()); + + appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appRecordProc->GetState()); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::CreateAppRunningRecord + * SubFunction: bundleMgr CheckPermission + * FunctionPoints: UnsuspendApplication + * CaseDescription: Check if there is background operation permission + */ +HWTEST_F(AmsAppLifeCycleTest, GetAbilityRunningRecordByAbilityToken_001, TestSize.Level1) +{ + // RecordQueryResult result; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + auto abilityRecord = serviceInner_->GetAbilityRunningRecordByAbilityToken(nullptr); + EXPECT_FALSE(abilityRecord); + + abilityRecord = serviceInner_->GetAbilityRunningRecordByAbilityToken(token); + EXPECT_FALSE(abilityRecord); + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, 1234); + EXPECT_TRUE(appRecord); + + abilityRecord = serviceInner_->GetAbilityRunningRecordByAbilityToken(token); + sptr token2 = new MockAbilityToken(); + auto abilityRecord2 = serviceInner_->GetAbilityRunningRecordByAbilityToken(token2); + EXPECT_FALSE(abilityRecord2); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::LoadResidentProcess + * SubFunction: NA + * FunctionPoints: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleTest, LoadResidentProcess_001, TestSize.Level1) +{ + std::string appName = "KeepAliveApp"; + std::string proc = "KeepAliveApplication"; + int uid = 2100; + int pid = 120; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_FALSE(appRecord); + + MockAppSpawnClient *mockClientPtrT = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtrT); + EXPECT_CALL(*mockClientPtrT, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtrT)); + + serviceInner_->LoadResidentProcess(); + appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_TRUE(appRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::LoadResidentProcess + * SubFunction: NA + * FunctionPoints: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleTest, LoadResidentProcess_002, TestSize.Level1) +{ + std::string appName = "KeepAliveApp"; + std::string proc = "KeepAliveApplication"; + int uid = 2100; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_FALSE(appRecord); + + serviceInner_->LoadResidentProcess(); + appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_FALSE(appRecord); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::StartResidentProcess + * SubFunction: NA + * FunctionPoints: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleTest, StartResidentProcess_001, TestSize.Level1) +{ + pid_t pid = 123; + sptr token = GetMockToken(); + std::string appName = "KeepAliveApp"; + std::string proc = "KeepAliveApplication"; + int uid = 2100; + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "KeepAliveApplication"; + + std::vector infos; + BundleInfo info; + info.name = proc; + info.uid = uid; + info.hapModuleInfos.push_back(hapModuleInfo); + + ApplicationInfo appInfo; + appInfo.name = "KeepAliveApp"; + appInfo.bundleName = "KeepAliveApplication"; + appInfo.uid = 2100; + info.applicationInfo = appInfo; + infos.push_back(info); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_FALSE(appRecord); + + MockAppSpawnClient *mockClientPtrT = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtrT); + EXPECT_CALL(*mockClientPtrT, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtrT)); + + serviceInner_->StartResidentProcess(infos, -1); + + appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_TRUE(appRecord); + pid_t newPid = appRecord->GetPriorityObject()->GetPid(); + EXPECT_TRUE(newPid == pid); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::StartResidentProcess + * SubFunction: NA + * FunctionPoints: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleTest, StartResidentProcess_002, TestSize.Level1) +{ + pid_t pid = 123; + sptr token = GetMockToken(); + std::string appName = "KeepAliveApp"; + std::string proc = "KeepAliveApplication"; + int uid = 2100; + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "KeepAliveApplication"; + std::vector infos; + BundleInfo info; + info.name = proc; + info.uid = uid; + info.hapModuleInfos.push_back(hapModuleInfo); + + ApplicationInfo appInfo; + appInfo.name = "KeepAliveApp"; + appInfo.bundleName = "KeepAliveApplication"; + appInfo.uid = 2100; + info.applicationInfo = appInfo; + infos.push_back(info); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_FALSE(appRecord); + + MockAppSpawnClient *mockClientPtrT = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtrT); + EXPECT_CALL(*mockClientPtrT, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtrT)); + + serviceInner_->StartResidentProcess(infos, -1); + + appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_TRUE(appRecord); + int recordId = appRecord->GetRecordId(); + + // start agin + serviceInner_->StartResidentProcess(infos, -1); + + auto other = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_TRUE(other); + int id = other->GetRecordId(); + EXPECT_TRUE(recordId == id); +} + +/* + * Feature: AMS + * Function: AppLifeCycle::RestartResidentProcess + * SubFunction: NA + * FunctionPoints: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleTest, RestartResidentProcess_001, TestSize.Level1) +{ + sptr token = GetMockToken(); + std::string appName = "KeepAliveApp"; + std::string proc = "KeepAliveApplication"; + int uid = 2100; + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "KeepAliveApplication"; + std::vector infos; + BundleInfo info; + info.name = proc; + info.uid = uid; + info.hapModuleInfos.push_back(hapModuleInfo); + + ApplicationInfo appInfo; + appInfo.name = "KeepAliveApp"; + appInfo.bundleName = "KeepAliveApplication"; + appInfo.uid = 2100; + info.applicationInfo = appInfo; + infos.push_back(info); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_FALSE(appRecord); + + int recordId = 156; + auto app = std::make_shared(appInfo); + auto record = std::make_shared(app, recordId, proc); + serviceInner_->RestartResidentProcess(record); + + appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, bundleInfo); + EXPECT_FALSE(appRecord); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_app_mgr_client_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_mgr_client_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3f49da6249649985eb1e3b6b8e919493d08395cc --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_mgr_client_test/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsAppMgrClientTest") { + module_out_path = module_output_path + + sources = [ + "${aafwk_path}/interfaces/innerkits//app_manager/src/appmgr/app_mgr_client.cpp", + "${aafwk_path}/interfaces/innerkits//app_manager/src/appmgr/app_service_manager.cpp", + ] + + sources += [ "ams_app_mgr_client_test.cpp" ] + + include_dirs = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include/", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/", + "//foundation/aafwk/standard/interfaces/innerkits/base/include/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + configs = + [ "${aafwk_path}/interfaces/innerkits/app_manager:appmgr_sdk_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsAppMgrClientTest" ] +} diff --git a/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp b/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..048ec60c7404422eda0fe5093123b0cff0b2c293 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp @@ -0,0 +1,366 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_mgr_client.h" +#undef private +#include +#include "ability_info.h" +#include "application_info.h" +#include "app_log_wrapper.h" +#include "iapp_state_callback.h" +#include "mock_ability_token.h" +#include "mock_ams_mgr_scheduler.h" +#include "mock_app_mgr_service.h" +#include "mock_app_service_mgr.h" +#include "mock_iapp_state_callback.h" +#include "running_process_info.h" + +using namespace testing::ext; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; +using testing::Return; +using testing::SetArgReferee; + +namespace OHOS { +namespace AppExecFwk { +class AmsAppMgrClientTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + sptr preToken_; + std::unique_ptr client_; +}; + +void AmsAppMgrClientTest::SetUpTestCase() +{} + +void AmsAppMgrClientTest::TearDownTestCase() +{} + +void AmsAppMgrClientTest::SetUp() +{ + client_.reset(new (std::nothrow) AppMgrClient()); + client_->SetServiceManager(std::make_unique()); + token_ = new (std::nothrow) MockAbilityToken(); +} + +void AmsAppMgrClientTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: LoadAbility Function + * FunctionPoints: AppMgrClient LoadAbility interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke LoadAbility works. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_001, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_001 start"); + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + + AbilityInfo abilityInfo; + ApplicationInfo appInfo; + + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), LoadAbility(_, _, _, _)).Times(1); + + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->LoadAbility(token_, preToken_, abilityInfo, appInfo)); + APP_LOGI("ams_app_mgr_client_test_001 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: LoadAbility Function + * FunctionPoints: AppMgrClient LoadAbility interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke LoadAbility act normal without connect to service. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_002, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_002 start"); + AbilityInfo abilityInfo; + ApplicationInfo appInfo; + EXPECT_EQ( + AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED, client_->LoadAbility(token_, preToken_, abilityInfo, appInfo)); + APP_LOGI("ams_app_mgr_client_test_002 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: TerminateAbility Function + * FunctionPoints: AppMgrClient TerminateAbility interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke TerminateAbility works. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_003, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_003 start"); + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), TerminateAbility(_)).Times(1); + + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->TerminateAbility(token_)); + APP_LOGI("ams_app_mgr_client_test_003 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: TerminateAbility Function + * FunctionPoints: AppMgrClient TerminateAbility interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke TerminateAbility act normal without connect to service. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_004, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_004 start"); + EXPECT_EQ(AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED, client_->TerminateAbility(token_)); + APP_LOGI("ams_app_mgr_client_test_004 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: UpdateAbilityState Function + * FunctionPoints: AppMgrClient UpdateAbilityState interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke UpdateAbilityState works. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_005, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_005 start"); + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), UpdateAbilityState(_, _)).Times(1); + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + + AbilityState state = AbilityState::ABILITY_STATE_BEGIN; + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->UpdateAbilityState(token_, state)); + APP_LOGI("ams_app_mgr_client_test_005 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: UpdateAbilityState Function + * FunctionPoints: AppMgrClient UpdateAbilityState interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke UpdateAbilityState act normal without connect to service. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_006, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_006 start"); + AbilityState state = AbilityState::ABILITY_STATE_BEGIN; + EXPECT_EQ(AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED, client_->UpdateAbilityState(token_, state)); + APP_LOGI("ams_app_mgr_client_test_006 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: RegisterAppStateCallback Function + * FunctionPoints: AppMgrClient RegisterAppStateCallback interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke RegisterAppStateCallback works. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_007, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_007 start"); + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + sptr mockCallback(new MockAppStateCallback()); + sptr callback = iface_cast(mockCallback); + + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(1); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(1); + + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->RegisterAppStateCallback(callback)); + APP_LOGI("ams_app_mgr_client_test_007 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient + * SubFunction: RegisterAppStateCallback Function + * FunctionPoints: AppMgrClient RegisterAppStateCallback interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrClient invoke RegisterAppStateCallback act normal without connect to service. + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_008, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_008 start"); + sptr callback; + EXPECT_EQ(AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED, client_->RegisterAppStateCallback(callback)); + APP_LOGI("ams_app_mgr_client_test_008 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient::AbilityBehaviorAnalysis + * SubFunction: RegisterAppStateCallback Function + * FunctionPoints: AppMgrClient AbilityBehaviorAnalysis interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: ability behavior notification + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_009, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_008 start"); + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + sptr token; + sptr preToken; + + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL( + *(static_cast(amsMgrScheduler.GetRefPtr())), AbilityBehaviorAnalysis(_, _, _, _, _)) + .Times(1); + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->AbilityBehaviorAnalysis(token, preToken, 1, 1, 1)); + APP_LOGI("ams_app_mgr_client_test_008 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient::KillApplication + * SubFunction: RegisterAppStateCallback Function + * FunctionPoints: AppMgrClient KillApplication interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Notify app of death + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_010, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_008 start"); + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + sptr token; + sptr preToken; + + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), KillApplication(_)) + .Times(1) + .WillOnce(Return(ERR_OK)); + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->KillApplication("")); + APP_LOGI("ams_app_mgr_client_test_008 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient::KillApplication + * SubFunction: RegisterAppStateCallback Function + * FunctionPoints: AppMgrClient KillApplication interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Notify app of death + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_011, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_011 start"); + sptr token; + sptr preToken; + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), KillApplication(_)) + .Times(1) + .WillOnce(Return(ERR_NO_MEMORY)); + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + + EXPECT_EQ(AppMgrResultCode::ERROR_SERVICE_NOT_READY, client_->KillApplication("")); + APP_LOGI("ams_app_mgr_client_test_011 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient::KillProcessByAbilityToken + * SubFunction: RegisterAppStateCallback Function + * FunctionPoints: AppMgrClient KillApplication interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Notify app of death + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_012, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_012 start"); + sptr token; + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), KillProcessByAbilityToken(_)) + .Times(1); + + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(amsMgrScheduler)); + + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->KillProcessByAbilityToken(token)); + APP_LOGI("ams_app_mgr_client_test_012 end"); +} + +/* + * Feature: AppMgrService + * Function: AppMgrClient::KillProcessByAbilityToken + * SubFunction: RegisterAppStateCallback Function + * FunctionPoints: AppMgrClient KillApplication interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Notify app of death + */ +HWTEST_F(AmsAppMgrClientTest, AppMgrClient_013, TestSize.Level1) +{ + APP_LOGI("ams_app_mgr_client_test_013 start"); + sptr token; + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->ConnectAppMgrService()); + sptr amsMgrScheduler(new MockAmsMgrScheduler()); + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), KillProcessByAbilityToken(_)) + .Times(0); + + EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) + .Times(1) + .WillOnce(Return(nullptr)); + + EXPECT_EQ(AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED, client_->KillProcessByAbilityToken(token)); + APP_LOGI("ams_app_mgr_client_test_013 end"); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6e6552887d6f3a3f1f85dc12b0e52929932cd4ae --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsAppRunningRecordTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/test/mock/src/mock_bundle_manager.cpp", + ] + + sources += [ "ams_app_running_record_test.cpp" ] + + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/services/appmgr:libams", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsAppRunningRecordTest" ] +} diff --git a/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp b/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..514a4c646e667b2f1649ead84a27b359490990f9 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp @@ -0,0 +1,1421 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_mgr_service_inner.h" +#undef private + +#include +#include +#include "iremote_object.h" +#include "refbase.h" +#include "application_info.h" +#include "app_log_wrapper.h" +#include "app_record_id.h" +#include "app_scheduler_host.h" +#include "ability_info.h" +#include "ability_running_record.h" +#include "mock_app_scheduler.h" +#include "mock_ability_token.h" +#include "mock_app_spawn_client.h" +#include "mock_app_mgr_service_inner.h" +#include "mock_iapp_state_callback.h" +#include "mock_bundle_manager.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; +namespace OHOS { +namespace AppExecFwk { +class AmsAppRunningRecordTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + static const std::string GetTestProcessName() + { + return "com.ohos.test.helloworld"; + } + static const std::string GetTestAppName() + { + return "com.ohos.test.helloworld"; + } + static const std::string GetTestAbilityName() + { + return "test_ability_name"; + } + static int GetTestUid() + { + // a valid inner uid value which is not border value. + const static int VALID_UID_VALUE = 1010; + return VALID_UID_VALUE; + } + + std::shared_ptr GetTestAppRunningRecord(); + sptr GetMockedAppSchedulerClient() const; + std::shared_ptr StartLoadAbility(const sptr &token, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const pid_t newPid) const; + sptr GetMockToken() const + { + return mock_token_; + } + +protected: + std::shared_ptr testAbilityRecord_; + sptr client_; + sptr mockAppSchedulerClient_; + std::shared_ptr testAppRecord_; + std::unique_ptr service_; + sptr mock_token_; + sptr mockBundleMgr; +}; + +void AmsAppRunningRecordTest::SetUpTestCase() +{} + +void AmsAppRunningRecordTest::TearDownTestCase() +{} + +void AmsAppRunningRecordTest::SetUp() +{ + mockAppSchedulerClient_ = new (std::nothrow) MockAppScheduler(); + service_.reset(new (std::nothrow) AppMgrServiceInner()); + mock_token_ = new (std::nothrow) MockAbilityToken(); + client_ = iface_cast(mockAppSchedulerClient_.GetRefPtr()); + mockBundleMgr = new (std::nothrow) BundleMgrService(); + service_->SetBundleManager(mockBundleMgr); +} + +void AmsAppRunningRecordTest::TearDown() +{ + testAbilityRecord_.reset(); + testAppRecord_.reset(); +} + +sptr AmsAppRunningRecordTest::GetMockedAppSchedulerClient() const +{ + if (client_) { + return client_; + } + return nullptr; +} + +std::shared_ptr AmsAppRunningRecordTest::GetTestAppRunningRecord() +{ + if (!testAppRecord_) { + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + testAppRecord_ = std::make_shared(appInfo, AppRecordId::Create(), GetTestProcessName()); + testAppRecord_->SetApplicationClient(GetMockedAppSchedulerClient()); + } + return testAppRecord_; +} + +std::shared_ptr AmsAppRunningRecordTest::StartLoadAbility(const sptr &token, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const pid_t newPid) const +{ + std::shared_ptr mockClientPtr = std::make_shared(); + service_->SetAppSpawnClient(mockClientPtr); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(newPid), Return(ERR_OK))); + + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestProcessName(), appInfo->uid, bundleInfo); + + EXPECT_TRUE(record); + auto clent = GetMockedAppSchedulerClient(); + record->SetApplicationClient(clent); + EXPECT_EQ(record->GetPriorityObject()->GetPid(), newPid); + EXPECT_NE(record->GetApplicationClient(), nullptr); + return record; +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Create using correct args with app/ability not exists. + * EnvConditions: NA + * CaseDescription: Call CreateAppRunningRecord to get result. + */ +HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + EXPECT_EQ(record->GetName(), GetTestAppName()); + + EXPECT_EQ(record->GetProcessName(), GetTestProcessName()); + + auto abilityRecord = record->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_TRUE(abilityRecord != nullptr); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints Create using correct args with app/ability exists. + * EnvConditions: NA + * CaseDescription: Call CreateAppRunningRecord twice to create/get a AppRunningRecord. + */ +HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_002, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + abilityInfo->applicationInfo.uid = 1010; + appInfo->uid = 1010; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + // Create + sptr token = GetMockToken(); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + record->SetUid(1010); + // Get + auto record1 = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + EXPECT_TRUE(record1 != nullptr); + EXPECT_EQ(record1->GetName(), GetTestAppName()); + EXPECT_EQ(record1->GetProcessName(), GetTestProcessName()); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Create using correct args with app exists but ability not. + * EnvConditions: NA + * CaseDescription: Call CreateAppRunningRecord twice which second call uses a different ability info. + */ +HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_003, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + abilityInfo->applicationInfo.uid = 1010; + appInfo->uid = 1010; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + record->SetUid(1010); + + auto anotherAbilityInfo = std::make_shared(); + anotherAbilityInfo->name = "Another_ability"; + anotherAbilityInfo->applicationInfo.uid = 1010; + sptr anotherToken = new (std::nothrow) MockAbilityToken(); + auto record1 = service_->CreateAppRunningRecord( + GetMockToken(), anotherToken, appInfo, anotherAbilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + EXPECT_EQ(record1->GetName(), GetTestAppName()); + EXPECT_EQ(record1->GetProcessName(), GetTestProcessName()); + + auto abilityRecord = record1->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_TRUE(abilityRecord != nullptr); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Create using empty appInfo. + * EnvConditions: NA + * CaseDescription: Call CreateAppRunningRecord using empty appInfo. + */ +HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_004, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + // Create + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, nullptr, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + EXPECT_TRUE(record == nullptr); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Create using empty abilityInfo. + * EnvConditions: NA + * CaseDescription: Call CreateAppRunningRecord using empty abilityInfo. + */ +HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_005, TestSize.Level1) +{ + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + // Create + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, nullptr, GetTestProcessName(), bundleInfo, hapModuleInfo); + EXPECT_TRUE(record != nullptr); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Test launch application. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call LaunchApplication. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchApplication_001, TestSize.Level1) +{ + Configuration config; + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + record->LaunchApplication(config); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Test launch ability via AppRunningRecord using valid name. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call LaunchAbility which is exists. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchAbility_001, TestSize.Level1) +{ + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + auto record = GetTestAppRunningRecord(); + EXPECT_TRUE(record); + record->AddModule(appInfo, nullptr, GetMockToken(), hapModuleInfo); + auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRecord = moduleRecord->GetAbilityRunningRecordByToken(GetMockToken()); + EXPECT_EQ(nullptr, abilityRecord); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(0); + record->LaunchAbility(abilityRecord); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Test launch ability via AppRunningRecord using empty name. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call LaunchAbility which is not exists. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchAbility_002, TestSize.Level1) +{ + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + auto record = GetTestAppRunningRecord(); + record->AddModule(appInfo, abilityInfo, GetMockToken(), hapModuleInfo); + auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRecord = moduleRecord->GetAbilityRunningRecordByToken(GetMockToken()); + + EXPECT_TRUE(abilityRecord); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + + record->LaunchAbility(abilityRecord); + + EXPECT_EQ(AbilityState::ABILITY_STATE_READY, abilityRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Schedule application terminate by AppRunningRecord. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call ScheduleTerminate. + */ +HWTEST_F(AmsAppRunningRecordTest, ScheduleTerminate_001, TestSize.Level1) +{ + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleTerminateApplication()).Times(1); + record->ScheduleTerminate(); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Schedule application foreground by AppRunningRecord. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call ScheduleForegroundRunning. + */ +HWTEST_F(AmsAppRunningRecordTest, ScheduleForegroundRunning_001, TestSize.Level1) +{ + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleForegroundApplication()).Times(1); + record->ScheduleForegroundRunning(); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Schedule application background by AppRunningRecord. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call ScheduleBackgroundRunning. + */ +HWTEST_F(AmsAppRunningRecordTest, ScheduleBackgroundRunning_001, TestSize.Level1) +{ + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleBackgroundApplication()).Times(1); + record->ScheduleBackgroundRunning(); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Schedule application trim memory by AppRunningRecord. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call ScheduleTrimMemory. + */ +HWTEST_F(AmsAppRunningRecordTest, ScheduleTrimMemory_001, TestSize.Level1) +{ + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleShrinkMemory(_)).Times(1); + EXPECT_NE(nullptr, record->GetPriorityObject()); + record->ScheduleTrimMemory(); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Test low memory warning notification handling. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call LowMemoryWarning. + */ +HWTEST_F(AmsAppRunningRecordTest, LowMemoryWarning_001, TestSize.Level1) +{ + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLowMemory()).Times(1); + record->LowMemoryWarning(); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Update application state using correct args. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call SetState in a for-each cycle. + */ +HWTEST_F(AmsAppRunningRecordTest, UpdateAppRunningRecord_001, TestSize.Level1) +{ + auto record = GetTestAppRunningRecord(); + for (ApplicationState state = ApplicationState::APP_STATE_BEGIN; state < ApplicationState::APP_STATE_END; + state = (ApplicationState)(static_cast::type>(state) + 1)) { + record->SetState(state); + EXPECT_EQ(record->GetState(), state); + } +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Update application state using wrong args. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call SetState using arg |APP_STATE_END|. + */ +HWTEST_F(AmsAppRunningRecordTest, UpdateAppRunningRecord_002, TestSize.Level1) +{ + auto record = GetTestAppRunningRecord(); + record->SetState(ApplicationState::APP_STATE_END); + EXPECT_NE(record->GetState(), ApplicationState::APP_STATE_END); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: Delete application record info when application terminated. + * EnvConditions: NA + * CaseDescription: Create an AppRunningRecord and call AppMgrService::ApplicationTerminated passing exists + |RecordId|. + */ +HWTEST_F(AmsAppRunningRecordTest, DeleteAppRunningRecord_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + EXPECT_TRUE(record != nullptr); + record->SetState(ApplicationState::APP_STATE_BACKGROUND); + record->SetApplicationClient(GetMockedAppSchedulerClient()); + service_->ApplicationTerminated(record->GetRecordId()); + record = service_->GetAppRunningRecordByAppRecordId(record->GetRecordId()); + EXPECT_TRUE(record == nullptr); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server received attachApplication request. + * EnvConditions: NA + * CaseDescription: Test server received normal pid attachApplication request. + */ +HWTEST_F(AmsAppRunningRecordTest, AttachApplication_001, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest AttachApplication_001 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + sptr token = GetMockToken(); + + const pid_t newPid = 1234; + EXPECT_TRUE(service_); + auto record = StartLoadAbility(token, abilityInfo, appInfo, newPid); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + service_->AttachApplication(newPid, mockAppSchedulerClient_); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + APP_LOGI("AmsAppRunningRecordTest AttachApplication_001 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server received attachApplication request. + * EnvConditions: NA + * CaseDescription: Test server received invalid pid attachApplication request. + */ +HWTEST_F(AmsAppRunningRecordTest, AttachApplication_002, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest AttachApplication_002 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + sptr token = GetMockToken(); + EXPECT_TRUE(service_ != nullptr); + const pid_t newPid = 1234; + const pid_t invalidPid = -1; + auto record = StartLoadAbility(token, abilityInfo, appInfo, newPid); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(0); + service_->AttachApplication(invalidPid, GetMockedAppSchedulerClient()); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + APP_LOGI("AmsAppRunningRecordTest AttachApplication_002 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server received attachApplication request. + * EnvConditions: NA + * CaseDescription: Test server received non-exist pid attachApplication request. + */ +HWTEST_F(AmsAppRunningRecordTest, AttachApplication_003, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest AttachApplication_003 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + sptr token = GetMockToken(); + EXPECT_TRUE(service_ != nullptr); + const pid_t newPid = 1234; + const pid_t anotherPid = 1000; + auto record = StartLoadAbility(token, abilityInfo, appInfo, newPid); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(0); + service_->AttachApplication(anotherPid, GetMockedAppSchedulerClient()); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + APP_LOGI("AmsAppRunningRecordTest AttachApplication_003 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server received attachApplication request. + * EnvConditions: NA + * CaseDescription: Test server received null appClient attachApplication request. + */ +HWTEST_F(AmsAppRunningRecordTest, AttachApplication_004, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest AttachApplication_004 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + sptr token = GetMockToken(); + EXPECT_TRUE(service_ != nullptr); + const pid_t newPid = 1234; + auto record = StartLoadAbility(token, abilityInfo, appInfo, newPid); + service_->AttachApplication(newPid, nullptr); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + APP_LOGI("AmsAppRunningRecordTest AttachApplication_004 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server received attachApplication request. + * EnvConditions: NA + * CaseDescription: Test server received multiple same attachApplication request. + */ +HWTEST_F(AmsAppRunningRecordTest, AttachApplication_005, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest AttachApplication_005 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + sptr token = GetMockToken(); + const pid_t newPid = 1234; + EXPECT_TRUE(service_ != nullptr); + auto record = StartLoadAbility(token, abilityInfo, appInfo, newPid); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + service_->AttachApplication(newPid, GetMockedAppSchedulerClient()); + EXPECT_NE(record->GetApplicationClient(), nullptr); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(0); + service_->AttachApplication(newPid, GetMockedAppSchedulerClient()); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + APP_LOGI("AmsAppRunningRecordTest AttachApplication_005 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server received attachApplication request. + * EnvConditions: NA + * CaseDescription: Test server received attachApplication request after multiple loadAbility. + */ +HWTEST_F(AmsAppRunningRecordTest, AttachApplication_006, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest AttachApplication_006 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->process = GetTestAppName(); + + auto abilityInfo3 = std::make_shared(); + abilityInfo3->name = GetTestAbilityName() + "_2"; + abilityInfo3->applicationName = GetTestAppName(); + abilityInfo3->process = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + sptr token = GetMockToken(); + const uint32_t EXPECT_RECORD_SIZE = 3; + const int EXPECT_ABILITY_LAUNCH_TIME = 3; + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + auto record = StartLoadAbility(token, abilityInfo, appInfo, PID); + + sptr token2 = new (std::nothrow) MockAbilityToken(); + service_->LoadAbility(token2, nullptr, abilityInfo2, appInfo); + sptr token3 = new (std::nothrow) MockAbilityToken(); + service_->LoadAbility(token3, nullptr, abilityInfo3, appInfo); + EXPECT_EQ(record->GetAbilities().size(), EXPECT_RECORD_SIZE); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); + service_->AttachApplication(PID, mockAppSchedulerClient_); + EXPECT_NE(record->GetApplicationClient(), nullptr); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + APP_LOGI("AmsAppRunningRecordTest AttachApplication_006 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server LaunchApplication and LaunchAbility. + * EnvConditions: NA + * CaseDescription: Test normal case of LaunchAbility after LaunchApplication. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_001, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_001 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + EXPECT_TRUE(service_ != nullptr); + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + record->SetApplicationClient(GetMockedAppSchedulerClient()); + service_->LaunchApplication(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_001 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server LaunchApplication and LaunchAbility. + * EnvConditions: NA + * CaseDescription: Test normal case of multiple LaunchAbility after LaunchApplication. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_002, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_002 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + auto abilityInfo3 = std::make_shared(); + abilityInfo3->name = GetTestAbilityName() + "_2"; + abilityInfo3->applicationName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + const int EXPECT_ABILITY_LAUNCH_TIME = 3; + EXPECT_TRUE(service_ != nullptr); + + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + auto abilityRecord2 = moduleRecord->GetAbilityRunningRecordByToken(token2); + EXPECT_TRUE(abilityRecord2 != nullptr); + + sptr token3 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo3, token3, hapModuleInfo); + auto moduleRecord3 = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord3); + auto abilityRecord3 = moduleRecord3->GetAbilityRunningRecordByToken(token3); + EXPECT_TRUE(abilityRecord3 != nullptr); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); + record->SetApplicationClient(GetMockedAppSchedulerClient()); + service_->LaunchApplication(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_002 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server LaunchApplication and LaunchAbility. + * EnvConditions: NA + * CaseDescription: Test abnormal case of LaunchApplication with wrong state. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_003, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_003 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + record->SetState(ApplicationState::APP_STATE_READY); + record->SetApplicationClient(GetMockedAppSchedulerClient()); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(0); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(0); + service_->LaunchApplication(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_003 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server LaunchApplication and LaunchAbility. + * EnvConditions: NA + * CaseDescription: Test normal case of LoadAbility after LaunchAbility and LaunchApplication. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_004, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_004 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->process = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + record->SetApplicationClient(GetMockedAppSchedulerClient()); + service_->LaunchApplication(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(0); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + sptr token2 = new (std::nothrow) MockAbilityToken(); + service_->LoadAbility(token2, nullptr, abilityInfo2, appInfo); + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_004 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: NA + * FunctionPoints: When server LaunchApplication and LaunchAbility. + * EnvConditions: NA + * CaseDescription: Test normal case of multiple LaunchAbility with wrong state after LaunchApplication. + */ +HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_005, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_005 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + auto abilityInfo3 = std::make_shared(); + abilityInfo3->name = GetTestAbilityName() + "_2"; + abilityInfo3->applicationName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + const int EXPECT_ABILITY_LAUNCH_TIME = 2; + EXPECT_TRUE(service_ != nullptr); + + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + auto moduleRecord2 = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord2); + auto abilityRecord2 = moduleRecord2->GetAbilityRunningRecordByToken(token2); + abilityRecord2->SetState(AbilityState::ABILITY_STATE_READY); + + sptr token3 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo3, token3, hapModuleInfo); + auto moduleRecord3 = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord3); + auto abilityRecord3 = moduleRecord3->GetAbilityRunningRecordByToken(token3); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); + record->SetApplicationClient(GetMockedAppSchedulerClient()); + service_->LaunchApplication(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); + APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_005 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: TerminateAbility + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify the function TerminateAbility can check the token which not added. + */ +HWTEST_F(AmsAppRunningRecordTest, TerminateAbility_001, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest TerminateAbility_001 start"); + + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleCleanAbility(_)).Times(0); + record->TerminateAbility(GetMockToken(), false); + + APP_LOGI("AmsAppRunningRecordTest TerminateAbility_001 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: TerminateAbility + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify the function TerminateAbility can check the state not in background. + */ +HWTEST_F(AmsAppRunningRecordTest, TerminateAbility_002, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest TerminateAbility_002 start"); + + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleCleanAbility(_)).Times(0); + record->TerminateAbility(GetMockToken(), false); + + APP_LOGI("AmsAppRunningRecordTest TerminateAbility_002 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: AbilityTerminated + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify the function AbilityTerminated can check the token is nullptr. + */ +HWTEST_F(AmsAppRunningRecordTest, AbilityTerminated_001, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest AbilityTerminated_001 start"); + + auto record = GetTestAppRunningRecord(); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleTerminateApplication()).Times(0); + record->AbilityTerminated(nullptr); + + APP_LOGI("AmsAppRunningRecordTest AbilityTerminated_001 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: GetAbilityRunningRecord + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify the function GetAbilityRunningRecord return nullptr when the ability doesn't added. + */ +HWTEST_F(AmsAppRunningRecordTest, GetAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest GetAbilityRunningRecord_001 start"); + + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + std::string abilityName = "not_exist_ability_name"; + EXPECT_EQ(nullptr, record->GetAbilityRunningRecord(abilityName)); + + APP_LOGI("AmsAppRunningRecordTest GetAbilityRunningRecord_001 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord + * SubFunction: GetAbilityRunningRecordByToken + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify the function GetAbilityRunningRecordByToken can check token is nullptr. + */ +HWTEST_F(AmsAppRunningRecordTest, GetAbilityRunningRecordByToken_001, TestSize.Level1) +{ + APP_LOGI("AmsAppRunningRecordTest GetAbilityRunningRecordByToken_001 start"); + + auto record = GetTestAppRunningRecord(); + EXPECT_EQ(nullptr, record->GetAbilityRunningRecordByToken(nullptr)); + + APP_LOGI("AmsAppRunningRecordTest GetAbilityRunningRecordByToken_001 end"); +} + +/* + * Feature: AMS + * Function: AppRunningRecord::SetUid, AppRunningRecord::GetUid() + * SubFunction: GetAbilityRunningRecordByToken + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify the function GetAbilityRunningRecordByToken can check token is nullptr. + */ + +HWTEST_F(AmsAppRunningRecordTest, SetUid_GetUid_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + bundleInfo.jointUserId = "joint456"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + record->SetUid(102); + + auto otherRecord = service_->GetAppRunningRecordByAppRecordId(record->GetRecordId()); + EXPECT_TRUE(record != nullptr); + + EXPECT_EQ(otherRecord->GetUid(), 102); +} + +/* + * Feature: AMS + * Function: OnAbilityStateChanged + * SubFunction: App state switch + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Notify ability when the status of the app changes + */ + +HWTEST_F(AmsAppRunningRecordTest, OnAbilityStateChanged_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + std::shared_ptr record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord != nullptr); + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); + EXPECT_TRUE(abilityRecord != nullptr); + + sptr callback = new (std::nothrow) MockAppStateCallback(); + EXPECT_CALL(*callback, OnAbilityRequestDone(_, _)).Times(0); + + moduleRecord->OnAbilityStateChanged(nullptr, AbilityState::ABILITY_STATE_FOREGROUND); + + EXPECT_NE(AbilityState::ABILITY_STATE_FOREGROUND, abilityRecord->GetState()); + + std::shared_ptr serviceInner; + serviceInner.reset(new (std::nothrow) AppMgrServiceInner()); + EXPECT_TRUE(serviceInner); + + EXPECT_CALL(*callback, OnAbilityRequestDone(_, _)).Times(2); + serviceInner->RegisterAppStateCallback(callback); + record->SetAppMgrServiceInner(serviceInner); + + moduleRecord->OnAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, abilityRecord->GetState()); + + moduleRecord->OnAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, abilityRecord->GetState()); +} + +/* + * Feature: AMS + * Function: AddModule + * SubFunction: AddModule + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: add module + */ + +HWTEST_F(AmsAppRunningRecordTest, AddModule_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + + auto moduleRecordList = record->GetAllModuleRecord(); + EXPECT_TRUE(moduleRecordList.size() == 1); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + HapModuleInfo hapModuleInfo1; + hapModuleInfo1.moduleName = "module123"; + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + + moduleRecordList = record->GetAllModuleRecord(); + EXPECT_TRUE(moduleRecordList.size() == 2); +} + +/* + * Feature: AMS + * Function: AddModule + * SubFunction: AddModule + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: add module + */ + +HWTEST_F(AmsAppRunningRecordTest, AddModule_002, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + + auto moduleRecordList = record->GetAllModuleRecord(); + EXPECT_TRUE(moduleRecordList.size() == 1); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + + moduleRecordList = record->GetAllModuleRecord(); + EXPECT_TRUE(moduleRecordList.size() == 1); +} + +/* + * Feature: AMS + * Function: GetModuleRecordByModuleName + * SubFunction: GetModuleRecordByModuleName + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Get ModuleRecord By ModuleName + */ + +HWTEST_F(AmsAppRunningRecordTest, GetModuleRecordByModuleName_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + HapModuleInfo hapModuleInfo1; + hapModuleInfo1.moduleName = "module123"; + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + + auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); +} + +/* + * Feature: AMS + * Function: GetAbilities + * SubFunction: GetAbilities + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Get All Abilities + */ + +HWTEST_F(AmsAppRunningRecordTest, GetAbilities_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + + auto abilities = record->GetAbilities(); + EXPECT_TRUE(abilities.size() == 2); +} + +/* + * Feature: AMS + * Function: GetAbilities + * SubFunction: GetAbilities + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Get All Abilities + */ + +HWTEST_F(AmsAppRunningRecordTest, GetAbilities_002, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + HapModuleInfo hapModuleInfo1; + hapModuleInfo1.moduleName = "module123"; + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + + auto abilities = record->GetAbilities(); + EXPECT_TRUE(abilities.size() == 2); +} + +/* + * Feature: AMS + * Function: RemoveModuleRecord + * SubFunction: RemoveModuleRecord + * FunctionPoints: check params + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Remove ModuleRecord + */ + +HWTEST_F(AmsAppRunningRecordTest, RemoveModuleRecord_001, TestSize.Level1) +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + EXPECT_TRUE(service_ != nullptr); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + + EXPECT_TRUE(record != nullptr); + + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + HapModuleInfo hapModuleInfo1; + hapModuleInfo1.moduleName = "module123"; + sptr token2 = new (std::nothrow) MockAbilityToken(); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + + auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord); + + record->RemoveModuleRecord(moduleRecord); + auto moduleRecordList = record->GetAllModuleRecord(); + EXPECT_TRUE(moduleRecordList.size() == 1); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/tools/zip/test/BUILD.gn b/services/appmgr/test/unittest/ams_app_state_callback_test/BUILD.gn similarity index 45% rename from tools/zip/test/BUILD.gn rename to services/appmgr/test/unittest/ams_app_state_callback_test/BUILD.gn index ecf094372d32f5a06cab413330430c2e59c7eaf8..58044684b0691f6f611bd1e61a5c08b7e29fd1e4 100644 --- a/tools/zip/test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_state_callback_test/BUILD.gn @@ -12,54 +12,44 @@ # limitations under the License. import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/tools_test" +module_output_path = "ability_runtime/appmgrservice" -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [] - cflags = [] - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } - defines = [ - "APP_LOG_TAG = \"ZipUnitTest\"", - "LOG_DOMAIN = 0xD002201", - ] -} - -ohos_unittest("zip_test") { +ohos_unittest("AmsAppStateCallbackTest") { module_out_path = module_output_path - include_dirs = [ "//foundation/aafwk/standard/tools/zip/include" ] + include_dirs = [ + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + sources = [ - "//foundation/aafwk/standard/tools/zip/src/file_path.cpp", - "//foundation/aafwk/standard/tools/zip/src/zip.cpp", - "//foundation/aafwk/standard/tools/zip/src/zip_internal.cpp", - "//foundation/aafwk/standard/tools/zip/src/zip_reader.cpp", - "//foundation/aafwk/standard/tools/zip/src/zip_utils.cpp", - "//foundation/aafwk/standard/tools/zip/src/zip_writer.cpp", - "//foundation/aafwk/standard/tools/zip/test/unittest/zip_test.cpp", + "${aafwk_path}/interfaces/innerkits//app_manager/src/appmgr/app_process_data.cpp", + "${aafwk_path}/interfaces/innerkits//app_manager/src/appmgr/app_state_callback_host.cpp", ] + sources += [ "ams_app_state_callback_test.cpp" ] + configs = [ - "//foundation/aafwk/standard/tools/zip:zip_config", - ":module_private_config", + "//utils/native/base:utils_config", + "${services_path}/appmgr/test:appmgr_test_config", ] - + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } deps = [ - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/common:libappexecfwk_common", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", - "//third_party/libuv:uv_static", - "//third_party/zlib:libz", - "//utils/native/base:utils", "//utils/native/base:utils", ] external_deps = [ + "bytrace_standard:bytrace_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -67,7 +57,6 @@ ohos_unittest("zip_test") { group("unittest") { testonly = true - deps = [] - deps += [ ":zip_test" ] + deps = [ ":AmsAppStateCallbackTest" ] } diff --git a/services/appmgr/test/unittest/ams_app_state_callback_test/ams_app_state_callback_test.cpp b/services/appmgr/test/unittest/ams_app_state_callback_test/ams_app_state_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..231ad9df5bbf06928661ec81183c03e75e5aeba6 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_state_callback_test/ams_app_state_callback_test.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_state_callback_host.h" +#include +#include "app_mgr_constants.h" +#include "iapp_state_callback.h" +#include "app_process_data.h" +#include "mock_ability_token.h" + +using namespace testing::ext; +namespace OHOS { +namespace AppExecFwk { +class AmsAppStateCallBackTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsAppStateCallBackTest::SetUpTestCase() +{} +void AmsAppStateCallBackTest::TearDownTestCase() +{} +void AmsAppStateCallBackTest::SetUp() +{} +void AmsAppStateCallBackTest::TearDown() +{} + +/* + * Feature: AppStateCallBackHost + * Function: AppStateCallBackHost + * SubFunction: OnRemoteRequest Function + * FunctionPoints: AppStateCallBackHost Onreceived interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if Onreceived works when app state changed. + */ +HWTEST_F(AmsAppStateCallBackTest, OnRemoteRequest_001, TestSize.Level1) +{ + sptr host(new AppStateCallbackHost()); + MessageParcel data; + MessageParcel reply; + MessageOption option {MessageOption::TF_ASYNC}; + + AppData appDataInfo; + AppProcessData processData; + appDataInfo.appName = "test_name"; + appDataInfo.uid = 2; + processData.appDatas.emplace_back(appDataInfo); + processData.pid = 1; + processData.appState = ApplicationState::APP_STATE_FOREGROUND; + data.WriteParcelable(&processData); + int32_t ret = 0; + EXPECT_EQ(0, ret); +} + +/* + * Feature: AppStateCallBackHost + * Function: AppStateCallBackHost + * SubFunction: OnRemoteRequest Function + * FunctionPoints: AppStateCallBackHost Onreceived interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if Onreceived works when ability request done. + */ +HWTEST_F(AmsAppStateCallBackTest, OnRemoteRequest_002, TestSize.Level1) +{ + sptr host(new AppStateCallbackHost()); + MessageParcel data; + MessageParcel reply; + MessageOption option{MessageOption::TF_ASYNC}; + sptr token = new MockAbilityToken(); + + data.WriteParcelable(token.GetRefPtr()); + int32_t abilityState = static_cast(AbilityState::ABILITY_STATE_FOREGROUND); + data.WriteInt32(abilityState); + int32_t ret = 0; + EXPECT_EQ(0, ret); +} + +/* +* Feature: AppProcessData +* Function: AppProcessData +* SubFunction: Marshalling and Unmarshalling +* FunctionPoints: Marshalling and Unmarshalling can work normal +* EnvConditions: Mobile that can run normal +* CaseDescription: 1. Verify process data can write to parcel. + 2. verify process data can read from parcel. +*/ +HWTEST_F(AmsAppStateCallBackTest, AppProcessData_001, TestSize.Level1) +{ + Parcel data; + AppData appDataInfo; + AppProcessData processData; + appDataInfo.appName = "test_name"; + appDataInfo.uid = 2; + processData.appDatas.emplace_back(appDataInfo); + processData.pid = 1; + processData.appState = ApplicationState::APP_STATE_FOREGROUND; + + bool ret = processData.Marshalling(data); + EXPECT_EQ(true, ret); + + sptr newProcessData = AppProcessData::Unmarshalling(data); + EXPECT_NE(nullptr, newProcessData); + + for (auto i = 0; i < processData.appDatas.size(); i++) { + EXPECT_EQ(processData.appDatas[i].appName, newProcessData->appDatas[i].appName); + EXPECT_EQ(processData.appDatas[i].uid, newProcessData->appDatas[i].uid); + } + + EXPECT_EQ(processData.pid, newProcessData->pid); + EXPECT_EQ(processData.appState, newProcessData->appState); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a8a0c8d1f3e98ce470ff850b4163c0b3939b7664 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsWorkFlowTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_lifecycle_deal.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_process_manager.cpp", + "${services_path}/appmgr/src/app_running_manager.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/src/cgroup_manager.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/module_running_record.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + "${services_path}/appmgr/src/process_optimizer_uba.cpp", + "${services_path}/appmgr/src/remote_client_manager.cpp", + ] + + sources += [ "ams_workflow_test.cpp" ] + + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsWorkFlowTest" ] +} diff --git a/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2de9fbac7a50b682653d3da83df16d36fb7bbf0 --- /dev/null +++ b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp @@ -0,0 +1,906 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_mgr_service_inner.h" +#undef private +#include +#include +#include "iremote_object.h" +#include "refbase.h" +#include "app_launch_data.h" +#include "app_log_wrapper.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; +namespace OHOS { +namespace AppExecFwk { +struct TestApplicationPreRecord { + TestApplicationPreRecord( + const std::shared_ptr &appRecord, const sptr &mockAppScheduler) + : appRecord_(appRecord), mockAppScheduler_(mockAppScheduler) + {} + + std::shared_ptr GetAbility(const sptr &token) const + { + return appRecord_->GetAbilityRunningRecordByToken(token); + } + + virtual ~TestApplicationPreRecord() + {} + + std::shared_ptr appRecord_; + sptr mockAppScheduler_; +}; + +pid_t g_mockPid = 0; +class AmsWorkFlowTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr CreateAbilityInfo(const std::string &ability, const std::string &app) const; + std::shared_ptr CreateApplication(const std::string &app) const; + sptr AddApplicationClient(const std::shared_ptr &appRecord) const; + TestApplicationPreRecord CreateTestApplicationRecord(const std::string &ability, const sptr &token, + const std::string &app, const AbilityState abilityState, const ApplicationState appState) const; + +protected: + std::shared_ptr serviceInner_; + std::shared_ptr handler_ = nullptr; +}; + +void AmsWorkFlowTest::SetUpTestCase() +{} + +void AmsWorkFlowTest::TearDownTestCase() +{} + +void AmsWorkFlowTest::SetUp() +{ + serviceInner_ = std::make_unique(); + auto runner = EventRunner::Create("AmsWorkFlowTest"); + handler_ = std::make_shared(runner, serviceInner_); + serviceInner_->SetEventHandler(handler_); +} + +void AmsWorkFlowTest::TearDown() +{ + g_mockPid = 0; +} + +std::shared_ptr AmsWorkFlowTest::CreateAbilityInfo( + const std::string &ability, const std::string &app) const +{ + auto abilityInfo = std::make_shared(); + abilityInfo->visible = true; + abilityInfo->name = "test_ability" + ability; + abilityInfo->applicationName = "test_app" + app; + abilityInfo->applicationInfo.bundleName = "test_app" + app; + + return abilityInfo; +} + +std::shared_ptr AmsWorkFlowTest::CreateApplication(const std::string &app) const +{ + auto appInfo = std::make_shared(); + appInfo->name = "test_app" + app; + appInfo->bundleName = "test_app" + app; + + return appInfo; +} + +sptr AmsWorkFlowTest::AddApplicationClient(const std::shared_ptr &appRecord) const +{ + if (appRecord->GetApplicationClient()) { + return nullptr; + } + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + return mockAppScheduler; +} + +// create one application that include one ability, and set state +TestApplicationPreRecord AmsWorkFlowTest::CreateTestApplicationRecord(const std::string &ability, + const sptr &token, const std::string &app, const AbilityState abilityState, + const ApplicationState appState) const +{ + auto abilityInfo = CreateAbilityInfo(ability, app); + auto appInfo = CreateApplication(app); + abilityInfo->applicationInfo.uid = 0; + appInfo->uid = 0; + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, appInfo->uid, bundleInfo); + if (!appRecord) { + appRecord = serviceInner_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, appInfo->name, bundleInfo, hapModuleInfo); + serviceInner_->StartProcess(abilityInfo->applicationName, + appInfo->name, + appRecord, + abilityInfo->applicationInfo.uid, + abilityInfo->applicationInfo.bundleName); + } else { + appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + } + + EXPECT_NE(appRecord, nullptr); + appRecord->SetEventHandler(handler_); + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + abilityRecord->SetState(abilityState); + appRecord->SetState(appState); + sptr mockAppScheduler = AddApplicationClient(appRecord); + + TestApplicationPreRecord testAppPreRecord(appRecord, mockAppScheduler); + return testAppPreRecord; +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: BackKey + * CaseDescription: when only one ability on foreground, previous is another app, simulate press back key + */ +HWTEST_F(AmsWorkFlowTest, BackKey_001, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest BackKey_001 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + TestApplicationPreRecord appB = CreateTestApplicationRecord( + "B", tokenB, "B", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*(appB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appB.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appB.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest BackKey_001 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: BackKey + * CaseDescription: when only one ability on foreground, previous ability in same app, simulate press back key + */ +HWTEST_F(AmsWorkFlowTest, BackKey_002, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest BackKey_002 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(0); + + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest BackKey_002 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: BackKey + * CaseDescription: when two ability on foreground, previous ability in another app, simulate press back key + */ +HWTEST_F(AmsWorkFlowTest, BackKey_003, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest BackKey_003 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenC = new MockAbilityToken(); + TestApplicationPreRecord appC = CreateTestApplicationRecord( + "C", tokenC, "C", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*(appC.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenC)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appC.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest BackKey_003 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: BackKey + * CaseDescription: when two ability on foreground, previous is 2 ability in another app, simulate press back key + */ +HWTEST_F(AmsWorkFlowTest, BackKey_004, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest BackKey_004 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenC = new MockAbilityToken(); + TestApplicationPreRecord appC = CreateTestApplicationRecord( + "C", tokenC, "C", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + sptr tokenD = new MockAbilityToken(); + CreateTestApplicationRecord( + "D", tokenD, "C", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*(appC.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenD, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenC)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenD)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appC.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest BackKey_004 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: BackKey + * CaseDescription: when only one ability on foreground, previous is another app, simulate press back key and exit + app + */ +HWTEST_F(AmsWorkFlowTest, BackKey_005, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest BackKey_005 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + sptr tokenB = new MockAbilityToken(); + TestApplicationPreRecord appB = CreateTestApplicationRecord( + "B", tokenB, "B", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + appB.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(appB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(tokenA); + serviceInner_->AbilityTerminated(tokenA); + serviceInner_->ApplicationTerminated(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appB.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appB.appRecord_->GetState()); + EXPECT_EQ(appA.GetAbility(tokenA), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest BackKey_005 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: BackKey + * CaseDescription: when two ability on foreground, previous is another app, simulate press back key and exit + */ +HWTEST_F(AmsWorkFlowTest, BackKey_006, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest BackKey_006 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenC = new MockAbilityToken(); + TestApplicationPreRecord appC = CreateTestApplicationRecord( + "C", tokenC, "C", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + appC.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(appC.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(2); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(tokenA); + serviceInner_->AbilityTerminated(tokenA); + serviceInner_->TerminateAbility(tokenB); + serviceInner_->AbilityTerminated(tokenB); + serviceInner_->ApplicationTerminated(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenC)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appC.appRecord_->GetState()); + EXPECT_EQ(appA.GetAbility(tokenA), nullptr); + EXPECT_EQ(appA.GetAbility(tokenB), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest BackKey_006 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: BackKey + * CaseDescription: when two ability on foreground, previous is 2 abiltiy in another app, + * simulate press back key and exit + */ +HWTEST_F(AmsWorkFlowTest, BackKey_007, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest BackKey_007 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenC = new MockAbilityToken(); + TestApplicationPreRecord appC = CreateTestApplicationRecord( + "C", tokenC, "C", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + appC.appRecord_->LaunchPendingAbilities(); + sptr tokenD = new MockAbilityToken(); + CreateTestApplicationRecord( + "D", tokenD, "C", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*(appC.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(2); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenD, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(tokenA); + serviceInner_->AbilityTerminated(tokenA); + serviceInner_->TerminateAbility(tokenB); + serviceInner_->AbilityTerminated(tokenB); + serviceInner_->ApplicationTerminated(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenC)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenD)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appC.appRecord_->GetState()); + EXPECT_EQ(appA.GetAbility(tokenA), nullptr); + EXPECT_EQ(appA.GetAbility(tokenB), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest BackKey_007 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOff + * CaseDescription: when only one ability on foreground, simulate screenoff + */ +HWTEST_F(AmsWorkFlowTest, ScreenOff_001, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOff_001 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOff_001 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOff + * CaseDescription: when multiple ability on foreground, simulate screenoff + */ +HWTEST_F(AmsWorkFlowTest, ScreenOff_002, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOff_002 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOff_002 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOff + * CaseDescription: when one ability on foreground, another ability in same app is background, simulate screenoff + */ +HWTEST_F(AmsWorkFlowTest, ScreenOff_003, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOff_003 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOff_003 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOff + * CaseDescription: when only one ability on foreground, simulate screenoff and exit + */ +HWTEST_F(AmsWorkFlowTest, ScreenOff_004, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOff_004 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(tokenA); + serviceInner_->AbilityTerminated(tokenA); + serviceInner_->ApplicationTerminated(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(appA.GetAbility(tokenA), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOff_004 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOff + * CaseDescription: when multiple ability on foreground, simulate screenoff and exit + */ +HWTEST_F(AmsWorkFlowTest, ScreenOff_005, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOff_005 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(2); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(tokenA); + serviceInner_->AbilityTerminated(tokenA); + serviceInner_->TerminateAbility(tokenB); + serviceInner_->AbilityTerminated(tokenB); + serviceInner_->ApplicationTerminated(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(appA.GetAbility(tokenA), nullptr); + EXPECT_EQ(appA.GetAbility(tokenB), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOff_005 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOff + * CaseDescription: when one ability on foreground, another ability in same app is background, + * simulate screenoff and exit + */ +HWTEST_F(AmsWorkFlowTest, ScreenOff_006, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOff_006 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_FOREGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(2); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(tokenA); + serviceInner_->AbilityTerminated(tokenA); + serviceInner_->TerminateAbility(tokenB); + serviceInner_->AbilityTerminated(tokenB); + serviceInner_->ApplicationTerminated(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(appA.GetAbility(tokenA), nullptr); + EXPECT_EQ(appA.GetAbility(tokenB), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOff_006 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOn + * CaseDescription: when only one ability on background, simulate screen on + */ +HWTEST_F(AmsWorkFlowTest, ScreenOn_001, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOn_001 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOn_001 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOn + * CaseDescription: when multiple abilities on backgroud, previous is one ability, simulate screen on + */ +HWTEST_F(AmsWorkFlowTest, ScreenOn_002, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOn_002 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOn_002 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ScreenOn + * CaseDescription: when multiple abilities on backgroud, all abilities are previous, simulate screen on + */ +HWTEST_F(AmsWorkFlowTest, ScreenOn_003, TestSize.Level1) +{ + APP_LOGI("AmsWorkFlowTest ScreenOn_003 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appA.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appA.appRecord_->GetState()); + APP_LOGI("AmsWorkFlowTest ScreenOn_003 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ChangeAbility + * CaseDescription: when one ability on foreground, request to load another ability of the same Application + */ +HWTEST_F(AmsWorkFlowTest, ChangeAbility_001, TestSize.Level1) +{ + APP_LOGD("AmsWorkFlowTest ChangeAbility_001 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_FOREGROUND); + + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + + std::shared_ptr abilityA = appA.GetAbility(tokenA); + std::shared_ptr abilityB = appA.GetAbility(tokenB); + EXPECT_EQ(abilityA->GetAbilityInfo()->applicationName, abilityB->GetAbilityInfo()->applicationName); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appA.appRecord_->GetState()); + + auto abilities = appA.appRecord_->GetAbilities(); + EXPECT_NE(nullptr, abilities[tokenA]); + EXPECT_NE(nullptr, abilities[tokenB]); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ChangeAbility + * CaseDescription: when two ability on foreground, request to load another ability of the same Application + */ +HWTEST_F(AmsWorkFlowTest, ChangeAbility_002, TestSize.Level1) +{ + APP_LOGD("AmsWorkFlowTest ChangeAbility_001 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenC = new MockAbilityToken(); + CreateTestApplicationRecord( + "C", tokenC, "A", AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_FOREGROUND); + + serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + + std::shared_ptr abilityA = appA.GetAbility(tokenA); + std::shared_ptr abilityB = appA.GetAbility(tokenB); + std::shared_ptr abilityC = appA.GetAbility(tokenC); + EXPECT_EQ(abilityA->GetAbilityInfo()->applicationName, abilityB->GetAbilityInfo()->applicationName); + EXPECT_EQ(abilityC->GetAbilityInfo()->applicationName, abilityB->GetAbilityInfo()->applicationName); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenC)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appA.appRecord_->GetState()); + + auto abilities = appA.appRecord_->GetAbilities(); + EXPECT_NE(nullptr, abilities[tokenA]); + EXPECT_NE(nullptr, abilities[tokenB]); + EXPECT_NE(nullptr, abilities[tokenC]); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ChangeAbility + * CaseDescription: when one ability on foreground, request to load another ability of the another Application + */ +HWTEST_F(AmsWorkFlowTest, ChangeAbility_003, TestSize.Level1) +{ + APP_LOGD("AmsWorkFlowTest ChangeAbility_001 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + sptr tokenB = new MockAbilityToken(); + TestApplicationPreRecord appB = CreateTestApplicationRecord( + "B", tokenB, "B", AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + appB.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(appB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + std::shared_ptr abilityA = appA.GetAbility(tokenA); + std::shared_ptr abilityB = appB.GetAbility(tokenB); + EXPECT_NE(abilityA->GetAbilityInfo()->applicationName, abilityB->GetAbilityInfo()->applicationName); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appB.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appB.appRecord_->GetState()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + + auto abilitiesA = appA.appRecord_->GetAbilities(); + auto abilitiesB = appB.appRecord_->GetAbilities(); + EXPECT_NE(nullptr, abilitiesA[tokenA]); + EXPECT_NE(nullptr, abilitiesB[tokenB]); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ChangeAbility + * CaseDescription: when two ability on foreground, request to load another ability of the another Application + */ +HWTEST_F(AmsWorkFlowTest, ChangeAbility_004, TestSize.Level1) +{ + APP_LOGD("AmsWorkFlowTest ChangeAbility_004 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + appA.appRecord_->LaunchPendingAbilities(); + sptr tokenB = new MockAbilityToken(); + CreateTestApplicationRecord( + "B", tokenB, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenC = new MockAbilityToken(); + TestApplicationPreRecord appC = CreateTestApplicationRecord( + "C", tokenC, "C", AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + appC.appRecord_->LaunchPendingAbilities(); + EXPECT_CALL(*(appC.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); + + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + std::shared_ptr abilityA = appA.GetAbility(tokenA); + std::shared_ptr abilityB = appA.GetAbility(tokenB); + std::shared_ptr abilityC = appC.GetAbility(tokenC); + EXPECT_EQ(abilityA->GetAbilityInfo()->applicationName, abilityB->GetAbilityInfo()->applicationName); + EXPECT_NE(abilityC->GetAbilityInfo()->applicationName, abilityB->GetAbilityInfo()->applicationName); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenC)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appC.appRecord_->GetState()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + + auto abilitiesA = appA.appRecord_->GetAbilities(); + auto abilitiesC = appC.appRecord_->GetAbilities(); + EXPECT_NE(nullptr, abilitiesA[tokenA]); + EXPECT_NE(nullptr, abilitiesA[tokenB]); + EXPECT_NE(nullptr, abilitiesC[tokenC]); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: WorkFlow + * FunctionPoints: ChangeAbility + * CaseDescription: when a application on background, request to load another ability of the same Application + */ +HWTEST_F(AmsWorkFlowTest, ChangeAbility_005, TestSize.Level1) +{ + APP_LOGD("AmsWorkFlowTest ChangeAbility_004 start"); + sptr tokenA = new MockAbilityToken(); + TestApplicationPreRecord appA = CreateTestApplicationRecord( + "A", tokenA, "A", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + sptr tokenB = new MockAbilityToken(); + TestApplicationPreRecord appB = CreateTestApplicationRecord( + "B", tokenB, "B", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + sptr tokenC = new MockAbilityToken(); + CreateTestApplicationRecord("C", tokenC, "B", AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(appB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + + serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); + + serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); + + std::shared_ptr abilityB = appB.GetAbility(tokenB); + std::shared_ptr abilityC = appB.GetAbility(tokenC); + EXPECT_EQ(abilityC->GetAbilityInfo()->applicationName, abilityB->GetAbilityInfo()->applicationName); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appB.GetAbility(tokenC)->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appB.GetAbility(tokenB)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, appB.appRecord_->GetState()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, appA.appRecord_->GetState()); + + auto abilitiesA = appA.appRecord_->GetAbilities(); + auto abilitiesB = appB.appRecord_->GetAbilities(); + EXPECT_NE(nullptr, abilitiesA[tokenA]); + EXPECT_NE(nullptr, abilitiesB[tokenB]); + EXPECT_NE(nullptr, abilitiesB[tokenC]); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_cgroup_manager_test/BUILD.gn b/services/appmgr/test/unittest/ams_cgroup_manager_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e5c7ca85ad04ed9c8730750eb692cc815af4ba98 --- /dev/null +++ b/services/appmgr/test/unittest/ams_cgroup_manager_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsCgroupManagerTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/services/appmgr/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ "${services_path}/appmgr/src/cgroup_manager.cpp" ] + + sources += [ "ams_cgroup_manager_test.cpp" ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsCgroupManagerTest" ] +} diff --git a/services/appmgr/test/unittest/ams_cgroup_manager_test/ams_cgroup_manager_test.cpp b/services/appmgr/test/unittest/ams_cgroup_manager_test/ams_cgroup_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22718c6b8fad306b4956bd2dc6acaf26ce9c667a --- /dev/null +++ b/services/appmgr/test/unittest/ams_cgroup_manager_test/ams_cgroup_manager_test.cpp @@ -0,0 +1,1066 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "cgroup_manager.h" +#undef private + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "nocopyable.h" +#include "app_log_wrapper.h" +#include "securec.h" + +#define CG_CPUCTL_DIR "/dev/cpuctl" +#define CG_CPUCTL_DEFAULT_DIR CG_CPUCTL_DIR +#define CG_CPUCTL_DEFAULT_TASKS_PATH CG_CPUCTL_DEFAULT_DIR "/tasks" +#define CG_CPUCTL_BACKGROUND_DIR CG_CPUCTL_DIR "/background" +#define CG_CPUCTL_BACKGROUND_TASKS_PATH CG_CPUCTL_BACKGROUND_DIR "/tasks" + +#define CG_CPUSET_DIR "/dev/cpuset" +#define CG_CPUSET_DEFAULT_DIR CG_CPUSET_DIR +#define CG_CPUSET_DEFAULT_TASKS_PATH CG_CPUSET_DEFAULT_DIR "/tasks" +#define CG_CPUSET_BACKGROUND_DIR CG_CPUSET_DIR "/background" +#define CG_CPUSET_BACKGROUND_TASKS_PATH CG_CPUSET_BACKGROUND_DIR "/tasks" + +#define CG_FREEZER_DIR "/dev/freezer" +#define CG_FREEZER_FROZEN_DIR CG_FREEZER_DIR "/frozen" +#define CG_FREEZER_FROZEN_TASKS_PATH CG_FREEZER_FROZEN_DIR "/tasks" +#define CG_FREEZER_THAWED_DIR CG_FREEZER_DIR "/thawed" +#define CG_FREEZER_THAWED_TASKS_PATH CG_FREEZER_THAWED_DIR "/tasks" + +#define CG_MEM_DIR "/dev/memcg" +#define CG_MEM_OOMCTL_PATH CG_MEM_DIR "/memory.oom_control" +#define CG_MEM_EVTCTL_PATH CG_MEM_DIR "/cgroup.event_control" +#define CG_MEM_PRESSURE_LEVEL_PATH CG_MEM_DIR "/memory.pressure_level" + +constexpr int OPEN_FILE_MAX = 32768; + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AppExecFwk { +static int LOW_MEMORY_LEVEL = -1; + +class AmsCgroupManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + void OnLowMemoryAlert(const CgroupManager::LowMemoryLevel level); + static void RenameCpusetDir(); + static void RecoveryCpusetDir(); + static void RenameCpuctlDir(); + static void RecoveryCpuctlDir(); + static void RenameFreezerFrozen(); + static void RecoveryFreezerFrozen(); +}; + +void AmsCgroupManagerTest::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel level) +{ + APP_LOGI("OnLowMemoryAlert level %{public}d", level); + + LOW_MEMORY_LEVEL = level; +} + +void AmsCgroupManagerTest::RenameCpusetDir() +{ + // rename dir + std::string command = "mv /dev/cpuset/background /dev/cpuset/background_tmp"; + system((char *)command.c_str()); +} + +void AmsCgroupManagerTest::RecoveryCpusetDir() +{ + // recovery dir + std::string command = "mv /dev/cpuset/background_tmp /dev/cpuset/background"; + system((char *)command.c_str()); +} + +void AmsCgroupManagerTest::RenameCpuctlDir() +{ + // rename dir + std::string command = "mv /dev/cpuctl/background /dev/cpuctl/background_tmp"; + system((char *)command.c_str()); +} + +void AmsCgroupManagerTest::RecoveryCpuctlDir() +{ + // recovery dir + std::string command = "mv /dev/cpuctl/background_tmp /dev/cpuctl/background"; + system((char *)command.c_str()); +} + +void AmsCgroupManagerTest::RenameFreezerFrozen() +{ + // rename dir + std::string command = "mv /dev/freezer/frozen /dev/freezer/frozen_tmp"; + system((char *)command.c_str()); +} + +void AmsCgroupManagerTest::RecoveryFreezerFrozen() +{ + // recovery dir + std::string command = "mv /dev/freezer/frozen_tmp /dev/freezer/frozen"; + system((char *)command.c_str()); +} + +void AmsCgroupManagerTest::SetUpTestCase() +{} + +void AmsCgroupManagerTest::TearDownTestCase() +{} + +void AmsCgroupManagerTest::SetUp() +{ + if (DelayedSingleton::GetInstance()->LowMemoryAlert == nullptr) { + DelayedSingleton::GetInstance()->LowMemoryAlert = + std::bind(&AmsCgroupManagerTest::OnLowMemoryAlert, this, std::placeholders::_1); + } +} +void AmsCgroupManagerTest::TearDown() +{} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Init can check the invalid eventHandler_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_Init_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_Init_001 start."); + + DelayedSingleton::GetInstance()->eventHandler_ = + std::make_shared(EventRunner::Create()); + EXPECT_TRUE(DelayedSingleton::GetInstance()->eventHandler_ != nullptr); + + EXPECT_EQ(false, DelayedSingleton::GetInstance()->Init()); + EXPECT_EQ(true, DelayedSingleton::GetInstance()->IsInited()); + + // recover eventHandler_ + DelayedSingleton::GetInstance()->eventHandler_.reset(); + DelayedSingleton::GetInstance()->eventHandler_ = nullptr; + EXPECT_EQ(false, DelayedSingleton::GetInstance()->IsInited()); + + APP_LOGD("AmsCgroupManager_Init_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function Init can check the failure of calling InitCpusetTasksFds + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_Init_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_Init_002 start."); + + AmsCgroupManagerTest::RenameCpusetDir(); + + EXPECT_EQ(false, DelayedSingleton::GetInstance()->Init()); + + AmsCgroupManagerTest::RecoveryCpusetDir(); + + APP_LOGD("AmsCgroupManager_Init_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function Init can check the failure of calling InitCpuctlTasksFds + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_Init_003, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_Init_003 start."); + + AmsCgroupManagerTest::RenameCpuctlDir(); + + EXPECT_EQ(false, DelayedSingleton::GetInstance()->Init()); + + AmsCgroupManagerTest::RecoveryCpuctlDir(); + + APP_LOGD("AmsCgroupManager_Init_003 end."); +} +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function Init can check the failure of calling InitFreezerTasksFds + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_Init_004, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_Init_004 start."); + + AmsCgroupManagerTest::RenameFreezerFrozen(); + + EXPECT_EQ(false, DelayedSingleton::GetInstance()->Init()); + + AmsCgroupManagerTest::RecoveryFreezerFrozen(); + + APP_LOGD("AmsCgroupManager_Init_004 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function Init can check that the initialization is successful + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_Init_005, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_Init_005 start."); + + EXPECT_EQ(true, DelayedSingleton::GetInstance()->Init()); + + APP_LOGD("AmsCgroupManager_Init_005 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetThreadSchedPolicy can check the invalid eventHandler_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_001 start."); + + int tid = 1; + DelayedSingleton::GetInstance()->eventHandler_ = nullptr; + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetThreadSchedPolicy can check the invalid tid + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_002 start."); + + int tid = 0; + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetThreadSchedPolicy can check the invalid SchedPolicy + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_003, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_003 start."); + + int tid = 2; + int SchedPolicy = -1; + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_MAX)); + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, static_cast(SchedPolicy))); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_003 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetThreadSchedPolicy can check the invalid freezerTasksFds_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_004, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_004 start."); + + int tid = 2; + + DelayedSingleton::GetInstance() + ->freezerTasksFds_[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN] = -1; + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_FREEZED)); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_004 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetThreadSchedPolicy can check the invalid cpusetTasksFds_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_005, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_005 start."); + + int tid = 2; + + DelayedSingleton::GetInstance() + ->cpusetTasksFds_[CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND] = -1; + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_005 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetThreadSchedPolicy can check the invalid cpuctlTasksFds_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_006, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_006 start."); + + int tid = 2; + + DelayedSingleton::GetInstance()->cpuctlTasksFds_[CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT] = + -1; + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT)); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_006 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetThreadSchedPolicy can check the invalid freezerTasksFds_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_007, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_007 start."); + + int tid = 2; + + DelayedSingleton::GetInstance() + ->freezerTasksFds_[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_THAWED] = -1; + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_007 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetThreadSchedPolicy + * FunctionPoints: set thread schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function SetThreadSchedPolicy can be executed successfully + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetThreadSchedPolicy_008, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_008 start."); + + int tid = 1; + + DelayedSingleton::GetInstance()->eventHandler_ = + std::make_shared(EventRunner::Create()); + EXPECT_TRUE(DelayedSingleton::GetInstance()->eventHandler_ != nullptr); + + DelayedSingleton::GetInstance() + ->cpusetTasksFds_[CgroupManager::SchedPolicyCpu::SCHED_POLICY_CPU_BACKGROUND] = + open(CG_CPUSET_BACKGROUND_TASKS_PATH, O_RDWR); + + DelayedSingleton::GetInstance() + ->cpuctlTasksFds_[CgroupManager::SchedPolicyCpu::SCHED_POLICY_CPU_BACKGROUND] = + open(CG_CPUCTL_BACKGROUND_TASKS_PATH, O_RDWR); + + DelayedSingleton::GetInstance() + ->freezerTasksFds_[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_THAWED] = + open(CG_FREEZER_THAWED_TASKS_PATH, O_RDWR); + + EXPECT_EQ(true, + DelayedSingleton::GetInstance()->SetThreadSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsCgroupManager_SetThreadSchedPolicy_008 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetProcessSchedPolicy + * FunctionPoints: set process schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetProcessSchedPolicy can check the invalid eventHandler_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetProcessSchedPolicy_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_001 start."); + + int pid = 2; + DelayedSingleton::GetInstance()->eventHandler_ = nullptr; + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetProcessSchedPolicy( + pid, CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT)); + + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetProcessSchedPolicy + * FunctionPoints: set process schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetProcessSchedPolicy can check the invalid pid + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetProcessSchedPolicy_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_002 start."); + + int pid = 0; + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetProcessSchedPolicy( + pid, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetProcessSchedPolicy + * FunctionPoints: set process schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetProcessSchedPolicy can check the invalid SchedPolicy + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetProcessSchedPolicy_003, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_003 start."); + + int tid = 2; + int SchedPolicy = -1; + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetProcessSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_MAX)); + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetProcessSchedPolicy( + tid, static_cast(SchedPolicy))); + + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_003 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetProcessSchedPolicy + * FunctionPoints: set process schedpolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function SetProcessSchedPolicy can be executed successfully + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetProcessSchedPolicy_004, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_004 start."); + + int tid = 2; + DelayedSingleton::GetInstance()->eventHandler_ = + std::make_shared(EventRunner::Create()); + EXPECT_TRUE(DelayedSingleton::GetInstance()->eventHandler_ != nullptr); + + EXPECT_EQ(true, + DelayedSingleton::GetInstance()->SetProcessSchedPolicy( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT)); + + APP_LOGD("AmsCgroupManager_SetProcessSchedPolicy_004 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: OnReadable + * FunctionPoints: system low memory alert + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verification function OnLowMemoryAlert in OnReadable returned level + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_OnReadable_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_OnReadable_001 start."); + + uint64_t cnt = 100; + int32_t fd[2] = {0, 0}; + + if (pipe(fd) == -1) { + GTEST_LOG_(WARNING) << "create pipe fail"; + return; + } + write(fd[1], &cnt, sizeof(uint64_t)); + + DelayedSingleton::GetInstance() + ->memoryEventFds_[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_LOW] = fd[0]; + DelayedSingleton::GetInstance()->OnReadable(fd[0]); + + EXPECT_EQ(CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_LOW, LOW_MEMORY_LEVEL); + + APP_LOGD("AmsCgroupManager_OnReadable_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: OnReadable + * FunctionPoints: system low memory alert + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verification function OnLowMemoryAlert in OnReadable returned level + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_OnReadable_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_OnReadable_002 start "); + + uint64_t cnt = 100; + int32_t fd[2] = {0, 0}; + + if (pipe(fd) == -1) { + GTEST_LOG_(WARNING) << "create pipe fail"; + return; + } + write(fd[1], &cnt, sizeof(uint64_t)); + DelayedSingleton::GetInstance() + ->memoryEventFds_[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MEDIUM] = fd[0]; + + DelayedSingleton::GetInstance()->OnReadable(fd[0]); + + EXPECT_EQ(CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MEDIUM, LOW_MEMORY_LEVEL); + + APP_LOGD("AmsCgroupManager_OnReadable_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: OnReadable + * FunctionPoints: system low memory alert + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verification function OnLowMemoryAlert in OnReadable returned level + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_OnReadable_003, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_OnReadable_003 start."); + + uint64_t cnt = 100; + int32_t fd[2] = {0, 0}; + + if (pipe(fd) == -1) { + GTEST_LOG_(WARNING) << "create pipe fail"; + return; + } + write(fd[1], &cnt, sizeof(uint64_t)); + DelayedSingleton::GetInstance() + ->memoryEventFds_[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_CRITICAL] = fd[0]; + + DelayedSingleton::GetInstance()->OnReadable(fd[0]); + + EXPECT_EQ(CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_CRITICAL, LOW_MEMORY_LEVEL); + + APP_LOGD("AmsCgroupManager_OnReadable_003 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: RegisterLowMemoryMonitor + * FunctionPoints: registering low memory monitor + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function RegisterLowMemoryMonitor can check the invalid memoryEventControlFd + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_RegisterLowMemoryMonitor_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_RegisterLowMemoryMonitor_001 start."); + + int memoryEventFds[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MAX] = {0}; + int memoryPressureFds[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MAX] = {0}; + int memoryEventControlFd = -1; + auto eventHandler = std::make_shared(EventRunner::Create()); + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->RegisterLowMemoryMonitor(memoryEventFds, + memoryPressureFds, + memoryEventControlFd, + CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_LOW, + eventHandler)); + + APP_LOGD("AmsCgroupManager_RegisterLowMemoryMonitor_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: RegisterLowMemoryMonitor + * FunctionPoints: registering low memory monitor + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function RegisterLowMemoryMonitor can be executed successfully + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_RegisterLowMemoryMonitor_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_RegisterLowMemoryMonitor_002 start."); + + int memoryEventFds[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MAX] = {1}; + int memoryPressureFds[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MAX] = {1}; + int memoryEventControlFd = 1; + auto eventHandler = std::make_shared(EventRunner::Create()); + EXPECT_EQ(true, + DelayedSingleton::GetInstance()->RegisterLowMemoryMonitor(memoryEventFds, + memoryPressureFds, + memoryEventControlFd, + CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_LOW, + eventHandler)); + + APP_LOGD("AmsCgroupManager_RegisterLowMemoryMonitor_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitCpusetTasksFds + * FunctionPoints: initialization cpusetTasksFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitCpusetTasksFds initialization memoryPressureFds failed + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitCpusetTasksFds_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitCpusetTasksFds_001 start."); + + AmsCgroupManagerTest::RenameCpusetDir(); + + UniqueFd cpusetTasksFds[CgroupManager::SchedPolicy::SCHED_POLICY_MAX]; + EXPECT_EQ(false, DelayedSingleton::GetInstance()->InitCpusetTasksFds(cpusetTasksFds)); + + AmsCgroupManagerTest::RecoveryCpusetDir(); + + APP_LOGD("AmsCgroupManager_InitCpusetTasksFds_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitCpusetTasksFds + * FunctionPoints: initialization cpusetTasksFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitCpusetTasksFds initialization memoryPressureFds successful + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitCpusetTasksFds_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitCpusetTasksFds_002 start."); + + UniqueFd cpusetTasksFds[CgroupManager::SchedPolicy::SCHED_POLICY_MAX]; + EXPECT_EQ(true, DelayedSingleton::GetInstance()->InitCpusetTasksFds(cpusetTasksFds)); + + APP_LOGD("AmsCgroupManager_InitCpusetTasksFds_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitCpuctlTasksFds + * FunctionPoints: initialization cpuctlTasksFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitCpuctlTasksFds initialization memoryPressureFds failed + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitCpuctlTasksFds_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitCpuctlTasksFds_001 start."); + + AmsCgroupManagerTest::RenameCpuctlDir(); + + UniqueFd cpuctlTasksFds[CgroupManager::SchedPolicy::SCHED_POLICY_MAX]; + EXPECT_EQ(false, DelayedSingleton::GetInstance()->InitCpuctlTasksFds(cpuctlTasksFds)); + + AmsCgroupManagerTest::RecoveryCpuctlDir(); + + APP_LOGD("AmsCgroupManager_InitCpuctlTasksFds_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitCpuctlTasksFds + * FunctionPoints: initialization cpuctlTasksFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitCpuctlTasksFds initialization memoryPressureFds successful + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitCpuctlTasksFds_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitCpuctlTasksFds_002 start."); + + UniqueFd cpuctlTasksFds[CgroupManager::SchedPolicy::SCHED_POLICY_MAX]; + EXPECT_EQ(true, DelayedSingleton::GetInstance()->InitCpuctlTasksFds(cpuctlTasksFds)); + + APP_LOGD("AmsCgroupManager_InitCpuctlTasksFds_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitFreezerTasksFds + * FunctionPoints: initialization freezerTasksFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitFreezerTasksFds initialization memoryPressureFds failed + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitFreezerTasksFds_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitFreezerTasksFds_001 start."); + + AmsCgroupManagerTest::RenameFreezerFrozen(); + + UniqueFd freezerTasksFds[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_MAX]; + EXPECT_EQ(false, DelayedSingleton::GetInstance()->InitFreezerTasksFds(freezerTasksFds)); + + AmsCgroupManagerTest::RecoveryFreezerFrozen(); + + APP_LOGD("AmsCgroupManager_InitFreezerTasksFds_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitFreezerTasksFds + * FunctionPoints: initialization freezerTasksFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitFreezerTasksFds initialization memoryPressureFds successful + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitFreezerTasksFds_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitFreezerTasksFds_002 start."); + + UniqueFd freezerTasksFds[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_MAX]; + EXPECT_EQ(true, DelayedSingleton::GetInstance()->InitFreezerTasksFds(freezerTasksFds)); + + APP_LOGD("AmsCgroupManager_InitFreezerTasksFds_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitMemoryEventControlFd + * FunctionPoints: initialization memoryEventControlFd + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitMemoryEventControlFd initialization memoryPressureFds failed + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitMemoryEventControlFd_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitMemoryEventControlFd_001 start."); + + int fds[OPEN_FILE_MAX] = {0}; + for (auto &fd : fds) { + fd = open(CG_MEM_EVTCTL_PATH, O_WRONLY); + } + + UniqueFd memoryEventControlFd; + EXPECT_EQ(false, DelayedSingleton::GetInstance()->InitMemoryEventControlFd(memoryEventControlFd)); + + for (auto fd : fds) { + close(fd); + } + + APP_LOGD("AmsCgroupManager_InitMemoryEventControlFd_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitMemoryEventControlFd + * FunctionPoints: initialization memoryEventControlFd + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitMemoryEventControlFd initialization memoryPressureFds successful + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitMemoryEventControlFd_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitMemoryEventControlFd_002 start."); + + UniqueFd memoryEventControlFd; + EXPECT_EQ(true, DelayedSingleton::GetInstance()->InitMemoryEventControlFd(memoryEventControlFd)); + + APP_LOGD("AmsCgroupManager_InitMemoryEventControlFd_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitMemoryEventFds + * FunctionPoints: initialization memoryEventFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitMemoryEventFds initialization memoryPressureFds failed + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitMemoryEventFds_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitMemoryEventFds_001 start."); + + int fds[OPEN_FILE_MAX] = {0}; + for (auto &fd : fds) { + fd = eventfd(0, EFD_NONBLOCK); + } + + UniqueFd memoryEventFds[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MAX]; + EXPECT_EQ(false, DelayedSingleton::GetInstance()->InitMemoryEventFds(memoryEventFds)); + + for (auto fd : fds) { + close(fd); + } + + APP_LOGD("AmsCgroupManager_InitMemoryEventFds_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitMemoryEventFds + * FunctionPoints: initialization memoryEventFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitMemoryEventFds initialization memoryPressureFds successful + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitMemoryEventFds_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitMemoryEventFds_002 start."); + + UniqueFd memoryEventFds[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MAX]; + EXPECT_EQ(true, DelayedSingleton::GetInstance()->InitMemoryEventFds(memoryEventFds)); + + APP_LOGD("AmsCgroupManager_InitMemoryEventFds_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: InitMemoryPressureFds + * FunctionPoints: initialization memoryPressureFds + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: The verification function InitMemoryPressureFds initialization memoryPressureFds failed + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_InitMemoryPressureFds_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_InitMemoryPressureFds_001 start."); + + int fds[OPEN_FILE_MAX] = {0}; + for (auto &fd : fds) { + fd = open(CG_MEM_PRESSURE_LEVEL_PATH, O_RDONLY); + } + + UniqueFd memoryPressureFds[CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_MAX]; + EXPECT_EQ(false, DelayedSingleton::GetInstance()->InitMemoryPressureFds(memoryPressureFds)); + + for (auto fd : fds) { + close(fd); + } + + APP_LOGD("AmsCgroupManager_InitMemoryPressureFds_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetCpusetSubsystem + * FunctionPoints: set cpuset + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetCpusetSubsystem can check the invalid cpusetTasksFds_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetCpusetSubsystem_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetCpusetSubsystem_001 start."); + + int tid = 1; + + DelayedSingleton::GetInstance()->cpusetTasksFds_[CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT] = + -1; + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetCpusetSubsystem( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT)); + + APP_LOGD("AmsCgroupManager_SetCpusetSubsystem_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetCpusetSubsystem + * FunctionPoints: set cpuset + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function SetCpusetSubsystem can be called successfully + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetCpusetSubsystem_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetCpusetSubsystem_002 start."); + + int tid = 1; + + DelayedSingleton::GetInstance()->cpusetTasksFds_[CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT] = + open(CG_CPUCTL_DEFAULT_TASKS_PATH, O_RDWR); + + EXPECT_EQ(true, + DelayedSingleton::GetInstance()->SetCpusetSubsystem( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT)); + + APP_LOGD("AmsCgroupManager_SetCpusetSubsystem_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetCpuctlSubsystem + * FunctionPoints: set cpuctl + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetCpuctlSubsystem can check the invalid cpuctlTasksFds_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetCpuctlSubsystem_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetCpuctlSubsystem_001 start."); + + int tid = 1; + + DelayedSingleton::GetInstance() + ->cpuctlTasksFds_[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN] = -1; + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetCpuctlSubsystem( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT)); + + APP_LOGD("AmsCgroupManager_SetCpuctlSubsystem_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetCpuctlSubsystem + * FunctionPoints: set cpuctl + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function SetCpuctlSubsystem can be called successfully + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetCpuctlSubsystem_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetCpuctlSubsystem_002 start."); + + int tid = 1; + + DelayedSingleton::GetInstance() + ->cpuctlTasksFds_[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN] = + open(CG_FREEZER_FROZEN_TASKS_PATH, O_RDWR); + + EXPECT_EQ(true, + DelayedSingleton::GetInstance()->SetCpuctlSubsystem( + tid, CgroupManager::SchedPolicy::SCHED_POLICY_DEFAULT)); + + APP_LOGD("AmsCgroupManager_SetCpuctlSubsystem_002 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetFreezerSubsystem + * FunctionPoints: set frozen of freezer + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetFreezerSubsystem can check the invalid freezerTasksFds_ + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetFreezerSubsystem_001, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetFreezerSubsystem_001 start."); + + int tid = 1; + + DelayedSingleton::GetInstance() + ->freezerTasksFds_[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN] = -1; + + EXPECT_EQ(false, + DelayedSingleton::GetInstance()->SetFreezerSubsystem( + tid, CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN)); + + APP_LOGD("AmsCgroupManager_SetFreezerSubsystem_001 end."); +} + +/* + * Feature: AMS + * Function: CgroupManager + * SubFunction: SetFreezerSubsystem + * FunctionPoints: set frozen of freezer + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function SetFreezerSubsystem can be called successfully + */ +HWTEST_F(AmsCgroupManagerTest, AmsCgroupManager_SetFreezerSubsystem_002, TestSize.Level1) +{ + APP_LOGD("AmsCgroupManager_SetFreezerSubsystem_002 start."); + + int tid = 1; + + DelayedSingleton::GetInstance() + ->freezerTasksFds_[CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN] = + open(CG_FREEZER_FROZEN_TASKS_PATH, O_RDWR); + + EXPECT_EQ(true, + DelayedSingleton::GetInstance()->SetFreezerSubsystem( + tid, CgroupManager::SchedPolicyFreezer::SCHED_POLICY_FREEZER_FROZEN)); + + APP_LOGD("AmsCgroupManager_SetFreezerSubsystem_002 end."); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_ipc_interface_test/BUILD.gn b/services/appmgr/test/unittest/ams_ipc_interface_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ec7312e5dbc298bdf2a8964b04a8308638f19b4a --- /dev/null +++ b/services/appmgr/test/unittest/ams_ipc_interface_test/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsIpcAppSchedulerInterfaceTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + ] + + configs = [ + "//foundation/aafwk/standard/interfaces/innerkits/want:want_public_config", + ] + + sources = [ "ams_ipc_appscheduler_interface_test.cpp" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ "${services_path}/appmgr/test:appmgr_test_source" ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_unittest("AmsIpcAppMgrInterfaceTest") { + module_out_path = module_output_path + + sources = [ "ams_ipc_appmgr_interface_test.cpp" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ + ":AmsIpcAppMgrInterfaceTest", + ":AmsIpcAppSchedulerInterfaceTest", + ] +} diff --git a/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b7f1e95471c1bb7d93bcda8a70574a9cc0b4618 --- /dev/null +++ b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_scheduler_proxy.h" +#include +#include +#include "errors.h" +#include "ipc_types.h" +#include "app_log_wrapper.h" +#include "app_mgr_proxy.h" +#include "app_record_id.h" +#include "mock_application.h" +#include "mock_app_mgr_service.h" +#include "application_state_observer_stub.h" + +using namespace testing::ext; + +using OHOS::iface_cast; +using OHOS::sptr; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; +using testing::Return; + +namespace OHOS { +namespace AppExecFwk { +class AmsIpcAppMgrInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsIpcAppMgrInterfaceTest::SetUpTestCase() +{} + +void AmsIpcAppMgrInterfaceTest::TearDownTestCase() +{} + +void AmsIpcAppMgrInterfaceTest::SetUp() +{} + +void AmsIpcAppMgrInterfaceTest::TearDown() +{} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: interface + * CaseDescription: test interface of AttachApplication + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, Interface_001, TestSize.Level1) +{ + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_001 start"); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + sptr app(new MockApplication()); + + EXPECT_CALL(*mockAppMgr, AttachApplication(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + appMgrClient->AttachApplication(app); + mockAppMgr->Wait(); + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_001 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: interface + * CaseDescription: test interface of ApplicationForegrounded + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, Interface_002, TestSize.Level1) +{ + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_002 start"); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, ApplicationForegrounded(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + auto recordId = AppRecordId::Create(); + appMgrClient->ApplicationForegrounded(recordId); + mockAppMgr->Wait(); + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_002 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: interface + * CaseDescription: test interface of ApplicationBackgrounded + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, Interface_003, TestSize.Level1) +{ + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_003 start"); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, ApplicationBackgrounded(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + auto recordId = AppRecordId::Create(); + appMgrClient->ApplicationBackgrounded(recordId); + mockAppMgr->Wait(); + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_003 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: interface + * CaseDescription: test interface of ApplicationTerminated + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, Interface_004, TestSize.Level1) +{ + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_004 start"); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, ApplicationTerminated(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + auto recordId = AppRecordId::Create(); + appMgrClient->ApplicationTerminated(recordId); + mockAppMgr->Wait(); + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_004 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: interface + * CaseDescription: test interface of CheckPermission + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, Interface_005, TestSize.Level1) +{ + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_005 start"); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, CheckPermission(_, _)).Times(1).WillOnce(Return(OHOS::NO_ERROR)); + auto recordId = AppRecordId::Create(); + int ret = appMgrClient->CheckPermission(recordId, "write"); + EXPECT_EQ(OHOS::NO_ERROR, ret); + + EXPECT_CALL(*mockAppMgr, CheckPermission(_, _)).Times(1).WillOnce(Return(OHOS::NO_ERROR)); + ret = appMgrClient->CheckPermission(recordId, "read"); + EXPECT_EQ(OHOS::NO_ERROR, ret); + + EXPECT_CALL(*mockAppMgr, CheckPermission(_, _)).Times(1).WillOnce(Return(OHOS::ERR_INVALID_STATE)); + ret = appMgrClient->CheckPermission(recordId, "location"); + EXPECT_EQ(OHOS::ERR_INVALID_STATE, ret); + + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_005 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, Interface_006, TestSize.Level1) +{ + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_006 start"); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, CheckPermission(_, _)) + .Times(1) + .WillOnce(Invoke(mockAppMgr.GetRefPtr(), &MockAppMgrService::CheckPermissionImpl)); + auto recordId = AppRecordId::Create(); + int ret = appMgrClient->CheckPermission(recordId, "write"); + EXPECT_EQ(0, ret); + EXPECT_EQ("write", mockAppMgr->GetData()); + APP_LOGD("AppMgrIpcInterfaceTest_AppMgr_006 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, ClearUpApplicationData_008, TestSize.Level1) +{ + APP_LOGD("ClearUpApplicationData_008 start"); + + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, ClearUpApplicationData(_)).Times(1); + + appMgrClient->ClearUpApplicationData("PROCESS"); + + APP_LOGD("ClearUpApplicationData_008 end"); +} + +/* + * Feature: AMS + * Function: IPC IsBackgroundRunningRestricted + * SubFunction: appmgr interface + * FunctionPoints: Check background operation + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, IsBackgroundRunningRestricted_009, TestSize.Level1) +{ + APP_LOGD("IsBackgroundRunningRestricted_009 start"); + + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, IsBackgroundRunningRestricted(_)).Times(1).WillOnce(Return(OHOS::NO_ERROR)); + + int32_t ret = appMgrClient->IsBackgroundRunningRestricted("PROCESS"); + + EXPECT_EQ(ret, OHOS::NO_ERROR); + // Returns 32 when the bundle name is empty + EXPECT_CALL(*mockAppMgr, IsBackgroundRunningRestricted(_)).Times(1).WillOnce(Return(32)); + ret = appMgrClient->IsBackgroundRunningRestricted(""); + + EXPECT_EQ(ret, 32); + APP_LOGD("IsBackgroundRunningRestricted_009 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, GetAllRunningProcesses_010, TestSize.Level1) +{ + APP_LOGD("GetAllRunningProcesses_009 start"); + + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, GetAllRunningProcesses(_)).Times(1).WillOnce(Return(OHOS::ERR_NULL_OBJECT)); + + std::vector runningProcessInfo; + int32_t ret = appMgrClient->GetAllRunningProcesses(runningProcessInfo); + EXPECT_EQ(ret, OHOS::ERR_NULL_OBJECT); + + EXPECT_CALL(*mockAppMgr, GetAllRunningProcesses(_)).Times(1).WillOnce(Return(OHOS::ERR_NONE)); + ret = appMgrClient->GetAllRunningProcesses(runningProcessInfo); + EXPECT_EQ(ret, OHOS::ERR_NONE); + + APP_LOGD("GetAllRunningProcesses_009 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, GetSystemMemoryAttr_0100, TestSize.Level1) +{ + APP_LOGD("GetSystemMemoryAttr_0100 start"); + + OHOS::AppExecFwk::SystemMemoryAttr memInfo; + std::string strConfig; + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + auto TestCall = [](OHOS::AppExecFwk::SystemMemoryAttr& mem, std::string &strConfig) { + mem.availSysMem_ = 1; + mem.isSysInlowMem_ = true; + mem.threshold_ = 1; + mem.totalSysMem_ = 1; + }; + + EXPECT_CALL(*mockAppMgr, GetSystemMemoryAttr(_, _)).Times(1).WillOnce(Invoke(TestCall)); + + appMgrClient->GetSystemMemoryAttr(memInfo, strConfig); + + EXPECT_EQ(1, memInfo.availSysMem_); + EXPECT_EQ(1, memInfo.threshold_); + EXPECT_EQ(1, memInfo.totalSysMem_); + EXPECT_TRUE(memInfo.isSysInlowMem_); + + APP_LOGD("GetSystemMemoryAttr_0100 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, RegisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("RegisterApplicationStateObserver_001 start"); + + sptr observer = new ApplicationStateObserverStub(); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, RegisterApplicationStateObserver(_)).Times(1).WillOnce(Return(OHOS::NO_ERROR)); + + int32_t err = appMgrClient->RegisterApplicationStateObserver(observer); + + EXPECT_EQ(OHOS::NO_ERROR, err); + + APP_LOGD("RegisterApplicationStateObserver_001 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsIpcAppMgrInterfaceTest, UnregisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("UnregisterApplicationStateObserver_001 start"); + + sptr observer = new ApplicationStateObserverStub(); + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + + EXPECT_CALL(*mockAppMgr, UnregisterApplicationStateObserver(_)).Times(1).WillOnce(Return(OHOS::NO_ERROR)); + + int32_t err = appMgrClient->UnregisterApplicationStateObserver(observer); + + EXPECT_EQ(OHOS::NO_ERROR, err); + + APP_LOGD("UnregisterApplicationStateObserver_001 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62e9c315074addcfd72f4edfc7cb030642a921f5 --- /dev/null +++ b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_scheduler_proxy.h" +#include +#include "app_log_wrapper.h" +#include "app_scheduler_host.h" +#include "mock_ability_token.h" +#include "mock_application.h" + +using namespace testing::ext; +using OHOS::iface_cast; +using OHOS::sptr; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; +namespace OHOS { +namespace AppExecFwk { +class AmsIpcAppSchedulerInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + sptr GetMockToken() const + { + return mock_token_; + } + +private: + sptr mock_token_; +}; + +void AmsIpcAppSchedulerInterfaceTest::SetUpTestCase() +{} + +void AmsIpcAppSchedulerInterfaceTest::TearDownTestCase() +{} + +void AmsIpcAppSchedulerInterfaceTest::SetUp() +{ + mock_token_ = new (std::nothrow) MockAbilityToken(); +} + +void AmsIpcAppSchedulerInterfaceTest::TearDown() +{} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleForegroundApplication + * SubFunction: NA + * FunctionPoints: ScheduleForegroundApplication interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleForegroundApplication of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_001, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_001 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleForegroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleForegroundApplication(); + mockApplication->Wait(); + APP_LOGD("AppSchedulerInterfaceTest_001 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleBackgroundApplication + * SubFunction: NA + * FunctionPoints: scheduleBackgroundApplication interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleBackgroundApplication of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_002, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_002 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleBackgroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleBackgroundApplication(); + mockApplication->Wait(); + APP_LOGD("AppSchedulerInterfaceTest_002 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleTerminateApplication + * SubFunction: NA + * FunctionPoints: scheduleTerminateApplication interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleTerminateApplication of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_003, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_003 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleTerminateApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleTerminateApplication(); + mockApplication->Wait(); + APP_LOGD("AppSchedulerInterfaceTest_003 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleShrinkMemory + * SubFunction: NA + * FunctionPoints: scheduleShrinkMemory interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleShrinkMemory of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_004, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_004 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + int level = 1; + + EXPECT_CALL(*mockApplication, ScheduleShrinkMemory(_)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::ShrinkMemory)); + client->ScheduleShrinkMemory(level); + mockApplication->Wait(); + + int shrinkLevel = mockApplication->GetShrinkLevel(); + EXPECT_EQ(level, shrinkLevel); + APP_LOGD("AppSchedulerInterfaceTest_004 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleLowMemory + * SubFunction: NA + * FunctionPoints: scheduleLowMemory interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleLowMemory of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_005, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_005 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleLowMemory()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleLowMemory(); + mockApplication->Wait(); + APP_LOGD("AppSchedulerInterfaceTest_005 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleLaunchApplication + * SubFunction: NA + * FunctionPoints: scheduleLaunchApplication interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleLaunchApplication of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_006, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_006 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + std::string applicationName("mockApplicationInfo"); + ApplicationInfo applicationInfo; + applicationInfo.name = applicationName; + std::string profileName("mockProfile"); + Profile profile(profileName); + std::string processName("mockProcessInfo"); + ProcessInfo processInfo(processName, 1); + + AppLaunchData launchData; + launchData.SetApplicationInfo(applicationInfo); + launchData.SetProfile(profile); + launchData.SetProcessInfo(processInfo); + + Configuration config; + EXPECT_CALL(*mockApplication, ScheduleLaunchApplication(_, _)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::LaunchApplication)); + client->ScheduleLaunchApplication(launchData, config); + mockApplication->Wait(); + + bool isEqual = mockApplication->CompareAppLaunchData(launchData); + EXPECT_EQ(true, isEqual); + APP_LOGD("AppSchedulerInterfaceTest_006 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleLaunchAbility + * SubFunction: NA + * FunctionPoints: scheduleLaunchAbility interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleLaunchAbility of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_007, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_007 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + std::string abilityName("mockAbilityInfo"); + AbilityInfo info; + info.name = abilityName; + + EXPECT_CALL(*mockApplication, ScheduleLaunchAbility(_, _)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::LaunchAbility)); + client->ScheduleLaunchAbility(info, GetMockToken()); + mockApplication->Wait(); + + bool isEqual = mockApplication->CompareAbilityInfo(info); + EXPECT_EQ(true, isEqual); + APP_LOGD("AppSchedulerInterfaceTest_007 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleCleanAbility + * SubFunction: NA + * FunctionPoints: scheduleCleanAbility interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleCleanAbility of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_008, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_008 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleCleanAbility(_)) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleCleanAbility(GetMockToken()); + mockApplication->Wait(); + APP_LOGD("AppSchedulerInterfaceTest_008 end"); +} + +/* + * Feature: AppScheduler ZIDL interface + * Function: ScheduleCleanAbility + * SubFunction: NA + * FunctionPoints: scheduleProfileChanged interface + * EnvConditions: Application already running + * CaseDescription: Test the interface ScheduleProfileChanged of AppScheduler + */ +HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_009, TestSize.Level1) +{ + APP_LOGD("AppSchedulerInterfaceTest_009 start"); + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + std::string profileName("mockProfile"); + Profile profile(profileName); + + EXPECT_CALL(*mockApplication, ScheduleProfileChanged(_)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::ProfileChanged)); + client->ScheduleProfileChanged(profile); + mockApplication->Wait(); + + bool isEqual = mockApplication->CompareProfile(profile); + EXPECT_EQ(true, isEqual); + APP_LOGD("AppSchedulerInterfaceTest_009 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_lmks_client_test/BUILD.gn b/services/appmgr/test/unittest/ams_lmks_client_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8e0af25a7884396549720d86f8b9286c5098ed4e --- /dev/null +++ b/services/appmgr/test/unittest/ams_lmks_client_test/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsLmksClientTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/services/appmgr/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ "${services_path}/appmgr/src/lmks_client.cpp" ] + + sources += [ "ams_lmks_client_test.cpp" ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsLmksClientTest" ] +} diff --git a/services/appmgr/test/unittest/ams_lmks_client_test/ams_lmks_client_test.cpp b/services/appmgr/test/unittest/ams_lmks_client_test/ams_lmks_client_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec424cefb166aa303df01fc6e746a6d6468f83ff --- /dev/null +++ b/services/appmgr/test/unittest/ams_lmks_client_test/ams_lmks_client_test.cpp @@ -0,0 +1,387 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "lmks_client.h" +#undef private + +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" + +using namespace testing::ext; + +namespace OHOS { +namespace AppExecFwk { +class AmsLmksClientTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsLmksClientTest::SetUpTestCase() +{} +void AmsLmksClientTest::TearDownTestCase() +{} +void AmsLmksClientTest::SetUp() +{} +void AmsLmksClientTest::TearDown() +{} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Open + * FunctionPoints: open socket + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Open can check the invalid socket_ + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Open_001, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Open_001 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + amsLmksClient->socket_ = 0; + EXPECT_EQ(-1, amsLmksClient->Open()); + + APP_LOGD("AmsLmksClientTest_Open_001 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Open + * FunctionPoints: open socket + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: open socket success + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Open_002, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Open_002 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + amsLmksClient->socket_ = -1; + EXPECT_EQ(ERR_OK, amsLmksClient->Open()); + + APP_LOGD("AmsLmksClientTest_Open_002 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Target + * FunctionPoints: Oom adj mapping table value of the initialization process + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Target can check the invalid targets + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Target_001, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Target_001 start."); + + std::vector> targets; + std::unique_ptr amsLmksClient = std::make_unique(); + + EXPECT_EQ(-EINVAL, amsLmksClient->Target(targets)); + + APP_LOGD("AmsLmksClientTest_Target_001 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Target + * FunctionPoints: Oom adj mapping table value of the initialization process + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Target can check the invalid targets + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Target_002, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Target_002 start."); + + std::vector> targets{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}}; + std::unique_ptr amsLmksClient = std::make_unique(); + + EXPECT_EQ(-EINVAL, amsLmksClient->Target(targets)); + + APP_LOGD("AmsLmksClientTest_Target_002 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Target + * FunctionPoints: Oom adj mapping table value of the initialization process + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Target can check the invalid targets + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Target_003, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Target_003 start."); + + std::vector> targets{{-1, 2}}; + std::unique_ptr amsLmksClient = std::make_unique(); + + EXPECT_EQ(-EINVAL, amsLmksClient->Target(targets)); + + APP_LOGD("AmsLmksClientTest_Target_003 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Target + * FunctionPoints: Oom adj mapping table value of the initialization process + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Target can check the invalid targets + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Target_004, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Target_004 start."); + + std::vector> targets{{1, 1100}}; + std::unique_ptr amsLmksClient = std::make_unique(); + + EXPECT_EQ(-EINVAL, amsLmksClient->Target(targets)); + + APP_LOGD("AmsLmksClientTest_Target_004 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Target + * FunctionPoints: Oom adj mapping table value of the initialization process + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function Target can be executed normally + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Target_005, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Target_005 start."); + + std::vector> targets{{1, 10}}; + std::unique_ptr amsLmksClient = std::make_unique(); + + EXPECT_EQ(ERR_OK, amsLmksClient->Target(targets)); + + APP_LOGD("AmsLmksClientTest_Target_005 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: ProcPrio + * FunctionPoints: Update the oom adj value of pid + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function ProcPrio can check the invalid pid + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_ProcPrio_001, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_ProcPrio_001 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + pid_t pid = -1; + uid_t uid = 1; + int oomAdj = 0; + EXPECT_EQ(-EINVAL, amsLmksClient->ProcPrio(pid, uid, oomAdj)); + + APP_LOGD("AmsLmksClientTest_ProcPrio_001 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: ProcPrio + * FunctionPoints: Update the oom adj value of pid + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function ProcPrio can check the invalid oomAdj + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_ProcPrio_002, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_ProcPrio_002 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + pid_t pid = 1; + uid_t uid = 1; + int oomAdj = 1100; + EXPECT_EQ(-EINVAL, amsLmksClient->ProcPrio(pid, uid, oomAdj)); + + APP_LOGD("AmsLmksClientTest_ProcPrio_002 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: ProcPrio + * FunctionPoints: Update the oom adj value of pid + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function ProcPrio can be executed normally + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_ProcPrio_003, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_ProcPrio_003 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + pid_t pid = 1; + uid_t uid = 1; + int oomAdj = 10; + EXPECT_EQ(ERR_OK, amsLmksClient->ProcPrio(pid, uid, oomAdj)); + + APP_LOGD("AmsLmksClientTest_ProcPrio_003 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: ProcRemove + * FunctionPoints: remove process + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function ProcRemove can check the invalid pid + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_ProcRemove_001, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_ProcRemove_001 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + pid_t pid = -1; + EXPECT_EQ(-EINVAL, amsLmksClient->ProcRemove(pid)); + + APP_LOGD("AmsLmksClientTest_ProcRemove_001 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: ProcRemove + * FunctionPoints: remove process + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function ProcRemove success to remove process + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_ProcRemove_002, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_ProcRemove_002 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + pid_t pid = 1; + EXPECT_EQ(0, amsLmksClient->ProcRemove(pid)); + + APP_LOGD("AmsLmksClientTest_ProcRemove_002 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Write + * FunctionPoints: send data + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Write can check the invalid buf + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Write_001, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Write_001 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + int32_t *buf = nullptr; + size_t len = 2; + EXPECT_EQ(false, amsLmksClient->Write(buf, len)); + + APP_LOGD("AmsLmksClientTest_Write_001 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Write + * FunctionPoints: send data + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Write can check the invalid len + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Write_002, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Write_002 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + int32_t buf[2] = {1, 2}; + size_t len = -1; + EXPECT_EQ(false, amsLmksClient->Write(buf, len)); + + APP_LOGD("AmsLmksClientTest_Write_002 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Read + * FunctionPoints: Receive data + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Read can check the invalid buf + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Read_001, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Read_001 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + int32_t *buf = nullptr; + size_t len = 2; + EXPECT_EQ(false, amsLmksClient->Read(buf, len)); + + APP_LOGD("AmsLmksClientTest_Read_001 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Read + * FunctionPoints: Receive data + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Read can check the invalid len + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Read_002, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Read_002 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + int32_t buf[2] = {1, 2}; + size_t len = -1; + EXPECT_EQ(false, amsLmksClient->Read(buf, len)); + + APP_LOGD("AmsLmksClientTest_Read_002 end."); +} + +/* + * Feature: AMS + * Function: LmksClient + * SubFunction: Close + * FunctionPoints: close socket + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the close function closes the socket + */ +HWTEST_F(AmsLmksClientTest, AmsLmksClientTest_Close_001, TestSize.Level1) +{ + APP_LOGD("AmsLmksClientTest_Close_001 start."); + + std::unique_ptr amsLmksClient = std::make_unique(); + amsLmksClient->Close(); + EXPECT_EQ(false, amsLmksClient->IsOpen()); + + APP_LOGD("AmsLmksClientTest_Close_001 end."); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_mgr_scheduler_test/BUILD.gn b/services/appmgr/test/unittest/ams_mgr_scheduler_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..967837c0768b05e6df2ce69572657104c729f192 --- /dev/null +++ b/services/appmgr/test/unittest/ams_mgr_scheduler_test/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsMgrSchedulerTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/appmgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + ] + + sources = [ "${services_path}/appmgr/src/ams_mgr_scheduler.cpp" ] + + sources += [ "ams_mgr_scheduler_test.cpp" ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/services/appmgr:libams", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsMgrSchedulerTest" ] +} diff --git a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6734c2ef1319131bb2e9c1c6a80b85d710ea1f83 --- /dev/null +++ b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp @@ -0,0 +1,447 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 + +#define private public +#include "ams_mgr_scheduler.h" +#undef private + +#include "app_log_wrapper.h" +#include "app_state_callback_host.h" +#include "mock_ability_token.h" +#include "mock_app_mgr_service_inner.h" +#include "application_state_observer_stub.h" + +using namespace testing; +using namespace testing::ext; +using testing::_; +using testing::Return; + +namespace OHOS { +namespace AppExecFwk { +class AmsMgrSchedulerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +public: +protected: + static const std::string GetTestAppName() + { + return "test_app_name"; + } + static const std::string GetTestAbilityName() + { + return "test_ability_name"; + } + + std::shared_ptr GetMockAppMgrServiceInner(); + std::shared_ptr GetAmsEventHandler(); + +private: + std::shared_ptr mockAppMgrServiceInner_; + std::shared_ptr amsEventHandler_; +}; + +void AmsMgrSchedulerTest::SetUpTestCase() +{} + +void AmsMgrSchedulerTest::TearDownTestCase() +{} + +void AmsMgrSchedulerTest::SetUp() +{} + +void AmsMgrSchedulerTest::TearDown() +{ + amsEventHandler_.reset(); + mockAppMgrServiceInner_.reset(); +} + +std::shared_ptr AmsMgrSchedulerTest::GetMockAppMgrServiceInner() +{ + if (!mockAppMgrServiceInner_) { + mockAppMgrServiceInner_ = std::make_shared(); + } + return mockAppMgrServiceInner_; +} + +std::shared_ptr AmsMgrSchedulerTest::GetAmsEventHandler() +{ + if (!amsEventHandler_) { + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + amsEventHandler_ = + std::make_shared(EventRunner::Create("AmsMgrSchedulerTest"), mockAppMgrServiceInner); + } + return amsEventHandler_; +} + +/* + * Feature: AMS + * Function: AmsMgrScheduler + * SubFunction: LoadAbility + * FunctionPoints: Act normal + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function LoadAbility can works. + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_001, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_001 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr token = new MockAbilityToken(); + sptr preToken = new MockAbilityToken(); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + std::shared_ptr applicationInfo = std::make_shared(); + applicationInfo->name = GetTestAppName(); + + EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler->LoadAbility(token, preToken, abilityInfo, applicationInfo); + mockAppMgrServiceInner->Wait(); + + APP_LOGD("AmsMgrScheduler_001 end."); +} + +/* + * Feature: AMS + * Function: AmsMgrScheduler + * SubFunction: LoadAbility + * FunctionPoints: Check params + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function LoadAbility can check appInfo and abilityInfo. + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_002, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_002 start."); + + auto mockAppMgrServiceInner = std::make_shared(); + auto eventRunner = EventRunner::Create("AmsMgrSchedulerTest"); + auto amsEventHandler = std::make_shared(eventRunner, mockAppMgrServiceInner); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr token = new MockAbilityToken(); + sptr preToken = new MockAbilityToken(); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + std::shared_ptr applicationInfo = std::make_shared(); + applicationInfo->name = GetTestAppName(); + + // check token parameter + EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)).Times(0); + amsMgrScheduler->LoadAbility(token, preToken, nullptr, applicationInfo); + + // check pretoken parameter + EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)).Times(0); + amsMgrScheduler->LoadAbility(token, preToken, abilityInfo, nullptr); + + APP_LOGD("AmsMgrScheduler_002 end."); +} + +/* + * Feature: AMS + * Function: AmsMgrScheduler + * SubFunction: UpdateAbilityState + * FunctionPoints: Act normal + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function UpdateAbilityState can works. + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_003, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_003 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr token = new MockAbilityToken(); + AbilityState abilityState = AbilityState::ABILITY_STATE_BEGIN; + + EXPECT_CALL(*mockAppMgrServiceInner, UpdateAbilityState(_, _)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler->UpdateAbilityState(token, abilityState); + mockAppMgrServiceInner->Wait(); + + APP_LOGD("AmsMgrScheduler_003 end."); +} + +/* + * Feature: AMS + * Function: AmsMgrScheduler + * SubFunction: TerminateAbility + * FunctionPoints: Act normal + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function TerminateAbility can works. + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_004, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_004 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + sptr token = new MockAbilityToken(); + + EXPECT_CALL(*mockAppMgrServiceInner, TerminateAbility(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler->TerminateAbility(token); + mockAppMgrServiceInner->Wait(); + + APP_LOGD("AmsMgrScheduler_004 end."); +} + +/* + * Feature: AMS + * Function: AmsMgrScheduler + * SubFunction: RegisterAppStateCallback + * FunctionPoints: Act normal + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function RegisterAppStateCallback can works. + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_005, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_005 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr appStateCallbackHost = new AppStateCallbackHost(); + EXPECT_CALL(*mockAppMgrServiceInner, RegisterAppStateCallback(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler->RegisterAppStateCallback(appStateCallbackHost); + mockAppMgrServiceInner->Wait(); + + APP_LOGD("AmsMgrScheduler_005 end."); +} + +/* + * Feature: AMS + * Function: AmsMgrScheduler + * SubFunction: Reset + * FunctionPoints: Act normal + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Reset can works. + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_006, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_006 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr appStateCallbackHost = new AppStateCallbackHost(); + EXPECT_CALL(*mockAppMgrServiceInner, StopAllProcess()) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler->Reset(); + mockAppMgrServiceInner->Wait(); + + APP_LOGD("AmsMgrScheduler_006 end."); +} + +/* + * Feature: AMS + * Function: AmsMgrScheduler + * SubFunction: IsReady + * FunctionPoints: Check Params + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function IsReady can check params. + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_007, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_007 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + + // act normal + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + EXPECT_EQ(true, amsMgrScheduler->IsReady()); + + // check params AppMgrServiceInner + std::unique_ptr amsMgrScheduler2 = std::make_unique(nullptr, amsEventHandler); + EXPECT_EQ(false, amsMgrScheduler2->IsReady()); + + // check params AMSEventHandler + std::unique_ptr amsMgrScheduler3 = + std::make_unique(mockAppMgrServiceInner, nullptr); + EXPECT_EQ(false, amsMgrScheduler3->IsReady()); + + APP_LOGD("AmsMgrScheduler_007 end."); +} + +/* + * Feature: AMS + * Function: KillApplication + * SubFunction: IsReady + * FunctionPoints: Check Params + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Kill apps by name + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_008, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_008 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + + EXPECT_CALL(*mockAppMgrServiceInner, KillApplication(_)).Times(1).WillOnce(Return(ERR_OK)); + + // check params AppMgrServiceInner + std::unique_ptr amsMgrScheduler2 = std::make_unique(nullptr, amsEventHandler); + EXPECT_EQ(false, amsMgrScheduler2->IsReady()); + + EXPECT_EQ(ERR_INVALID_OPERATION, amsMgrScheduler2->KillApplication(GetTestAppName())); + + // check params AMSEventHandler + std::unique_ptr amsMgrScheduler3 = + std::make_unique(mockAppMgrServiceInner, nullptr); + EXPECT_EQ(false, amsMgrScheduler3->IsReady()); + + EXPECT_EQ(ERR_INVALID_OPERATION, amsMgrScheduler3->KillApplication(GetTestAppName())); + + // act normal + std::unique_ptr amsMgrScheduler4 = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + EXPECT_EQ(true, amsMgrScheduler4->IsReady()); + + EXPECT_EQ(ERR_OK, amsMgrScheduler4->KillApplication(GetTestAppName())); + + APP_LOGD("AmsMgrScheduler_008 end."); +} + +/* + * Feature: AMS + * Function: AbilityBehaviorAnalysis + * SubFunction: IsReady + * FunctionPoints: Check Params + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Optimize based on visibility and perception + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_009, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_009 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + EXPECT_EQ(true, amsMgrScheduler->IsReady()); + + EXPECT_CALL(*mockAppMgrServiceInner, AbilityBehaviorAnalysis(_, _, _, _, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + + sptr token; + sptr preToken; + int32_t visibility = 0; + int32_t perceptibility = 0; + int32_t connectionState = 0; + + amsMgrScheduler->AbilityBehaviorAnalysis(token, preToken, visibility, perceptibility, connectionState); + + mockAppMgrServiceInner->Wait(); + + mockAppMgrServiceInner.reset(); + amsEventHandler.reset(); + + APP_LOGD("AmsMgrScheduler_009 end."); +} + +/* + * Feature: AMS + * Function: AbilityBehaviorAnalysis + * SubFunction: IsReady + * FunctionPoints: Check Params + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Optimize based on visibility and perception + */ +HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_010, TestSize.Level1) +{ + APP_LOGD("AmsMgrScheduler_010 start."); + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + + std::unique_ptr amsMgrScheduler = std::make_unique(nullptr, nullptr); + EXPECT_EQ(false, amsMgrScheduler->IsReady()); + + EXPECT_CALL(*mockAppMgrServiceInner, AbilityBehaviorAnalysis(_, _, _, _, _)).Times(0); + + sptr token; + sptr preToken; + int32_t visibility = 0; + int32_t perceptibility = 0; + int32_t connectionState = 0; + + amsMgrScheduler->AbilityBehaviorAnalysis(token, preToken, visibility, perceptibility, connectionState); + + APP_LOGD("AmsMgrScheduler_010 end."); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsMgrSchedulerTest, RegisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("RegisterApplicationStateObserver_001 start"); + sptr observer = new ApplicationStateObserverStub(); + auto mockAppMgrServiceInner = std::make_shared(); + mockAppMgrServiceInner->RegisterApplicationStateObserver(observer); + int32_t err = mockAppMgrServiceInner->RegisterApplicationStateObserver(observer); + // repeat register return ERR_INVALID_VALUE + EXPECT_EQ(ERR_INVALID_VALUE, err); + APP_LOGD("RegisterApplicationStateObserver_001 end"); +} + +/* + * Feature: AMS + * Function: IPC + * SubFunction: appmgr interface + * FunctionPoints: KillApplication interface + * CaseDescription: test IPC can transact data + */ +HWTEST_F(AmsMgrSchedulerTest, UnregisterApplicationStateObserver_001, TestSize.Level0) +{ + APP_LOGD("UnregisterApplicationStateObserver_001 start"); + sptr observer = new ApplicationStateObserverStub(); + auto mockAppMgrServiceInner = std::make_shared(); + int32_t err1 = mockAppMgrServiceInner->UnregisterApplicationStateObserver(observer); + // unregister not exist return ERR_INVALID_VALUE + EXPECT_EQ(ERR_INVALID_VALUE, err1); + int32_t err2 = mockAppMgrServiceInner->UnregisterApplicationStateObserver(nullptr); + // unregister null return ERR_INVALID_VALUE + EXPECT_EQ(ERR_INVALID_VALUE, err2); + APP_LOGD("UnregisterApplicationStateObserver_001 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_process_optimizer_test/BUILD.gn b/services/appmgr/test/unittest/ams_process_optimizer_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a6dca78f458f2436dafa6a28ffc075d3c3ede469 --- /dev/null +++ b/services/appmgr/test/unittest/ams_process_optimizer_test/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsamsProcessOptimizerTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//foundation/aafwk/standard/services/appmgr/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + ] + + sources += [ + "${services_path}/appmgr/test/mock/src/cgroup_manager.cpp", + "ams_process_optimizer_test.cpp", + ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsamsProcessOptimizerTest" ] +} diff --git a/services/appmgr/test/unittest/ams_process_optimizer_test/ams_process_optimizer_test.cpp b/services/appmgr/test/unittest/ams_process_optimizer_test/ams_process_optimizer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d115fd46d62bcd98390df37402bb30a8255dcf14 --- /dev/null +++ b/services/appmgr/test/unittest/ams_process_optimizer_test/ams_process_optimizer_test.cpp @@ -0,0 +1,905 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 + +#define private public +#define protected public +#include "process_optimizer.h" +#undef private +#undef protected +#include "app_log_wrapper.h" +#include +#include +#include +#include "lmks_client.h" + +namespace{ +constexpr int APP_OOM_ADJ_BACKGROUND_MIN = 400; +constexpr int APP_OOM_ADJ_SUSPEND_MIN = 600; +const std::string APP_RECORD_NAME = "App_Name_Z"; +static constexpr int APP_SUSPEND_TIMEOUT_DEFAULT = 100; +static constexpr int APP_USLEEP = 200 * 1000; +using namespace testing::ext; +}; + +namespace OHOS { +namespace AppExecFwk { +class AmsProcessOptimizerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsProcessOptimizerTest::SetUpTestCase() +{} +void AmsProcessOptimizerTest::TearDownTestCase() +{} +void AmsProcessOptimizerTest::SetUp() +{} +void AmsProcessOptimizerTest::TearDown() +{} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Init can check the invalid suspendTimeout + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_Init_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_Init_001 start."); + + auto lmksClient = std::make_shared(); + int suspendTimeout = -1; + std::unique_ptr amsProcessOptimizer = + std::make_unique(lmksClient, suspendTimeout); + EXPECT_EQ(false, amsProcessOptimizer->Init()); + + APP_LOGD("AmsProcessOptimizerTest_Init_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function Init can check the invalid eventHandler_ + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_Init_002, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_Init_002 start."); + + auto lmksClient = std::make_shared(); + int suspendTimeout = 0; + std::unique_ptr amsProcessOptimizer = + std::make_unique(lmksClient, suspendTimeout); + amsProcessOptimizer->eventHandler_ = std::make_shared(EventRunner::Create()); + EXPECT_EQ(false, amsProcessOptimizer->Init()); + amsProcessOptimizer->eventHandler_ = nullptr; + + APP_LOGD("AmsProcessOptimizerTest_Init_002 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: Init + * FunctionPoints: initialization + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function Init can be executed normally and initialize + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_Init_003, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_Init_003 start."); + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + + EXPECT_EQ(true, amsProcessOptimizer->Init()); + + APP_LOGD("AmsProcessOptimizerTest_Init_003 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppAdded + * FunctionPoints: add application in appLru_ + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function OnAppAdded can check the invalid app + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_OnAppAdded_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_OnAppAdded_001 start."); + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + amsProcessOptimizer->appLru_.clear(); + amsProcessOptimizer->OnAppAdded(nullptr); + EXPECT_TRUE(amsProcessOptimizer->appLru_.size() == 0); + + APP_LOGD("AmsProcessOptimizerTest_OnAppAdded_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppAdded + * FunctionPoints: add application in appLru_ + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function OnAppAdded adds app to appLru_ + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_OnAppAdded_002, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_OnAppAdded_002 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + amsProcessOptimizer->appLru_.clear(); + amsProcessOptimizer->OnAppAdded(app); + EXPECT_TRUE(amsProcessOptimizer->appLru_.size() > 0); + + APP_LOGD("AmsProcessOptimizerTest_OnAppAdded_002 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppRemoved + * FunctionPoints: remove application from appLru_ + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function OnAppRemoved can check the invalid app + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_OnAppRemoved_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_OnAppRemoved_001 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + amsProcessOptimizer->appLru_.clear(); + amsProcessOptimizer->appLru_.push_front(app); + amsProcessOptimizer->OnAppRemoved(nullptr); + EXPECT_TRUE(amsProcessOptimizer->appLru_.size() > 0); + + APP_LOGD("AmsProcessOptimizerTest_OnAppRemoved_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppRemoved + * FunctionPoints: remove application from appLru_ + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify whether the function OnAppRemoved removes the app in appLru_ + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_OnAppRemoved_002, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_OnAppRemoved_002 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + amsProcessOptimizer->appLru_.clear(); + amsProcessOptimizer->appLru_.push_front(app); + amsProcessOptimizer->OnAppRemoved(app); + EXPECT_TRUE(amsProcessOptimizer->appLru_.size() == 0); + + APP_LOGD("AmsProcessOptimizerTest_OnAppRemoved_002 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppStateChanged + * FunctionPoints: change application state + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify whether the function OnAppStateChanged moves app2 in appLru_ to the head + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_OnAppStateChanged_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_OnAppStateChanged_001 start."); + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto app1 = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app1->GetPriorityObject()->SetPid(11); + auto app2 = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app2->GetPriorityObject()->SetPid(22); + auto app3 = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app3->GetPriorityObject()->SetPid(33); + amsProcessOptimizer->appLru_.clear(); + amsProcessOptimizer->appLru_.push_back(app1); + amsProcessOptimizer->appLru_.push_back(app2); + amsProcessOptimizer->appLru_.push_back(app3); + app2->SetState(ApplicationState::APP_STATE_FOREGROUND); + amsProcessOptimizer->OnAppStateChanged(app2, ApplicationState::APP_STATE_BEGIN); + EXPECT_TRUE(app2 == amsProcessOptimizer->appLru_.front()); + + APP_LOGD("AmsProcessOptimizerTest_OnAppStateChanged_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppOomAdj + * FunctionPoints: set application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetAppOomAdj can check the invalid app + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppOomAdj_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_001 start."); + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + int oomAdj = 1; + EXPECT_EQ(false, amsProcessOptimizer->SetAppOomAdj(nullptr, oomAdj)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppOomAdj + * FunctionPoints: set application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetAppOomAdj can check the invalid oomAdj + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppOomAdj_002, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_002 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + int oomAdj = 1100; + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + EXPECT_EQ(false, amsProcessOptimizer->SetAppOomAdj(app, oomAdj)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_002 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppOomAdj + * FunctionPoints: set application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetAppOomAdj can check the invalid lmksClient_ + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppOomAdj_003, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_003 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + std::unique_ptr amsProcessOptimizer = std::make_unique(nullptr); + int oomAdj = 1; + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + EXPECT_EQ(false, amsProcessOptimizer->SetAppOomAdj(app, oomAdj)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_003 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppOomAdj + * FunctionPoints: set application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Oom adj has no change in the verification function SetAppOomAdj + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppOomAdj_004, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_004 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + int oomAdj = 1; + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + auto priorityObject = app->GetPriorityObject(); + EXPECT_TRUE(priorityObject != nullptr); + priorityObject->SetCurAdj(oomAdj); + EXPECT_EQ(true, amsProcessOptimizer->SetAppOomAdj(app, oomAdj)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_004 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppOomAdj + * FunctionPoints: set application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function SetAppOomAdj is executed normally + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppOomAdj_005, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_005 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + int oomAdj = 1; + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + EXPECT_EQ(true, amsProcessOptimizer->SetAppOomAdj(app, oomAdj)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppOomAdj_005 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppSchedPolicy + * FunctionPoints: set the application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function SetAppSchedPolicy can check the invalid app + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppSchedPolicy_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_001 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + EXPECT_EQ( + false, amsProcessOptimizer->SetAppSchedPolicy(nullptr, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppSchedPolicy + * FunctionPoints: set the application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the incoming SchedPolicy is the same as before + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppSchedPolicy_002, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_002 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetCurCgroup(CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND); + EXPECT_EQ(true, amsProcessOptimizer->SetAppSchedPolicy(app, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_002 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppSchedPolicy + * FunctionPoints: set the application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the incoming SchedPolicy is equal to CgroupManager::SCHED_POLICY_FREEZED + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppSchedPolicy_003, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_003 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + EXPECT_EQ(true, amsProcessOptimizer->SetAppSchedPolicy(app, CgroupManager::SchedPolicy::SCHED_POLICY_FREEZED)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_003 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: SetAppSchedPolicy + * FunctionPoints: set the application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the old SchedPolicy is equal to CgroupManager::SCHED_POLICY_FREEZED + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_SetAppSchedPolicy_004, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_004 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetCurCgroup(CgroupManager::SchedPolicy::SCHED_POLICY_FREEZED); + EXPECT_EQ(true, amsProcessOptimizer->SetAppSchedPolicy(app, CgroupManager::SchedPolicy::SCHED_POLICY_BACKGROUND)); + + APP_LOGD("AmsProcessOptimizerTest_SetAppSchedPolicy_004 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnLowMemoryAlert + * FunctionPoints: processing when low memory + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the OnLowMemoryAlert function will remove the app in appLru_ when the pid is less than + * zero + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_OnLowMemoryAlert_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_OnLowMemoryAlert_001 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + auto priorityObject = app->GetPriorityObject(); + amsProcessOptimizer->appLru_.clear(); + amsProcessOptimizer->appLru_.push_back(app); + priorityObject->SetPid(-1); + amsProcessOptimizer->OnLowMemoryAlert(CgroupManager::LowMemoryLevel::LOW_MEMORY_LEVEL_CRITICAL); + EXPECT_TRUE(amsProcessOptimizer->appLru_.size() == 0); + + APP_LOGD("AmsProcessOptimizerTest_OnLowMemoryAlert_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppOomAdj + * FunctionPoints: update application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function UpdateAppOomAdj can check the invalid app + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppOomAdj_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_001 start."); + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + EXPECT_EQ(false, amsProcessOptimizer->UpdateAppOomAdj(nullptr)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppOomAdj + * FunctionPoints: update application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function UpdateAppOomAdj can check the invalid state + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppOomAdj_002, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_002 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_FOREGROUND); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetCurAdj(0); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppOomAdj(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_002 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppOomAdj + * FunctionPoints: update application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function UpdateAppOomAdj can check the invalid state + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppOomAdj_003, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_003 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_CREATE); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetCurAdj(0); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppOomAdj(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_003 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppOomAdj + * FunctionPoints: update application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function UpdateAppOomAdj can check the invalid state + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppOomAdj_004, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_004 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_READY); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetCurAdj(0); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppOomAdj(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_004 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppOomAdj + * FunctionPoints: update application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check the execution of the UpdateAppOomAdj function when the state is normal + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppOomAdj_005, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_005 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_BACKGROUND); + amsProcessOptimizer->appLru_.push_back(app); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppOomAdj(app)); + auto priorityObject = app->GetPriorityObject(); + auto curAdj = priorityObject->GetCurAdj(); + EXPECT_TRUE(curAdj == APP_OOM_ADJ_BACKGROUND_MIN); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_005 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppOomAdj + * FunctionPoints: update application OOM adjustment + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check the execution of the UpdateAppOomAdj function when the state is normal + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppOomAdj_006, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_006 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_SUSPENDED); + amsProcessOptimizer->appLru_.push_back(app); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppOomAdj(app)); + auto priorityObject = app->GetPriorityObject(); + auto curAdj = priorityObject->GetCurAdj(); + EXPECT_TRUE(curAdj == APP_OOM_ADJ_SUSPEND_MIN); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppOomAdj_006 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppSchedPolicy + * FunctionPoints: update application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify the function UpdateAppSchedPolicy can check the invalid app + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppSchedPolicy_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_001 start."); + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + EXPECT_EQ(false, amsProcessOptimizer->UpdateAppSchedPolicy(nullptr)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppSchedPolicy + * FunctionPoints: update application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the case ApplicationState::APP_STATE_CREATE in the switch case can be executed + * correctly + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppSchedPolicy_002, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_002 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_CREATE); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppSchedPolicy(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_002 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppSchedPolicy + * FunctionPoints: update application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the case ApplicationState::APP_STATE_READY in the switch case can be executed + * correctly + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppSchedPolicy_003, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_003 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_READY); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppSchedPolicy(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_003 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppSchedPolicy + * FunctionPoints: update application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the case ApplicationState::APP_STATE_FOREGROUND in the switch case can be executed + * correctly + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppSchedPolicy_004, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_004 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_FOREGROUND); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppSchedPolicy(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_004 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppSchedPolicy + * FunctionPoints: update application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the case ApplicationState::APP_STATE_BACKGROUND in the switch case can be executed + * correctly + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppSchedPolicy_005, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_005 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_BACKGROUND); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppSchedPolicy(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_005 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppSchedPolicy + * FunctionPoints: update application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the case ApplicationState::APP_STATE_SUSPENDED in the switch case can be executed + * correctly + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppSchedPolicy_006, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_006 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_SUSPENDED); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppSchedPolicy(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_006 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: UpdateAppSchedPolicy + * FunctionPoints: update application SchedPolicy + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Check whether the default in switch case can be executed correctly + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_UpdateAppSchedPolicy_007, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_007 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_END); + EXPECT_EQ(true, amsProcessOptimizer->UpdateAppSchedPolicy(app)); + + APP_LOGD("AmsProcessOptimizerTest_UpdateAppSchedPolicy_007 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: StartAppSuspendTimer + * FunctionPoints: start application SuspendTimer + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function StartAppSuspendTimer can work normally. + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_StartAppSuspendTimer_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_StartAppSuspendTimer_001 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = + std::make_unique(lmksClient, APP_SUSPEND_TIMEOUT_DEFAULT); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + amsProcessOptimizer->eventHandler_ = std::make_shared(EventRunner::Create()); + EXPECT_TRUE(amsProcessOptimizer->eventHandler_ != nullptr); + amsProcessOptimizer->suspendTimers_.clear(); + amsProcessOptimizer->StartAppSuspendTimer(app); + EXPECT_TRUE(amsProcessOptimizer->suspendTimers_.size() > 0); + usleep(APP_USLEEP); + EXPECT_TRUE(amsProcessOptimizer->suspendTimers_.size() == 0); + amsProcessOptimizer->eventHandler_ = nullptr; + + APP_LOGD("AmsProcessOptimizerTest_StartAppSuspendTimer_001 end."); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: StopAppSuspendTimer + * FunctionPoints: stop application SuspendTimer + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify that the function StopAppSuspendTimer can work normally. + */ +HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_StopAppSuspendTimer_001, TestSize.Level1) +{ + APP_LOGD("AmsProcessOptimizerTest_StopAppSuspendTimer_001 start."); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto lmksClient = std::make_shared(); + std::unique_ptr amsProcessOptimizer = std::make_unique(lmksClient); + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + amsProcessOptimizer->eventHandler_ = std::make_shared(EventRunner::Create()); + EXPECT_TRUE(amsProcessOptimizer->eventHandler_ != nullptr); + amsProcessOptimizer->suspendTimers_.clear(); + auto timerName = amsProcessOptimizer->GetAppSuspendTimerName(app); + amsProcessOptimizer->suspendTimers_.emplace(timerName); + amsProcessOptimizer->StopAppSuspendTimer(app); + auto it = amsProcessOptimizer->suspendTimers_.find(timerName); + EXPECT_TRUE(it == amsProcessOptimizer->suspendTimers_.end()); + + APP_LOGD("AmsProcessOptimizerTest_StopAppSuspendTimer_001 end."); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn b/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a17a31a6b851f928f0b64745e64952f5aeb72f85 --- /dev/null +++ b/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" +ohos_unittest("AmsRecentAppListTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_lifecycle_deal.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_process_manager.cpp", + "${services_path}/appmgr/src/app_running_manager.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/src/cgroup_manager.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/module_running_record.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + "${services_path}/appmgr/src/process_optimizer_uba.cpp", + "${services_path}/appmgr/src/remote_client_manager.cpp", + "${services_path}/appmgr/test/mock/src/mock_bundle_manager.cpp", + ] + + sources += [ "ams_recent_app_list_test.cpp" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + + deps = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsRecentAppListTest" ] +} diff --git a/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp b/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fda095275ba9996b2923ee44bfaf40d380ca9e48 --- /dev/null +++ b/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp @@ -0,0 +1,419 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_running_record.h" +#include "app_mgr_service_inner.h" +#undef private + +#include +#include +#include "iremote_object.h" +#include "refbase.h" +#include "mock_bundle_manager.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t INDEX_NUM_1 = 1; +const int32_t INDEX_NUM_2 = 2; +const int32_t INDEX_NUM_3 = 3; +const int32_t PID_MAX = 0x8000; +} // namespace +class AmsRecentAppListTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + const std::shared_ptr GetAbilityInfoByIndex(const int32_t index) const; + const std::shared_ptr GetApplicationByIndex(const int32_t index) const; + const std::shared_ptr GetAppRunningRecordByIndex(const int32_t index) const; + void StartProcessSuccess(const int32_t index) const; + + std::unique_ptr serviceInner_; + sptr mockToken_; + sptr mockBundleMgr; +}; + +void AmsRecentAppListTest::SetUpTestCase() +{} + +void AmsRecentAppListTest::TearDownTestCase() +{} + +void AmsRecentAppListTest::SetUp() +{ + serviceInner_.reset(new (std::nothrow) AppMgrServiceInner()); + mockBundleMgr = new (std::nothrow) BundleMgrService(); + serviceInner_->SetBundleManager(mockBundleMgr); +} + +void AmsRecentAppListTest::TearDown() +{} + +const std::shared_ptr AmsRecentAppListTest::GetAbilityInfoByIndex(const int32_t index) const +{ + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "test_ability" + std::to_string(index); + abilityInfo->applicationName = "com.ohos.test.helloworld" + std::to_string(index); + abilityInfo->applicationInfo.bundleName = "com.ohos.test.helloworld" + std::to_string(index); + return abilityInfo; +} + +const std::shared_ptr AmsRecentAppListTest::GetApplicationByIndex(const int32_t index) const +{ + std::shared_ptr appInfo = std::make_shared(); + appInfo->name = "com.ohos.test.helloworld" + std::to_string(index); + appInfo->bundleName = "com.ohos.test.helloworld" + std::to_string(index); + return appInfo; +} + +const std::shared_ptr AmsRecentAppListTest::GetAppRunningRecordByIndex(const int32_t index) const +{ + auto appInfo = GetApplicationByIndex(index); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, appInfo->uid, bundleInfo); + + EXPECT_NE(nullptr, appRecord); + return appRecord; +} + +void AmsRecentAppListTest::StartProcessSuccess(const int32_t index) const +{ + pid_t pid = PID_MAX - index; + auto abilityInfo = GetAbilityInfoByIndex(index); + auto appInfo = GetApplicationByIndex(index); + sptr token = new (std::nothrow) MockAbilityToken(); + MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtr); + + // mock start process success, and pid is right. + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + return; +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: create + * FunctionPoints: Add app to RecentAppList when start a new process success. + * EnvConditions: RecentAppList is empty. + * CaseDescription: Verity ams can add app to RecentAppList success when start a new process success. + */ +HWTEST_F(AmsRecentAppListTest, Create_001, TestSize.Level1) +{ + // get the recent app list before test. + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + + for (int32_t index = INDEX_NUM_1; index <= INDEX_NUM_3; index++) { + StartProcessSuccess(index); + EXPECT_EQ(index, static_cast(serviceInner_->GetRecentAppList().size())); + } +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: create + * FunctionPoints: The size of RecentAppList remains the same when start a new process failed. + * EnvConditions: RecentAppList is empty. + * CaseDescription: Verity ams can not add app to RecentAppList when start a new process failed. + */ +HWTEST_F(AmsRecentAppListTest, Create_002, TestSize.Level1) +{ + auto abilityInfo = GetAbilityInfoByIndex(1); + auto appInfo = GetApplicationByIndex(INDEX_NUM_1); + sptr token = new (std::nothrow) MockAbilityToken(); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + + // mock start process failed. + MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtr); + + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).WillOnce(Return(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED)); + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: create + * FunctionPoints: The size of RecentAppList remains the same when start an already exist process. + * EnvConditions: RecentAppList is empty. + * CaseDescription: Verity ams can not add app to RecentAppList when start an already exist process. + */ +HWTEST_F(AmsRecentAppListTest, Create_003, TestSize.Level1) +{ + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + + pid_t pid = INDEX_NUM_1; + auto abilityInfo = GetAbilityInfoByIndex(INDEX_NUM_1); + auto appInfo = GetApplicationByIndex(INDEX_NUM_1); + sptr token = new (std::nothrow) MockAbilityToken(); + MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtr); + + // mock start process success, and pid is right. + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + + // Load ability1, start process 1 again. + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: update + * FunctionPoints: Remove app from RecentAppList when app terminated. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can remove app from RecentAppList when app terminated. + */ +HWTEST_F(AmsRecentAppListTest, Update_001, TestSize.Level1) +{ + StartProcessSuccess(INDEX_NUM_1); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + serviceInner_->ApplicationTerminated(appRecord->GetRecordId()); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: update + * FunctionPoints: Remove app from RecentAppList when app died. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can remove app from RecentAppList when app died. + */ +HWTEST_F(AmsRecentAppListTest, Update_002, TestSize.Level1) +{ + StartProcessSuccess(INDEX_NUM_1); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); + + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + sptr object = client->AsObject(); + wptr app = object; + serviceInner_->OnRemoteDied(app); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: update + * FunctionPoints: Push app front. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can push app front when app is foregrounded. + */ +HWTEST_F(AmsRecentAppListTest, Update_003, TestSize.Level1) +{ + for (int32_t index = INDEX_NUM_1; index <= INDEX_NUM_3; index++) { + StartProcessSuccess(index); + EXPECT_EQ(index, static_cast(serviceInner_->GetRecentAppList().size())); + } + + for (int32_t index = INDEX_NUM_1; index <= INDEX_NUM_3; index++) { + auto appRecord = GetAppRunningRecordByIndex(index); + serviceInner_->ApplicationForegrounded(appRecord->GetRecordId()); + auto appTaskInfo = serviceInner_->GetRecentAppList().front(); + EXPECT_NE(nullptr, appTaskInfo); + EXPECT_EQ(appRecord->GetRecordId(), appTaskInfo->GetRecordId()); + } +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: remove + * FunctionPoints: Remove app from RecentAppList. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can remove app from RecentAppList when call RemoveAppFromRecentList. + */ +HWTEST_F(AmsRecentAppListTest, Remove_001, TestSize.Level1) +{ + StartProcessSuccess(INDEX_NUM_1); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + auto appInfo = GetApplicationByIndex(INDEX_NUM_1); + + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); + appRecord->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + + serviceInner_->RemoveAppFromRecentList(appInfo->name, appInfo->bundleName); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: remove + * FunctionPoints: Remove app from RecentAppList. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can not remove app from RecentAppList when app name is not correct. + */ +HWTEST_F(AmsRecentAppListTest, Remove_002, TestSize.Level1) +{ + StartProcessSuccess(INDEX_NUM_1); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + + auto appInfo = GetApplicationByIndex(INDEX_NUM_2); + serviceInner_->RemoveAppFromRecentList(appInfo->name, appInfo->bundleName); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: remove + * FunctionPoints: Remove app from RecentAppList. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can not remove app from RecentAppList when app name is empty. + */ +HWTEST_F(AmsRecentAppListTest, Remove_003, TestSize.Level1) +{ + StartProcessSuccess(INDEX_NUM_1); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + + serviceInner_->RemoveAppFromRecentList("", ""); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: clear + * FunctionPoints: Clear RecentAppList. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can clear RecentAppList when call ClearRecentAppList. + */ +HWTEST_F(AmsRecentAppListTest, Clear_001, TestSize.Level1) +{ + StartProcessSuccess(INDEX_NUM_1); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); + appRecord->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + + serviceInner_->ClearRecentAppList(); + EXPECT_TRUE(!serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: clear + * FunctionPoints: Clear RecentAppList. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can clear RecentAppList when RecentAppList is empty. + */ +HWTEST_F(AmsRecentAppListTest, Clear_002, TestSize.Level1) +{ + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + serviceInner_->ClearRecentAppList(); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: RecentAppList + * SubFunction: Add + * FunctionPoints: Add RecentAppList. + * EnvConditions: RecentAppList has application. + * CaseDescription: Verity ams can Add RecentAppList when RecentAppList is empty. + */ +HWTEST_F(AmsRecentAppListTest, RecentAppList_001, TestSize.Level1) +{ + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + pid_t pid = INDEX_NUM_1; + auto abilityInfo = GetAbilityInfoByIndex(INDEX_NUM_1); + auto appInfo = GetApplicationByIndex(INDEX_NUM_1); + sptr token = new (std::nothrow) MockAbilityToken(); + MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtr); + + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); + serviceInner_->AddAppDeathRecipient(pid, nullptr); + EXPECT_EQ(nullptr, appRecord->appDeathRecipient_); +} + +/* + * Feature: Ams + * Function: PushAppFront + * SubFunction: PushAppFront + * FunctionPoints: PushAppFront. + * EnvConditions: app has application. + * CaseDescription: Verity ams can PushAppFront when App is not empty. + */ +HWTEST_F(AmsRecentAppListTest, PushAppFront_001, TestSize.Level1) +{ + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + pid_t pid = INDEX_NUM_1; + auto abilityInfo = GetAbilityInfoByIndex(INDEX_NUM_1); + auto appInfo = GetApplicationByIndex(INDEX_NUM_1); + sptr token = new (std::nothrow) MockAbilityToken(); + MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtr); + + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); + serviceInner_->PushAppFront(appRecord->GetRecordId()); + EXPECT_NE(nullptr, serviceInner_->GetAppTaskInfoById(appRecord->GetRecordId())); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..48bbb035ac3a00f4ed7bb5e97252d64ac118b46a --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsServiceAppSpawnClientTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/services/appmgr/test/mock/include", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + defines = [ "usleep(time) = MockSleep(time)" ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", + "${services_path}/appmgr/src/app_mgr_service.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + ] + + sources += [ "ams_service_app_spawn_client_test.cpp" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/appmgr:libams", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsServiceAppSpawnClientTest" ] +} diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_client_test/ams_service_app_spawn_client_test.cpp b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/ams_service_app_spawn_client_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba1743cb5887b6f76613e7bd33e86b488b796aad --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/ams_service_app_spawn_client_test.cpp @@ -0,0 +1,748 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#define protected public +#include "app_mgr_service.h" +#undef private +#undef protected +#include +#include "securec.h" +#include "app_log_wrapper.h" +#include "mock_app_spawn_socket.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using testing::_; +using testing::AtLeast; +using testing::InSequence; +using testing::Invoke; +using testing::Return; + +// keep same with app_spawn_client.cpp +const int32_t CONNECT_RETRY_MAX_TIMES = 15; + +// this function is only used to mock sleep method so ut can run without delay. +int MockSleep([[maybe_unused]] uint32_t seconds) +{ + return 0; +} + +class AppMgrServiceInnerMock : public AppMgrServiceInner { +public: + AppMgrServiceInnerMock() + : socket_(std::make_shared()), appSpawnClient_(std::make_unique()) + { + appSpawnClient_->SetSocket(socket_); + } + + ~AppMgrServiceInnerMock() + {} + + virtual ErrCode OpenAppSpawnConnection() override + { + if (appSpawnClient_.get() != nullptr) { + return appSpawnClient_->OpenConnection(); + } + return -1; + } + + virtual SpawnConnectionState QueryAppSpawnConnectionState() const override + { + if (appSpawnClient_) { + return appSpawnClient_->QueryConnectionState(); + } + return SpawnConnectionState::STATE_NOT_CONNECT; + } + + void CloseAppSpawnConnection() const override + { + if (appSpawnClient_) { + appSpawnClient_->CloseConnection(); + } + } + + const std::shared_ptr &GetSocket() const + { + return socket_; + } + +private: + std::shared_ptr socket_; + std::unique_ptr appSpawnClient_; +}; + +class AmsServiceAppSpawnClientTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsServiceAppSpawnClientTest::SetUpTestCase() +{} + +void AmsServiceAppSpawnClientTest::TearDownTestCase() +{} + +void AmsServiceAppSpawnClientTest::SetUp() +{} + +void AmsServiceAppSpawnClientTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: Create AppSpawnClient and connect to AppSpawnDaemon in AppMgrService_001 + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrService act normal when create appspawnclient and connect to AppSpawnDaemon + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_001, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_001 start"); + std::shared_ptr appMgrService = std::make_shared(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_CALL(*(innerService->GetSocket()), OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + appMgrService->OnStart(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_CALL(*(innerService->GetSocket()), CloseAppSpawnConnection()).Times(1); + appMgrService->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + APP_LOGI("ams_service_app_spawn_client_001 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: Create AppSpawnClient and connect to AppSpawnDaemon in AppMgrService_002 + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrService act normal when create appspawnclient and failed connect to AppSpawnDaemon + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_002, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_002 start"); + std::shared_ptr appMgrService = std::make_shared(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_CALL(*(innerService->GetSocket()), OpenAppSpawnConnection()) + .WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + appMgrService->OnStart(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECT_FAILED, appMgrService->QueryServiceState().connectionState); + appMgrService->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + APP_LOGI("ams_service_app_spawn_client_002 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient connect to AppSpawnDaemon_001 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when successfully connect to AppSpawnDaemon + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_003, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_003 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_app_spawn_client_003 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient connect to AppSpawnDaemon_002 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when failed to connect to AppSpawnDaemon + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_004, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_004 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, appSpawnClient->OpenConnection()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECT_FAILED, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_app_spawn_client_004 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_001 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when successfully to send fork request + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_005, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_005 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillOnce(Invoke(socketMock.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t expectPid = 11111; + pid_t newPid = 0; + socketMock->SetExpectPid(expectPid); + appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(expectPid, newPid); + APP_LOGI("ams_service_app_spawn_client_005 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_002 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when failed to connect daemon but reconnect success + * when try to send fork request + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_006, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_006 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, appSpawnClient->OpenConnection()); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillOnce(Invoke(socketMock.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t expectPid = 11111; + pid_t newPid = 0; + socketMock->SetExpectPid(expectPid); + appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(expectPid, newPid); + APP_LOGI("ams_service_app_spawn_client_006 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_003 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when failed to connect daemon and reconnect fail + * when try to send fork request + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_007, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_007 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_007 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_004 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when try to send request without connect but reconnect success + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_008, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_008 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillOnce(Invoke(socketMock.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t expectPid = 11111; + pid_t newPid = 0; + socketMock->SetExpectPid(expectPid); + appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(expectPid, newPid); + APP_LOGI("ams_service_app_spawn_client_008 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_005 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when try to send request without connect and reconnect failed + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_009, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_009 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_009 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_006 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when failed to send message to AppSpawnDaemon + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_010, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_010 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillRepeatedly(Return(ERR_APPEXECFWK_SOCKET_WRITE_FAILED)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_SOCKET_WRITE_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_010 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_007 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when failed to read message from AppSpawnDaemon + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_011, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_011 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillRepeatedly(Return(ERR_APPEXECFWK_SOCKET_READ_FAILED)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_SOCKET_READ_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_011 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_008 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when pass invalid param procName(empty) + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_012, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_012 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "", "soPath"}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_012 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_011 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when pass invalid param soPath(empty) + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_013, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_013 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + + appSpawnClient->SetSocket(socketMock); + + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "", ""}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_013 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_012 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when pass invalid param procName(oversize) + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_014, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_014 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + std::string invalidParam = "invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid\ + invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid\ + invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid\ + invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid"; + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, invalidParam, "soPath"}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_014 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient request new process_015 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient act normal when pass invalid param soPath(oversize) + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_015, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_015 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + std::string invalidParam = "invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid\ + invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid\ + invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid\ + invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid"; + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", invalidParam}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED, result); + APP_LOGI("ams_service_app_spawn_client_015 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient close connection with AppSpawnDaemon_001 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient CloseConnection act normal after OpenConnection + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_016, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_016 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_app_spawn_client_016 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient close connection with AppSpawnDaemon_002 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient CloseConnection act normal without OpenConnection + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_017, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_017 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_app_spawn_client_017 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient close connection with AppSpawnDaemon_003 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient CloseConnection act normal when OpenConnection failed + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_018, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_018 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, appSpawnClient->OpenConnection()); + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_app_spawn_client_018 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: AppSpawnClient + * FunctionPoints: AppSpawnClient close connection with AppSpawnDaemon_004 + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if after close connection with appspawn, appspawnclient startprocess + * will invoke openconnection. + */ +HWTEST_F(AmsServiceAppSpawnClientTest, AppSpawnClient_019, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_client_019 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + appSpawnClient->CloseConnection(); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillOnce(Invoke(socketMock.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t expectPid = 11111; + pid_t newPid = 0; + socketMock->SetExpectPid(expectPid); + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(expectPid, newPid); + EXPECT_EQ(ERR_OK, result); + APP_LOGI("ams_service_app_spawn_client_019 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: ReConnectAppSpawn + * FunctionPoints: Test AppSpawnClient reconnect functions. + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient first time connection fail, but second time is success. + */ +HWTEST_F(AmsServiceAppSpawnClientTest, ReConnectAppSpawn_001, TestSize.Level1) +{ + APP_LOGI("ams_service_reconnect_app_spawn_001 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()) + .WillOnce(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)) + .WillOnce(Return(ERR_OK)); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_reconnect_app_spawn_001 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: ReConnectAppSpawn + * FunctionPoints: Test AppSpawnClient reconnect functions. + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient first n time connection fail, but last time is success. + */ +HWTEST_F(AmsServiceAppSpawnClientTest, ReConnectAppSpawn_002, TestSize.Level1) +{ + APP_LOGI("ams_service_reconnect_app_spawn_002 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + InSequence seq; + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()) + .Times(CONNECT_RETRY_MAX_TIMES) + .WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)) + .RetiresOnSaturation(); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_reconnect_app_spawn_002 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: ReConnectAppSpawn + * FunctionPoints: Test AppSpawnClient reconnect functions. + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient all (n+1) times connection fail. + */ +HWTEST_F(AmsServiceAppSpawnClientTest, ReConnectAppSpawn_003, TestSize.Level1) +{ + APP_LOGI("ams_service_reconnect_app_spawn_003 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()) + .Times(CONNECT_RETRY_MAX_TIMES + 1) + .WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, appSpawnClient->OpenConnection()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECT_FAILED, appSpawnClient->QueryConnectionState()); + APP_LOGI("ams_service_reconnect_app_spawn_003 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: ReConnectAppSpawn + * FunctionPoints: Test AppSpawnClient reconnect functions. + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient first time start process fail, but second time is success. + */ +HWTEST_F(AmsServiceAppSpawnClientTest, ReConnectAppSpawn_004, TestSize.Level1) +{ + APP_LOGI("ams_service_reconnect_app_spawn_004 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)) + .WillOnce(Return(ERR_APPEXECFWK_SOCKET_READ_FAILED)) + .WillOnce(Invoke(socketMock.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t expectPid = 11111; + pid_t newPid = 0; + socketMock->SetExpectPid(expectPid); + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(expectPid, newPid); + EXPECT_EQ(ERR_OK, result); + APP_LOGI("ams_service_reconnect_app_spawn_004 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: ReConnectAppSpawn + * FunctionPoints: Test AppSpawnClient reconnect functions. + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient first n time start process fail, but last time is success. + */ +HWTEST_F(AmsServiceAppSpawnClientTest, ReConnectAppSpawn_005, TestSize.Level1) +{ + APP_LOGI("ams_service_reconnect_app_spawn_005 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + InSequence seq; + for (int i = 0; i < CONNECT_RETRY_MAX_TIMES; i++) { + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillOnce(Return(ERR_APPEXECFWK_SOCKET_READ_FAILED)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + } + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillOnce(Invoke(socketMock.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(1); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t expectPid = 11111; + pid_t newPid = 0; + socketMock->SetExpectPid(expectPid); + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(expectPid, newPid); + EXPECT_EQ(ERR_OK, result); + APP_LOGI("ams_service_reconnect_app_spawn_005 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: ReConnectAppSpawn + * FunctionPoints: Test AppSpawnClient reconnect functions. + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if AppSpawnClient all(n+1) times start process fail. + */ +HWTEST_F(AmsServiceAppSpawnClientTest, ReConnectAppSpawn_006, TestSize.Level1) +{ + APP_LOGI("ams_service_reconnect_app_spawn_006 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr socketMock = std::make_shared(); + appSpawnClient->SetSocket(socketMock); + EXPECT_CALL(*socketMock, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*socketMock, ReadMessage(_, _)).WillRepeatedly(Return(ERR_APPEXECFWK_SOCKET_READ_FAILED)); + EXPECT_CALL(*socketMock, CloseAppSpawnConnection()).Times(AtLeast(1)); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + pid_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_SOCKET_READ_FAILED, result); + APP_LOGI("ams_service_reconnect_app_spawn_006 end"); +} diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e1e8104530a3571f52ef1b9f2eafb59185f731aa --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsServiceAppSpawnMsgWrapperTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + defines = [ "usleep(time) = MockSleep(time)" ] + + sources = [ + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + ] + + sources += [ "ams_service_app_spawn_msg_wrapper_test.cpp" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + + deps = [ + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsServiceAppSpawnMsgWrapperTest" ] +} diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp b/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b331180f84324afbf41c67e0325f7c230895002d --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "app_spawn_msg_wrapper.h" +#include "securec.h" + +using namespace testing::ext; + +// this function is only used to mock sleep method so ut can run without delay. +int MockSleep([[maybe_unused]] uint32_t seconds) +{ + return 0; +} + +namespace OHOS { +namespace AppExecFwk { +class AmsServiceAppSpawnMsgWrapperTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsServiceAppSpawnMsgWrapperTest::SetUpTestCase() +{} + +void AmsServiceAppSpawnMsgWrapperTest::TearDownTestCase() +{} + +void AmsServiceAppSpawnMsgWrapperTest::SetUp() +{} + +void AmsServiceAppSpawnMsgWrapperTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg can check the invalid uid. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_001, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_001 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + + AppSpawnStartMsg params = {10000, 10000, {10001, 10002}, "processName", "soPath"}; + EXPECT_EQ(true, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_001 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg can check the invalid gid. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_002, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_002 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + + AppSpawnStartMsg params = {10000, 10000, {10001, 10002}, "processName", "soPath"}; + EXPECT_EQ(true, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_002 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg can check gid count which exceeds the max limit. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_003, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_003 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + // gids limit, max 64 + AppSpawnStartMsg params = {10000, + 10000, + {10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001, + 10001}, + "processName", + "soPath"}; + EXPECT_EQ(false, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_003 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg can check the process name is empty. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_004, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_004 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + AppSpawnStartMsg params = {10000, 10000, {10001, 10001}, "", "soPath"}; + EXPECT_EQ(false, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_004 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg can check the process name exceeds the max length. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_005, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_005 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + std::string invalid = + "InvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalid" + "InvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInval" + "id" + "InvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInval" + "id"; + AppSpawnStartMsg params = {10000, 10000, {10001, 10001}, invalid, "soPath"}; + EXPECT_EQ(false, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_005 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg can check the so path is empty. + */ + +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_006, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_006 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + AppSpawnStartMsg params = {10000, 10000, {10001, 10001}, "", ""}; + EXPECT_EQ(false, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_006 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg can check the so path exceeds the max length. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_007, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_007 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + std::string invalid = + "InvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalid" + "InvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInval" + "id" + "InvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInvalidInval" + "id"; + AppSpawnStartMsg params = {10000, 10000, {10001, 10001}, "processName", invalid}; + EXPECT_EQ(false, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_007 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: AssembleMsg + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function AssembleMsg check the valid message. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_008, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_008 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + AppSpawnStartMsg params = {10000, 10000, {10001, 10001}, "processName", "soPath"}; + EXPECT_EQ(true, appSpawnMsgWrapper->AssembleMsg(params)); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_008 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: IsValid & GetMsgLength + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if check the message pass, the length and valid value is right. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_009, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_009 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + AppSpawnStartMsg params = {10000, 10000, {10001, 10001}, "processName", "soPath"}; + EXPECT_EQ(true, appSpawnMsgWrapper->AssembleMsg(params)); + EXPECT_EQ(true, appSpawnMsgWrapper->IsValid()); + int32_t lhs = sizeof(AppSpawnMsg); + EXPECT_EQ(lhs, appSpawnMsgWrapper->GetMsgLength()); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_009 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnMsgWrapper + * SubFunction: IsValid & GetMsgLength + * FunctionPoints: check message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if check the message fail, the length and valid value is right. + */ +HWTEST(AmsServiceAppSpawnMsgWrapperTest, AppSpawnMsgWrapper_010, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_msg_wrapper_010 start"); + + std::unique_ptr appSpawnMsgWrapper = std::make_unique(); + AppSpawnStartMsg params = {10000, 10000, {10001, 10001}, "", "soPath"}; + EXPECT_EQ(false, appSpawnMsgWrapper->AssembleMsg(params)); + EXPECT_EQ(false, appSpawnMsgWrapper->IsValid()); + int32_t lhs = 0; + EXPECT_EQ(lhs, appSpawnMsgWrapper->GetMsgLength()); + + APP_LOGI("ams_service_app_spawn_msg_wrapper_010 end"); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..181f09bee1070c8d17b6ecd10d1481bdb1b716d1 --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsServiceAppSpawnSocketTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/startup/appspawn_standard/test/mock/include", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + defines = [ "usleep(time) = MockSleep(time)" ] + + sources = [ "${services_path}/appmgr/src/app_spawn_socket.cpp" ] + + sources += [ "ams_service_app_spawn_socket_test.cpp" ] + + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsServiceAppSpawnSocketTest" ] +} diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp b/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b7f75bc09d6cafe7b7cba0401be19849eb105df --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp @@ -0,0 +1,373 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "app_spawn_socket.h" +#include "mock_client_socket.h" +#include "securec.h" + +using namespace testing::ext; +using namespace OHOS; +using testing::_; +using testing::AtLeast; +using testing::InSequence; +using testing::Invoke; +using testing::Return; + +// this function is only used to mock sleep method so ut can run without delay. +int MockSleep([[maybe_unused]] uint32_t seconds) +{ + return 0; +} + +namespace OHOS { +namespace AppExecFwk { +class AmsServiceAppSpawnSocketTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsServiceAppSpawnSocketTest::SetUpTestCase() +{} + +void AmsServiceAppSpawnSocketTest::TearDownTestCase() +{} + +void AmsServiceAppSpawnSocketTest::SetUp() +{} + +void AmsServiceAppSpawnSocketTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: OpenAppSpawnConnection + * FunctionPoints: open connection + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if create client socket fail, open connection error. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_001, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_001 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_CALL(*mockClientSocket, CreateClient()).WillOnce(Return(-1)); + EXPECT_EQ(ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT, appSpawnSocket->OpenAppSpawnConnection()); + + APP_LOGI("ams_service_app_spawn_socket_001 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: OpenAppSpawnConnection + * FunctionPoints: open connection + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify if connect socket client fail, open connection error. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_002, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_002 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_CALL(*mockClientSocket, CreateClient()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockClientSocket, ConnectSocket()).WillOnce(Return(-1)); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, appSpawnSocket->OpenAppSpawnConnection()); + + APP_LOGI("ams_service_app_spawn_socket_002 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: OpenAppSpawnConnection + * FunctionPoints: open connection + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function OpenAppSpawnConnection open connection success. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_003, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_003 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_CALL(*mockClientSocket, CreateClient()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockClientSocket, ConnectSocket()).WillOnce(Return(ERR_OK)); + EXPECT_EQ(ERR_OK, appSpawnSocket->OpenAppSpawnConnection()); + + APP_LOGI("ams_service_app_spawn_socket_003 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: ReadMessage + * FunctionPoints: check params + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function ReadMessage can check the invalid buffer point. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_004, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_004 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = nullptr; + int32_t len = 10; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_EQ(ERR_INVALID_VALUE, appSpawnSocket->ReadMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_004 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: ReadMessage + * FunctionPoints: check params + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function ReadMessage can check the buffer length is 0. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_005, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_005 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = 0; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_EQ(ERR_INVALID_VALUE, appSpawnSocket->ReadMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_005 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: ReadMessage + * FunctionPoints: check params + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function ReadMessage can check the buffer length < 0. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_006, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_006 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = -1; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_EQ(ERR_INVALID_VALUE, appSpawnSocket->ReadMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_006 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: ReadMessage + * FunctionPoints: read message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function ReadMessage can read the valid message. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_007, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_007 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = 10; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_CALL(*mockClientSocket, ReadSocketMessage(_, _)).WillOnce(Return(len)); + EXPECT_EQ(ERR_OK, appSpawnSocket->ReadMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_007 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: ReadMessage + * FunctionPoints: check params + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function ReadMessage can check the message length. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_008, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_008 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = 10; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_CALL(*mockClientSocket, ReadSocketMessage(_, _)).WillOnce(Return(11)); + EXPECT_EQ(ERR_APPEXECFWK_SOCKET_READ_FAILED, appSpawnSocket->ReadMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_008 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: WriteMessage + * FunctionPoints: check params + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function WriteMessage can check the invalid buffer point. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_009, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_009 start"); + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = nullptr; + int32_t len = 10; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_EQ(ERR_INVALID_VALUE, appSpawnSocket->WriteMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_009 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: WriteMessage + * FunctionPoints: check params + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function WriteMessage can check the buffer length is 0. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_010, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_010 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = 0; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_EQ(ERR_INVALID_VALUE, appSpawnSocket->WriteMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_010 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: WriteMessage + * FunctionPoints: check params + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function WriteMessage can check the buffer length < 0. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_011, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_011 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = -1; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_EQ(ERR_INVALID_VALUE, appSpawnSocket->WriteMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_011 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: WriteMessage + * FunctionPoints: write message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function WriteMessage can write valid message. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_012, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_012 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = 10; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_CALL(*mockClientSocket, WriteSocketMessage(_, _)).WillOnce(Return(len)); + EXPECT_EQ(ERR_OK, appSpawnSocket->WriteMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_012 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnSocket + * SubFunction: WriteMessage + * FunctionPoints: write message + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Verify the function WriteMessage can check the message length. + */ +HWTEST(AmsServiceAppSpawnSocketTest, AppSpawnSocket_013, TestSize.Level1) +{ + APP_LOGI("ams_service_app_spawn_socket_013 start"); + + std::shared_ptr mockClientSocket = + std::make_shared(); + std::unique_ptr appSpawnSocket = std::make_unique(); + std::unique_ptr buff = std::make_unique(10); + int32_t len = 10; + + appSpawnSocket->SetClientSocket(mockClientSocket); + EXPECT_CALL(*mockClientSocket, WriteSocketMessage(_, _)).WillOnce(Return(11)); + EXPECT_EQ(ERR_APPEXECFWK_SOCKET_WRITE_FAILED, appSpawnSocket->WriteMessage(buff.get(), len)); + + APP_LOGI("ams_service_app_spawn_socket_013 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a6d93271e42fbe7e8e0d69a0963afd268f5b5975 --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsServiceEventDriveTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/services/appmgr/test/mock/include", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk", + "//utils/native/base/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/services/appmgr/src", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", + "${services_path}/appmgr/src/app_mgr_service.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/src/system_memory_attr.cpp", + ] + + sources += [ "ams_service_event_drive_test.cpp" ] + + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/appmgr:libams", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsServiceEventDriveTest" ] +} diff --git a/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..093b1e7ccb936ef01098e9ff1492f75bf713b2ad --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp @@ -0,0 +1,1020 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function +#define private public +#define protected public +#include "app_mgr_service.h" +#undef private +#undef protected +#include +#include "app_log_wrapper.h" +#include "errors.h" +#include "iremote_object.h" +#include "mock_app_mgr_service_inner.h" +#include"system_environment_information.h" +#include "system_memory_attr.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using OHOS::iface_cast; +using OHOS::IRemoteObject; +using OHOS::sptr; +using testing::_; +using testing::InvokeWithoutArgs; + +class AmsServiceEventDriveTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + std::shared_ptr GetMockAppMgrServiceInner(); + std::shared_ptr GetAmsEventHandler(); + +protected: + std::shared_ptr appMgrService_; +}; + +void AmsServiceEventDriveTest::SetUpTestCase() +{} + +void AmsServiceEventDriveTest::TearDownTestCase() +{} + +void AmsServiceEventDriveTest::SetUp() +{ + appMgrService_ = std::make_shared(); +} + +void AmsServiceEventDriveTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post AttachApplication task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_001, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_001 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + innerService->SetWaitCount(2); + + EXPECT_CALL(*innerService, AddAppDeathRecipient(_, _)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*innerService, AttachApplication(_, _)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + sptr client; + appMgrService_->AttachApplication(client); + innerService->Wait(); + + APP_LOGI("ams_service_event_drive_test_001 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post ApplicationForegrounded task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_002, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_002 start"); + + std::shared_ptr innerService = std::make_shared(); + std::unique_ptr appMgrService = std::make_unique(); + appMgrService->SetInnerService(innerService); + appMgrService->OnStart(); + + EXPECT_CALL(*innerService, ApplicationForegrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService->ApplicationForegrounded(recordId); + innerService->Wait(); + + APP_LOGI("ams_service_event_drive_test_002 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post ApplicationBackgrounded task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_003, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_003 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, ApplicationBackgrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationBackgrounded(recordId); + innerService->Wait(); + + APP_LOGI("ams_service_event_drive_test_003 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post ApplicationTerminated task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_004, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_004 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, ApplicationTerminated(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationTerminated(recordId); + innerService->Wait(); + + APP_LOGI("ams_service_event_drive_test_004 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post AbilityCleaned task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_005, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_005 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, AbilityTerminated(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + sptr token; + appMgrService_->AbilityCleaned(token); + innerService->Wait(); + + APP_LOGI("ams_service_event_drive_test_005 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post ClearUpApplicationData task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_006, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_006 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, ClearUpApplicationData(_, _, _)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + std::string appName = "appName"; + appMgrService_->ClearUpApplicationData(appName); + innerService->Wait(); + + APP_LOGI("ams_service_event_drive_test_006 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post IsBackgroundRunningRestricted task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_007, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_007 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, IsBackgroundRunningRestricted(_)).WillOnce(Return(0)); + + std::string appName = "appName"; + EXPECT_EQ(0, appMgrService_->IsBackgroundRunningRestricted(appName)); + + APP_LOGI("ams_service_event_drive_test_007 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post IsBackgroundRunningRestricted task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_008, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_008 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, GetAllRunningProcesses(_)).WillOnce(Return(0)); + + std::vector runningProcessInfo; + EXPECT_EQ(0, appMgrService_->GetAllRunningProcesses(runningProcessInfo)); + + APP_LOGI("ams_service_event_drive_test_008 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AttachApplication act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_009, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_009 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, AttachApplication(_, _)).Times(0); + + sptr client; + appMgrService_->AttachApplication(client); + + APP_LOGI("ams_service_event_drive_test_009 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ApplicationForegrounded act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_010, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_010 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, ApplicationForegrounded(_)).Times(0); + + int32_t recordId = 0; + appMgrService_->ApplicationForegrounded(recordId); + + APP_LOGI("ams_service_event_drive_test_010 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ApplicationBackgrounded act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_011, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_011 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, ApplicationBackgrounded(_)).Times(0); + + int32_t recordId = 0; + appMgrService_->ApplicationBackgrounded(recordId); + + APP_LOGI("ams_service_event_drive_test_011 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ApplicationTerminated act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_012, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_012 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, ApplicationTerminated(_)).Times(0); + + int32_t recordId = 0; + appMgrService_->ApplicationTerminated(recordId); + + APP_LOGI("ams_service_event_drive_test_012 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AbilityCleaned act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_013, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_013 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, AbilityTerminated(_)).Times(0); + + sptr token; + appMgrService_->AbilityCleaned(token); + + APP_LOGI("ams_service_event_drive_test_013 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ClearUpApplicationData act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_014, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_014 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, ClearUpApplicationData(_, _, _)).Times(0); + + std::string appName = "appName"; + appMgrService_->ClearUpApplicationData(appName); + + APP_LOGI("ams_service_event_drive_test_014 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if IsBackgroundRunningRestricted act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_015, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_015 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + std::string appName = "appName"; + EXPECT_EQ(OHOS::ERR_INVALID_OPERATION, appMgrService_->IsBackgroundRunningRestricted(appName)); + + APP_LOGI("ams_service_event_drive_test_015 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if GetAllRunningProcesses act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_016, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_016 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + std::vector runningProcessInfo; + EXPECT_EQ(OHOS::ERR_INVALID_OPERATION, appMgrService_->GetAllRunningProcesses(runningProcessInfo)); + + APP_LOGI("ams_service_event_drive_test_016 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AttachApplication act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_017, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_017 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, AttachApplication(_, _)).Times(0); + + sptr client; + appMgrService_->AttachApplication(client); + + APP_LOGI("ams_service_event_drive_test_017 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ApplicationForegrounded act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_018, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_018 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, ApplicationForegrounded(_)).Times(0); + + int32_t recordId = 0; + appMgrService_->ApplicationForegrounded(recordId); + + APP_LOGI("ams_service_event_drive_test_018 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ApplicationBackgrounded act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_019, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_019 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, ApplicationBackgrounded(_)).Times(0); + + int32_t recordId = 0; + appMgrService_->ApplicationBackgrounded(recordId); + + APP_LOGI("ams_service_event_drive_test_019 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ApplicationTerminated act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_020, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_020 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, ApplicationTerminated(_)).Times(0); + + int32_t recordId = 0; + appMgrService_->ApplicationTerminated(recordId); + + APP_LOGI("ams_service_event_drive_test_020 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AbilityCleaned act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_021, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_021 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, AbilityTerminated(_)).Times(0); + + sptr token; + appMgrService_->AbilityCleaned(token); + + APP_LOGI("ams_service_event_drive_test_021 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if ClearUpApplicationData act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_022, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_022 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, ClearUpApplicationData(_, _, _)).Times(0); + + std::string appName = "appName"; + appMgrService_->ClearUpApplicationData(appName); + + APP_LOGI("ams_service_event_drive_test_022 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if IsBackgroundRunningRestricted act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_023, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_023 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + std::string appName = "appName"; + EXPECT_EQ(OHOS::ERR_INVALID_OPERATION, appMgrService_->IsBackgroundRunningRestricted(appName)); + + APP_LOGI("ams_service_event_drive_test_023 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if GetAllRunningProcesses act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_024, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_024 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + appMgrService_->SetInnerService(innerService); + + std::vector runningProcessInfo; + EXPECT_EQ(OHOS::ERR_INVALID_OPERATION, appMgrService_->GetAllRunningProcesses(runningProcessInfo)); + + APP_LOGI("ams_service_event_drive_test_024 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post application from background to foreground task act normal + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_025, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_025 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t waitCount = 2; + innerService->SetWaitCount(waitCount); + + EXPECT_CALL(*innerService, ApplicationBackgrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*innerService, ApplicationForegrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationForegrounded(recordId); + innerService->Wait(); + APP_LOGI("ams_service_event_drive_test_025 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post application from foreground to background task act normal + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_026, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_026 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t waitCount = 2; + innerService->SetWaitCount(waitCount); + + EXPECT_CALL(*innerService, ApplicationForegrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*innerService, ApplicationBackgrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + innerService->Wait(); + APP_LOGI("ams_service_event_drive_test_026 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post application from background to terminate task act normal + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_027, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_027 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t waitCount = 2; + innerService->SetWaitCount(waitCount); + + EXPECT_CALL(*innerService, ApplicationBackgrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*innerService, ApplicationTerminated(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + innerService->Wait(); + APP_LOGI("ams_service_event_drive_test_027 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post application from foreground to terminated task act normal + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_028, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_028 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t waitCount = 2; + innerService->SetWaitCount(waitCount); + + EXPECT_CALL(*innerService, ApplicationForegrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*innerService, ApplicationTerminated(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + innerService->Wait(); + APP_LOGI("ams_service_event_drive_test_028 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post application from terminate to foreground task act normal + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_029, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_029 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t waitCount = 2; + innerService->SetWaitCount(waitCount); + + EXPECT_CALL(*innerService, ApplicationTerminated(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*innerService, ApplicationForegrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationForegrounded(recordId); + innerService->Wait(); + APP_LOGI("ams_service_event_drive_test_029 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework. + * CaseDescription: Verify if post application from terminate to background task act normal + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_030, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_030 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t waitCount = 2; + innerService->SetWaitCount(waitCount); + + EXPECT_CALL(*innerService, ApplicationTerminated(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*innerService, ApplicationBackgrounded(_)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + int32_t recordId = 0; + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + innerService->Wait(); + APP_LOGI("ams_service_event_drive_test_030 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if post AddAppDeathRecipient task success + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_034, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_034 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, AddAppDeathRecipient(_, _)) + .WillOnce(InvokeWithoutArgs(innerService.get(), &MockAppMgrServiceInner::Post)); + + pid_t pid = 1; + appMgrService_->AddAppDeathRecipient(pid); + innerService->Wait(); + APP_LOGI("ams_service_event_drive_test_034 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AddAppDeathRecipient act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_035, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_035 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, AddAppDeathRecipient(_, _)).Times(0); + + pid_t pid = 1; + appMgrService_->AddAppDeathRecipient(pid); + + APP_LOGI("ams_service_event_drive_test_035 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AddAppDeathRecipient act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_036, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_036 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, AddAppDeathRecipient(_, _)).Times(0); + + pid_t pid = 1; + appMgrService_->AddAppDeathRecipient(pid); + + APP_LOGI("ams_service_event_drive_test_036 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if QueryServiceState act normal + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_037, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_037 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + + EXPECT_CALL(*innerService, QueryAppSpawnConnectionState()) + .WillRepeatedly(Return(SpawnConnectionState::STATE_CONNECTED)); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService_->QueryServiceState().serviceRunningState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService_->QueryServiceState().connectionState); + + APP_LOGI("ams_service_event_drive_test_037 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if QueryServiceState act normal without initialize AppMgrService + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_038, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_038 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + + EXPECT_CALL(*innerService, QueryAppSpawnConnectionState()).Times(2); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService_->QueryServiceState().serviceRunningState); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService_->QueryServiceState().connectionState); + + APP_LOGI("ams_service_event_drive_test_038 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: EventDrive + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if QueryServiceState act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_039, TestSize.Level1) +{ + APP_LOGI("ams_service_event_drive_test_039 start"); + + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + appMgrService_->OnStop(); + + EXPECT_CALL(*innerService, QueryAppSpawnConnectionState()).Times(2); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService_->QueryServiceState().serviceRunningState); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService_->QueryServiceState().connectionState); + + APP_LOGI("ams_service_event_drive_test_039 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: GetSystemMemoryAttr + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if QueryServiceState act normal after AppMgrService stopped + */ +/* +HWTEST_F(AmsServiceEventDriveTest, EventDrive_040, TestSize.Level1) +{ + APP_LOGI("AppMgrService::EventDrive_040 start 1"); + OHOS::AppExecFwk::SystemMemoryAttr memInfo; + nlohmann::json memJson = { "memoryThreshold", 25 }; + std::string strConfig = memJson.dump(); + + memInfo.availSysMem_ = -1; + memInfo.totalSysMem_ = -1; + memInfo.threshold_ = -1; + + appMgrService_->GetSystemMemoryAttr(memInfo, strConfig); + + EXPECT_NE(-1, memInfo.availSysMem_); + EXPECT_NE(-1, memInfo.totalSysMem_); + EXPECT_NE(-1, memInfo.threshold_); + + APP_LOGI("AppMgrService::EventDrive_040 end"); +} +*/ + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: GetSystemMemoryAttr + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if QueryServiceState act normal after AppMgrService stopped + */ +HWTEST_F(AmsServiceEventDriveTest, EventDrive_041, TestSize.Level1) +{ + APP_LOGI("AppMgrService::EventDrive_041 start"); + OHOS::AppExecFwk::SystemMemoryAttr memInfo; + std::string strConfig; + + memInfo.availSysMem_ = -1; + memInfo.totalSysMem_ = -1; + memInfo.threshold_ = -1; + + appMgrService_->GetSystemMemoryAttr(memInfo, strConfig); + + EXPECT_NE(-1, memInfo.availSysMem_); + EXPECT_NE(-1, memInfo.totalSysMem_); + EXPECT_NE(-1, memInfo.threshold_); + + APP_LOGI("AppMgrService::EventDrive_041 end"); +} diff --git a/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..23f0b68234b8c9d7e3b645b967985730cf4fbee9 --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn @@ -0,0 +1,83 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsServiceLoadAbilityProcessTest") { + module_out_path = module_output_path + + include_dirs = [ + "${services_path}/appmgr/test/unittest/mocks", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_lifecycle_deal.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_process_manager.cpp", + "${services_path}/appmgr/src/app_running_manager.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/src/cgroup_manager.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/module_running_record.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + "${services_path}/appmgr/src/process_optimizer_uba.cpp", + "${services_path}/appmgr/src/remote_client_manager.cpp", + "${services_path}/appmgr/test/mock/src/mock_bundle_manager.cpp", + ] + + sources += [ "ams_service_load_ability_process_test.cpp" ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsServiceLoadAbilityProcessTest" ] +} diff --git a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21b40a10e95fdc5fb213b5df5c9080f36dcc3f07 --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp @@ -0,0 +1,1307 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_mgr_service_inner.h" +#undef private + +#include +#include "gtest/gtest.h" +#include "ability_running_record.h" +#include "app_mgr_service.h" +#include "app_running_record.h" +#include "app_log_wrapper.h" +#include "app_record_id.h" +#include "ability_info.h" +#include "application_info.h" +#include "mock_app_scheduler.h" +#include "mock_bundle_manager.h" +#include "mock_ability_token.h" +#include "mock_app_spawn_client.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; +namespace OHOS { +namespace AppExecFwk { +#define CHECK_POINTER_IS_NULLPTR(object) \ + do { \ + if (object == nullptr) { \ + return; \ + } \ + } while (0) + +class AmsServiceLoadAbilityProcessTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + static const std::string GetTestAppName() + { + return "com.ohos.test.helloworld"; + } + static const std::string GetTestAbilityName() + { + return "test_ability_name"; + } + + std::shared_ptr StartLoadAbility(const sptr &token, + const sptr &preToken, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo, const pid_t newPid) const; + + sptr GetMockToken() const + { + return mock_token_; + } + +protected: + std::unique_ptr service_; + sptr mock_token_; + sptr bundleMgr_; +}; + +void AmsServiceLoadAbilityProcessTest::SetUpTestCase() +{} + +void AmsServiceLoadAbilityProcessTest::TearDownTestCase() +{} + +void AmsServiceLoadAbilityProcessTest::SetUp() +{ + bundleMgr_ = new (std::nothrow) BundleMgrService(); + service_.reset(new (std::nothrow) AppMgrServiceInner()); + mock_token_ = new (std::nothrow) MockAbilityToken(); + if (service_) { + service_->SetBundleManager(bundleMgr_.GetRefPtr()); + } +} + +void AmsServiceLoadAbilityProcessTest::TearDown() +{} + +std::shared_ptr AmsServiceLoadAbilityProcessTest::StartLoadAbility(const sptr &token, + const sptr &preToken, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo, const pid_t newPid) const +{ + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(newPid), Return(ERR_OK))); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, preToken, abilityInfo, appInfo); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, appInfo->uid, bundleInfo); + EXPECT_EQ(record->GetPriorityObject()->GetPid(), newPid); + return record; +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Normal loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_001, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_001 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + sptr token = GetMockToken(); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_001 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Multiple different loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_002 start"); + + EXPECT_TRUE(service_ != nullptr); + service_->ClearRecentAppList(); + + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + appInfo->process = GetTestAppName(); + + const pid_t PID = 1234; + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + + sptr token2 = GetMockToken(); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = "com.ohos.test.special"; + abilityInfo2->process = "com.ohos.test.special"; + abilityInfo2->applicationInfo.bundleName = "com.ohos.test.special"; + + auto appInfo2 = std::make_shared(); + appInfo2->name = "com.ohos.test.special"; + appInfo2->bundleName = "com.ohos.test.special"; + const pid_t PID2 = 2234; + + APP_LOGI("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + StartLoadAbility(token2, token, abilityInfo2, appInfo2, PID2); + APP_LOGI("00000000000000000000000000000000000000"); + const uint32_t EXPECT_MAP_SIZE = 2; + EXPECT_EQ(recordMap.size(), EXPECT_MAP_SIZE); + + APP_LOGI("11111111111111111111111111111111111111111"); + auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo2->name, "com.ohos.test.special", appInfo2->uid, bundleInfo); + APP_LOGI("22222222222222222222222222222222222222"); + EXPECT_NE(record2, nullptr); + CHECK_POINTER_IS_NULLPTR(record2); + APP_LOGI("3333333333333333333333333333333333333"); + EXPECT_EQ(record2->GetState(), ApplicationState::APP_STATE_CREATE); + APP_LOGI("444444444444444444444444444444444444444444444"); + auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); + APP_LOGI("5555555555555555555555555555555555555"); + EXPECT_NE(abilityRecord2, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord2); + APP_LOGI("666666666666666666666666666666666"); + EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_002 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Null abilityId loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_003, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_003 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + EXPECT_TRUE(service_ != nullptr); + + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(nullptr, nullptr, abilityInfo, appInfo); + + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)0); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_003 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Null abilityInfo name loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_004, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_004 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = ""; + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + EXPECT_TRUE(service_ != nullptr); + + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)0); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_004 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Null appInfo name loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_005, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_005 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = ""; + abilityInfo->applicationInfo.bundleName = ""; + auto appInfo = std::make_shared(); + appInfo->name = ""; + appInfo->bundleName = ""; + EXPECT_TRUE(service_ != nullptr); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)0); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_005 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Different name loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_006, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_006 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName() + "_1"; + abilityInfo->applicationInfo.bundleName = GetTestAppName() + "_1"; + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + EXPECT_TRUE(service_ != nullptr); + + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)0); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_006 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Multiple same loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_007, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_007 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + + auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_EQ(record2, record); + const auto &abilityMap2 = record2->GetAbilities(); + EXPECT_EQ(abilityMap2.size(), (uint32_t)1); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_007 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Multiple different ability with same appName loadAbility requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_008 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + sptr token2 = new MockAbilityToken(); + sptr preToken = token; + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->applicationInfo.bundleName = GetTestAppName(); + const uint32_t EXPECT_MAP_SIZE = 2; + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token2, preToken, abilityInfo2, appInfo); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_EQ(record2, record); + const auto &abilityMap2 = record2->GetAbilities(); + EXPECT_EQ(abilityMap2.size(), EXPECT_MAP_SIZE); + auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); + EXPECT_NE(abilityRecord2, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord2); + EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); + EXPECT_EQ(abilityRecord2->GetPreToken(), token); + APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_008 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests and needd create new process. + * EnvConditions: NA + * CaseDescription: Normal loadAbility requesets handled when start process success. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_001, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest RequestProcess_001 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_OK))); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetPriorityObject()->GetPid(), PID); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + APP_LOGI("AmsServiceLoadAbilityProcessTest RequestProcess_001 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests and needd create new process. + * EnvConditions: NA + * CaseDescription: Normal loadAbility requesets handled when start process failed. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_002, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest RequestProcess_002 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + EXPECT_TRUE(service_ != nullptr); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(Return(ERR_APPEXECFWK_INVALID_PID)); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)0); + APP_LOGI("AmsServiceLoadAbilityProcessTest RequestProcess_002 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: the Service save pid to app running record when create new process successfully. + * EnvConditions: NA + * CaseDescription: Normal loadAbility and save pid to app running record. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, SavePid_001, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest SavePid_001 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_OK))); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_EQ(record->GetPriorityObject()->GetPid(), PID); + APP_LOGI("AmsServiceLoadAbilityProcessTest SavePid_001 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: the Service save pid to app running record when create new process failed. + * EnvConditions: NA + * CaseDescription: The service can't save pid to app running record when create new process failed. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, SavePid_002, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest SavePid_002 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + EXPECT_TRUE(service_ != nullptr); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(Return(ERR_APPEXECFWK_INVALID_PID)); + + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_EQ(record, nullptr); + APP_LOGI("AmsServiceLoadAbilityProcessTest SavePid_002 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Normal loadAbility requeset with singleton launch mode handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_001, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LaunchMode_001 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + abilityInfo->launchMode = LaunchMode::SINGLETON; + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + sptr token = GetMockToken(); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + APP_LOGI("AmsServiceLoadAbilityProcessTest LaunchMode_001 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive loadAbility requests. + * EnvConditions: NA + * CaseDescription: Multiple same loadAbility requesets with singleton launch mode and same ability info. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_002, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest LaunchMode_002 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->launchMode = LaunchMode::SINGLETON; + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); + sptr token2 = new MockAbilityToken(); + sptr preToken = token; + service_->SetAppSpawnClient(mockClientPtr); + service_->LoadAbility(token2, preToken, abilityInfo, appInfo); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_EQ(record2, record); + const auto &abilityMap2 = record2->GetAbilities(); + EXPECT_EQ(abilityMap2.size(), (uint32_t)1); + APP_LOGI("AmsServiceLoadAbilityProcessTest LaunchMode_002 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive startAbility requests. + * EnvConditions: NA + * CaseDescription: startAbility requesets with ability info. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_001 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + sptr token2 = new MockAbilityToken(); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->process = GetTestAppName(); + abilityInfo2->applicationInfo.bundleName = GetTestAppName(); + + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + record->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + service_->StartAbility(token2, token, abilityInfo2, record, hapModuleInfo); + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + const auto &abilityMap1 = record1->GetAbilities(); + EXPECT_EQ(abilityMap1.size(), (uint32_t)2); + auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); + EXPECT_NE(abilityrecord1, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityrecord1); + EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_001 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive startAbility requests. + * EnvConditions: NA + * CaseDescription: startAbility requesets with not apprecord. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_002, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_002 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + sptr token2 = new MockAbilityToken(); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->process = GetTestAppName(); + abilityInfo2->applicationInfo.bundleName = GetTestAppName(); + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + record->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + service_->StartAbility(token2, token, abilityInfo2, nullptr, hapModuleInfo); + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + const auto &abilityMap1 = record1->GetAbilities(); + EXPECT_EQ(abilityMap1.size(), (uint32_t)1); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_002 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive startAbility requests. + * EnvConditions: NA + * CaseDescription: startAbility requesets with the same LaunchMode. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_003, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_003 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->launchMode = LaunchMode::SINGLETON; + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + + sptr token2 = new MockAbilityToken(); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->launchMode = LaunchMode::SINGLETON; + abilityInfo2->process = GetTestAppName(); + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->applicationInfo.bundleName = GetTestAppName(); + + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + record->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + service_->StartAbility(token2, token, abilityInfo2, nullptr, hapModuleInfo); + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + const auto &abilityMap1 = record1->GetAbilities(); + EXPECT_EQ(abilityMap1.size(), (uint32_t)1); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_003 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive startAbility requests. + * EnvConditions: NA + * CaseDescription: startAbility requesets with not token. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_004, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_004 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->process = GetTestAppName(); + abilityInfo2->applicationInfo.bundleName = GetTestAppName(); + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + record->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + service_->StartAbility(nullptr, token, abilityInfo2, nullptr, hapModuleInfo); + + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + const auto &abilityMap1 = record1->GetAbilities(); + EXPECT_EQ(abilityMap1.size(), (uint32_t)1); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_004 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive startAbility requests. + * EnvConditions: NA + * CaseDescription: startAbility requesets with not preToken. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_005 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + sptr token2 = new MockAbilityToken(); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->process = GetTestAppName(); + abilityInfo2->applicationInfo.bundleName = GetTestAppName(); + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + record->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + service_->StartAbility(token2, nullptr, abilityInfo2, record, hapModuleInfo); + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + const auto &abilityMap1 = record1->GetAbilities(); + EXPECT_EQ(abilityMap1.size(), (uint32_t)2); + auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); + EXPECT_NE(abilityrecord1, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityrecord1); + EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_005 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive startAbility requests. + * EnvConditions: NA + * CaseDescription: startAbility requesets with ABILITY_STATE_CREATE. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_006, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_006 start"); + sptr token = GetMockToken(); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + + auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + auto abilityInfo2 = std::make_shared(); + abilityInfo2->name = GetTestAbilityName() + "_1"; + abilityInfo2->applicationName = GetTestAppName(); + abilityInfo2->process = GetTestAppName(); + abilityInfo2->applicationInfo.bundleName = GetTestAppName(); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + record->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + service_->StartAbility(nullptr, token, abilityInfo2, nullptr, hapModuleInfo); + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + const auto &abilityMap1 = record1->GetAbilities(); + EXPECT_EQ(abilityMap1.size(), (uint32_t)1); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_006 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive StartProcess requests. + * EnvConditions: NA + * CaseDescription: Normal StartProcess requesets handled inner service. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess001, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess001 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + sptr token = GetMockToken(); + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_OK))); + service_->SetAppSpawnClient(mockClientPtr); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + std::shared_ptr record = service_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + + service_->StartProcess(abilityInfo->applicationName, + GetTestAppName(), + record, + abilityInfo->applicationInfo.uid, + abilityInfo->applicationInfo.bundleName); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_EQ(record1->GetPriorityObject()->GetPid(), PID); + EXPECT_NE(record1, nullptr); + CHECK_POINTER_IS_NULLPTR(record1); + EXPECT_EQ(record1->GetState(), ApplicationState::APP_STATE_CREATE); + const auto &abilityMap = record1->GetAbilities(); + EXPECT_EQ(abilityMap.size(), (uint32_t)1); + auto abilityRecord = record1->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); + EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess001 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive StartProcess requests. + * EnvConditions: NA + * CaseDescription: Normal StartProcess requesets with not SpawnClient. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess002, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess002 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + EXPECT_TRUE(service_ != nullptr); + sptr token = GetMockToken(); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + std::shared_ptr record = service_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + + service_->SetAppSpawnClient(nullptr); + service_->StartProcess(abilityInfo->applicationName, + GetTestAppName(), + record, + abilityInfo->applicationInfo.uid, + abilityInfo->applicationInfo.bundleName); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record1, nullptr); + CHECK_POINTER_IS_NULLPTR(record1); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess002 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive StartProcess requests. + * EnvConditions: NA + * CaseDescription: Normal StartProcess requesets with not AppRecord. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess003, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess003 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + EXPECT_TRUE(service_ != nullptr); + sptr token = GetMockToken(); + std::shared_ptr mockClientPtr = std::make_shared(); + service_->SetAppSpawnClient(mockClientPtr); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + std::shared_ptr record = service_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + + service_->StartProcess(abilityInfo->applicationName, + GetTestAppName(), + nullptr, + abilityInfo->applicationInfo.uid, + abilityInfo->applicationInfo.bundleName); + const auto &recordMap = service_->GetRecordMap(); + EXPECT_EQ(recordMap.size(), (uint32_t)1); + + auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); + EXPECT_NE(record1, nullptr); + CHECK_POINTER_IS_NULLPTR(record1); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess003 end"); +} + +/* + * Feature: AMS + * Function: Service + * SubFunction: NA + * FunctionPoints: When Service receive StartProcess requests. + * EnvConditions: NA + * CaseDescription: Normal StartProcess requesets with StartProcess return fail. + */ +HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess004, TestSize.Level1) +{ + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess004 start"); + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(); + abilityInfo->applicationName = GetTestAppName(); + abilityInfo->process = GetTestAppName(); + abilityInfo->applicationInfo.bundleName = GetTestAppName(); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(); + appInfo->bundleName = GetTestAppName(); + const pid_t PID = 1234; + EXPECT_TRUE(service_ != nullptr); + sptr token = GetMockToken(); + std::shared_ptr mockClientPtr = std::make_shared(); + service_->SetAppSpawnClient(mockClientPtr); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)) + .Times(1) + .WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_TIMED_OUT))); + + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + + std::shared_ptr record = service_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); + service_->StartProcess(abilityInfo->applicationName, + GetTestAppName(), + record, + abilityInfo->applicationInfo.uid, + abilityInfo->applicationInfo.bundleName); + auto record1 = service_->GetAppRunningRecordByAppRecordId(record->GetRecordId()); + EXPECT_EQ(record1, nullptr); + APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess004 end"); +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..55ea371d65101d6666cae789e65217a51396d3b0 --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsServiceStartupTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/services/appmgr/test/mock/include", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", + "${services_path}/appmgr/src/app_mgr_service.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + ] + + sources += [ "ams_service_startup_test.cpp" ] + + configs = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/appmgr:libams", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsServiceStartupTest" ] +} diff --git a/services/appmgr/test/unittest/ams_service_startup_test/ams_service_startup_test.cpp b/services/appmgr/test/unittest/ams_service_startup_test/ams_service_startup_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44b30301932d7450c3a695ce70dff0b5164f4fe9 --- /dev/null +++ b/services/appmgr/test/unittest/ams_service_startup_test/ams_service_startup_test.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function +#define private public +#define protected public +#include "app_mgr_service.h" +#undef private +#undef protected +#include +#include "app_log_wrapper.h" + +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace AppExecFwk { +class AppMgrServiceInnerMock : public AppMgrServiceInner { +public: + virtual int32_t OpenAppSpawnConnection() override + { + return 0; + } +}; +class AmsServiceStartupTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsServiceStartupTest::SetUpTestCase() +{} + +void AmsServiceStartupTest::TearDownTestCase() +{} + +void AmsServiceStartupTest::SetUp() +{} + +void AmsServiceStartupTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: StartUp + * FunctionPoints: AppMgrService startup + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AppMgrService startup successfully + */ +HWTEST_F(AmsServiceStartupTest, Startup_001, TestSize.Level1) +{ + APP_LOGI("ams_service_startup_001 start"); + std::shared_ptr appMgrService = std::make_shared(); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + APP_LOGI("ams_service_startup_001 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: StartUp + * FunctionPoints: AppMgrService startup again + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if start up repeatly system act normal + */ +HWTEST_F(AmsServiceStartupTest, Startup_002, TestSize.Level1) +{ + APP_LOGI("ams_service_startup_002 start"); + std::shared_ptr appMgrService = std::make_shared(); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + APP_LOGI("ams_service_startup_002 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: StartUp + * FunctionPoints: AppMgrService stop without start + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if stop without start system act normal + */ +HWTEST_F(AmsServiceStartupTest, Startup_003, TestSize.Level1) +{ + APP_LOGI("ams_service_startup_003 start"); + std::shared_ptr appMgrService = std::make_shared(); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + APP_LOGI("ams_service_startup_003 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: StartUp + * FunctionPoints: AppMgrService stop repeatly + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if stop repeatly system act normal + */ +HWTEST_F(AmsServiceStartupTest, Startup_004, TestSize.Level1) +{ + APP_LOGI("ams_service_startup_004 start"); + std::shared_ptr appMgrService = std::make_shared(); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + APP_LOGI("ams_service_startup_004 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: StartUp + * FunctionPoints: AppMgrService start and stop repeatly + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if start and stop repeatly system act normal + */ +HWTEST_F(AmsServiceStartupTest, Startup_005, TestSize.Level1) +{ + APP_LOGI("ams_service_startup_005 start"); + std::shared_ptr appMgrService = std::make_shared(); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + APP_LOGI("ams_service_startup_005 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_start_via_asan_test/BUILD.gn b/services/appmgr/test/unittest/ams_start_via_asan_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4ee03a78efa2e6e8d9624708ead426869131ef12 --- /dev/null +++ b/services/appmgr/test/unittest/ams_start_via_asan_test/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AmsStartViaAsanTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/start_via_asan.cpp", + "ams_start_via_asan_test.cpp", + ] + + deps = [ + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("unittest") { + testonly = true + + deps = [ ":AmsStartViaAsanTest" ] +} diff --git a/services/appmgr/test/unittest/ams_start_via_asan_test/ams_start_via_asan_test.cpp b/services/appmgr/test/unittest/ams_start_via_asan_test/ams_start_via_asan_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce3783d987021f650dfa492d84289f60efe2b804 --- /dev/null +++ b/services/appmgr/test/unittest/ams_start_via_asan_test/ams_start_via_asan_test.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "start_via_asan.h" +#include +#include "properties.h" +#include "app_log_wrapper.h" + +using namespace testing::ext; +namespace OHOS { +namespace AppExecFwk { +class AmsStartViaAsanTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsStartViaAsanTest::SetUpTestCase() +{} + +void AmsStartViaAsanTest::TearDownTestCase() +{} + +void AmsStartViaAsanTest::SetUp() +{} + +void AmsStartViaAsanTest::TearDown() +{} + +/* + * Feature: StartViaAsan + * Function: ASAN + * SubFunction: IsAsanVersion + * FunctionPoints: Use interface GetSysPara to get wrap.appName attribute. + * EnvConditions: NA + * CaseDescription: Judge whether the wrap attribute exists in the environment. + */ +HWTEST_F(AmsStartViaAsanTest, IsAsanVersion_001, TestSize.Level1) +{ + APP_LOGD("IsAsanVersion_001 start"); + std::string appName = "com.ohos.hiworld"; + bool result = DelayedSingleton::GetInstance()->IsAsanVersion(appName); + EXPECT_EQ(result, false); + + APP_LOGD("IsAsanVersion_001 end"); +} + +/* + * Feature: StartViaAsan + * Function: ASAN + * SubFunction: GetAsanStartMsg + * FunctionPoints: Add wrap attribute to AppSpawnStartMsg object + * EnvConditions: NA + * CaseDescription: Add the wrap attribute to the arg field of the AppSpawnStartMsg object + */ +HWTEST_F(AmsStartViaAsanTest, GetAsanStartMsg_001, TestSize.Level1) +{ + APP_LOGD("GetAsanStartMsg_001 start"); + std::string appName = "com.ohos.hiworld"; + AppSpawnStartMsg startMsg = {appName, "clsName", "funcName", "soPath"}; + DelayedSingleton::GetInstance()->GetAsanStartMsg(startMsg); + EXPECT_EQ(startMsg.arg, "wrap." + appName); + APP_LOGD("GetAsanStartMsg_001 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4e64ee9e19f45f6b7a59424d5859e3eba4f75120 --- /dev/null +++ b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/appmgrservice" + +ohos_unittest("AMSEventHandlerTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", + "${services_path}/appmgr/src/app_lifecycle_deal.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_process_manager.cpp", + "${services_path}/appmgr/src/app_running_manager.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/src/cgroup_manager.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/module_running_record.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + "${services_path}/appmgr/src/process_optimizer_uba.cpp", + "${services_path}/appmgr/src/remote_client_manager.cpp", + ] + + sources += [ "app_mgr_service_event_handler_test.cpp" ] + + configs = [ + "${services_path}/appmgr/test:appmgr_test_config", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AMSEventHandlerTest" ] +} diff --git a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..977e1889552f297500429166a6dd5afc6c9166ad --- /dev/null +++ b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_mgr_service_event_handler.h" +#undef private + +#include "app_log_wrapper.h" +#include "app_mgr_service_inner.h" +#include +#include +#include "mock_app_scheduler.h" +#include "inner_event.h" +#include + +using namespace testing::ext; +namespace OHOS { +namespace AppExecFwk { +static bool eventHandlerFlag_ = false; +class MockAMSEventHandler : public AMSEventHandler { +public: + MockAMSEventHandler(const std::shared_ptr &runner, const std::shared_ptr &ams); + virtual ~MockAMSEventHandler(); + + void ProcessEvent(const InnerEvent::Pointer &event) override + { + if (event->GetInnerEventId() == 10) { + eventHandlerFlag_ = true; + } + } +}; + +class AMSEventHandlerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +public: + std::shared_ptr testAms; + std::shared_ptr eventHandler_; + std::shared_ptr runner_; +}; + +static void WaitUntilTaskFinished(std::shared_ptr handler) +{ + if (!handler) { + return; + } + + const uint32_t MAX_RETRY_COUNT = 1000; + const uint32_t SLEEP_TIME = 1000; + uint32_t count = 0; + std::atomic taskCalled(false); + auto f = [&taskCalled]() { taskCalled.store(true); }; + if (handler->PostTask(f)) { + while (!taskCalled.load()) { + ++count; + // if delay more than 1 second, break + if (count >= MAX_RETRY_COUNT) { + break; + } + + usleep(SLEEP_TIME); + } + } +} + +void AMSEventHandlerTest::SetUpTestCase() +{} + +void AMSEventHandlerTest::TearDownTestCase() +{} + +void AMSEventHandlerTest::SetUp() +{ + runner_ = EventRunner::Create("AMSEventHandlerTest"); + testAms = std::make_shared(); +} + +void AMSEventHandlerTest::TearDown() +{} + +MockAMSEventHandler ::MockAMSEventHandler( + const std::shared_ptr &runner, const std::shared_ptr &ams) + : AMSEventHandler(runner, ams) +{} + +MockAMSEventHandler::~MockAMSEventHandler() +{} + +/* + * Feature: AMS + * Function: AMSEventHandler + * SubFunction: AMSEventHandler + * FunctionPoints: init. + * EnvConditions: need to start a runner + * CaseDescription: Initialize message class + */ + +HWTEST_F(AMSEventHandlerTest, app_mgr_service_event_handler_test_001, TestSize.Level1) +{ + APP_LOGI("app_mgr_service_event_handler_test start"); + + if (!runner_) { + APP_LOGI("app_mgr_service_event_handler_test : runner_ is null"); + } + + if (!testAms) { + APP_LOGI("app_mgr_service_event_handler_test : testAms is null"); + } + EXPECT_FALSE(eventHandler_); + // init + eventHandler_ = std::make_shared(runner_, testAms); + EXPECT_TRUE(eventHandler_); + APP_LOGI("app_mgr_service_event_handler_test end"); +} + +/* + * Feature: AMS + * Function: ProcessEvent + * SubFunction: AMSEventHandler + * FunctionPoints: postTask. + * EnvConditions: need to start a runner + * CaseDescription: Notification message + */ + +HWTEST_F(AMSEventHandlerTest, app_mgr_service_event_handler_test_002, TestSize.Level1) +{ + APP_LOGI("app_mgr_service_event_handler_test start"); + + if (!eventHandler_) { + eventHandler_ = std::make_shared(runner_, testAms); + } + + // Error testing + eventHandler_->SendEvent(20); + + // waiting callback + WaitUntilTaskFinished(eventHandler_); + EXPECT_FALSE(eventHandlerFlag_); + + // test num == 10 + eventHandler_->SendEvent(10); + + // waiting callback + WaitUntilTaskFinished(eventHandler_); + EXPECT_TRUE(eventHandlerFlag_); + + APP_LOGI("app_mgr_service_event_handler_test end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/appmgr/zidl/IAbilityScheduler.zidl b/services/appmgr/zidl/IAbilityScheduler.zidl new file mode 100644 index 0000000000000000000000000000000000000000..6107b91f259d5e7f225bc1ab343ea918b5628bc4 --- /dev/null +++ b/services/appmgr/zidl/IAbilityScheduler.zidl @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +interface IAbilityScheduler { + void scheduleLaunchAbilitySlice(in AbilitySliceInfo); + void scheduleForegroundAbility(); + void scheduleBackgroundAbility(); + void scheduleTerminateAbility(); +} \ No newline at end of file diff --git a/services/appmgr/zidl/IAppMgr.zidl b/services/appmgr/zidl/IAppMgr.zidl new file mode 100644 index 0000000000000000000000000000000000000000..4e73f1395b474dc98e55fffa1e69d36acd56f21d --- /dev/null +++ b/services/appmgr/zidl/IAppMgr.zidl @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +interface OHOS.AppExecFwk.IAppScheduler; +interface OHOS.AppExecFwk.IAbilityScheduler; +interface OHOS.AppExecFwk.IAppStateCallback; + +parcelable OHOS.AppExecFwk.AppRecordId; +parcelable OHOS.AppExecFwk.AbilityInfo; +parcelable OHOS.AppExecFwk.AbilityRecordId; +parcelable OHOS.AppExecFwk.ApplicationInfo; + +interface OHOS.AppExecFwk.IAppMgr { + /* the function about ASMS begin */ + [oneway] void LoadAbility([in] IRemoteObject, [in] AbilityInfo, [in] ApplicationInfo); + [oneway] void TerminateAbility([in] IRemoteObject); + [oneway] void UpdateAbilityState([in] IRemoteObject, [in] int); + [oneway] void RegisterAppStateCallback([in] IAppStateCallback); + /* the function about ASMS end */ + + /* the function about Application begin */ + [oneway] void AttachApplication([in] IAppScheduler); + [oneway] void ApplicationForegrounded([in] AppRecordId); + [oneway] void ApplicationBackgrounded([in] AppRecordId); + [oneway] void ApplicationTerminated([in] AppRecordId); + int CheckPermission([in] AppRecordId, [in] String); + /* the function about Application end*/ +} \ No newline at end of file diff --git a/services/appmgr/zidl/IAppScheduler.zidl b/services/appmgr/zidl/IAppScheduler.zidl new file mode 100644 index 0000000000000000000000000000000000000000..c905313e2ab95fb57b8ba2ad63ee41599dd1bea4 --- /dev/null +++ b/services/appmgr/zidl/IAppScheduler.zidl @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +parcelable OHOS.AppExecFwk.AbilityInfo; +parcelable OHOS.AppExecFwk.ApplicationInfo; +parcelable OHOS.AppExecFwk.Profile; + +interface OHOS.AppExecFwk.IAppScheduler { + [oneway] void ScheduleLaunchApplication([in] ApplicationInfo, [in] Profile); + [oneway] void ScheduleLaunchAbility([in] AbilityInfo, [in] IRemoteObject); + [oneway] void ScheduleCleanAbility([in] IRemoteObject); + [oneway] void ScheduleForegroundApplication(); + [oneway] void ScheduleBackgroundApplication(); + [oneway] void ScheduleTerminateApplication(); + [oneway] void ScheduleShrinkMemory([in] int); + [oneway] void ScheduleLowMemory(); + [oneway] void ScheduleProfileChanged([in] Profile); +} \ No newline at end of file diff --git a/services/appmgr/zidl/IAppStateCallback.zidl b/services/appmgr/zidl/IAppStateCallback.zidl new file mode 100644 index 0000000000000000000000000000000000000000..fda532ca530a0760f3824b15d5653fbd80ec67b0 --- /dev/null +++ b/services/appmgr/zidl/IAppStateCallback.zidl @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +interface OHOS.AppExecFwk.IAppStateCallback { + [oneway] void OnAppStateChanged[in] String, [in] int); + [oneway] void OnAbilityRequestDone([in] IRemoteObject, [in] int ); +} \ No newline at end of file diff --git a/services/dataobsmgr/BUILD.gn b/services/dataobsmgr/BUILD.gn index 474d2a4eb3f60d61466be2e6cee92a363881707b..6dfd775b53ffa9020edf47eb834d0d7782bbb265 100644 --- a/services/dataobsmgr/BUILD.gn +++ b/services/dataobsmgr/BUILD.gn @@ -50,6 +50,7 @@ ohos_shared_library("dataobsms") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager:dataobs_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", @@ -66,5 +67,5 @@ ohos_shared_library("dataobsms") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/services/dataobsmgr/test/unittest/phone/data_ability_observer_proxy_test/BUILD.gn b/services/dataobsmgr/test/unittest/phone/data_ability_observer_proxy_test/BUILD.gn index 77f3aee3d7a525aaba5dd6387ba817737fc12e94..63c9ba0dfef50f2574d208b3b29db53fa1628393 100644 --- a/services/dataobsmgr/test/unittest/phone/data_ability_observer_proxy_test/BUILD.gn +++ b/services/dataobsmgr/test/unittest/phone/data_ability_observer_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/dataobsmgr" +module_output_path = "ability_runtime/dataobsmgr" ohos_unittest("data_ability_observer_proxy_test") { module_out_path = module_output_path diff --git a/services/dataobsmgr/test/unittest/phone/data_ability_observer_stub_test/BUILD.gn b/services/dataobsmgr/test/unittest/phone/data_ability_observer_stub_test/BUILD.gn index 1f51108585ef12f5a6b68ec846fdc4cf8784ba95..415dc3d766c4f95c3a072b876f564e3ce6fedb8e 100644 --- a/services/dataobsmgr/test/unittest/phone/data_ability_observer_stub_test/BUILD.gn +++ b/services/dataobsmgr/test/unittest/phone/data_ability_observer_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/dataobsmgr" +module_output_path = "ability_runtime/dataobsmgr" ohos_unittest("data_ability_observer_stub_test") { module_out_path = module_output_path diff --git a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/BUILD.gn b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/BUILD.gn index c6d47bf97e601bbb87e17585c5569009bbf87435..d5cb95a7339137a8dc3618a6129da6d7063f3965 100644 --- a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/BUILD.gn +++ b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/dataobsmgr" +module_output_path = "ability_runtime/dataobsmgr" ohos_unittest("dataobs_mgr_client_test") { module_out_path = module_output_path diff --git a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_inner_test/BUILD.gn b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_inner_test/BUILD.gn index e6a4317cc8e87b902e6d606b104aa4b99a20db6f..ee45c6b5a50275c5962faf00391bfecd891eae73 100644 --- a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_inner_test/BUILD.gn +++ b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_inner_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/dataobsmgr" +module_output_path = "ability_runtime/dataobsmgr" ohos_unittest("dataobs_mgr_inner_test") { module_out_path = module_output_path diff --git a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_proxy_test/BUILD.gn b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_proxy_test/BUILD.gn index 0c2b2c22e3a12ac3a5d537bb3b54b0565b983930..498086970366649c6c5c8c913ac334901f1531a2 100644 --- a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_proxy_test/BUILD.gn +++ b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_proxy_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/dataobsmgr" +module_output_path = "ability_runtime/dataobsmgr" ohos_unittest("dataobs_mgr_proxy_test") { module_out_path = module_output_path diff --git a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_service_test/BUILD.gn b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_service_test/BUILD.gn index 19d61681b3655fc9a9e55cc43c3eb2a54482027d..3a388ab2d1a7cf7c693d95de6c0a3ab9c1f080e0 100644 --- a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_service_test/BUILD.gn +++ b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_service_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/dataobsmgr" +module_output_path = "ability_runtime/dataobsmgr" ohos_unittest("dataobs_mgr_service_test") { module_out_path = module_output_path diff --git a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_stub_test/BUILD.gn b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_stub_test/BUILD.gn index 0ca427e7100f1aff1ac56291108dc4e275318506..dfa0acb484ef81f1827418f24eebab99142c220e 100644 --- a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_stub_test/BUILD.gn +++ b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_stub_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/dataobsmgr" +module_output_path = "ability_runtime/dataobsmgr" ohos_unittest("dataobs_mgr_stub_test") { module_out_path = module_output_path diff --git a/services/formmgr/BUILD.gn b/services/formmgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7f7bbfc2a83904207b57d6ecd9bfdba809d95a9a --- /dev/null +++ b/services/formmgr/BUILD.gn @@ -0,0 +1,125 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("formmgr_config") { + include_dirs = [ + "include", + "//third_party/json/include", + "//utils/system/safwk/native/include", + + # "//base/miscservices/time/interfaces/innerkits/include", + ] +} + +group("fms_target") { + deps = [ ":libfms" ] +} + +ohos_shared_library("libfms") { + include_dirs = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", + + # "//third_party/libuuid", + ] + sources = [ + "src/form_ability_connection.cpp", + "src/form_acquire_connection.cpp", + "src/form_ams_helper.cpp", + "src/form_batch_delete_connection.cpp", + "src/form_bms_helper.cpp", + "src/form_cache_mgr.cpp", + "src/form_cast_temp_connection.cpp", + "src/form_data_mgr.cpp", + "src/form_db_cache.cpp", + "src/form_db_info.cpp", + "src/form_delete_connection.cpp", + "src/form_dump_mgr.cpp", + "src/form_event_notify_connection.cpp", + "src/form_host_callback.cpp", + "src/form_host_record.cpp", + "src/form_info_mgr.cpp", + "src/form_info_storage_mgr.cpp", + "src/form_item_info.cpp", + "src/form_mgr_adapter.cpp", + "src/form_mgr_service.cpp", + "src/form_msg_event_connection.cpp", + "src/form_provider_mgr.cpp", + "src/form_refresh_connection.cpp", + "src/form_refresh_limiter.cpp", + "src/form_storage_mgr.cpp", + "src/form_supply_callback.cpp", + "src/form_sys_event_receiver.cpp", + "src/form_task_mgr.cpp", + "src/form_timer_mgr.cpp", + "src/form_util.cpp", + "src/kvstore_death_recipient_callback.cpp", + ] + + defines = [ + "APP_LOG_TAG = \"FormMgrService\"", + "LOG_DOMAIN = 0xD001120", + ] + + configs = [ + ":formmgr_config", + "//base/miscservices/time/services:time_service_config", + "${aafwk_path}/interfaces/innerkits/form_manager:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//utils/native/base:utils", + + # "//third_party/libuuid:libuuid_static", + ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "dmsfwk_standard:zuri", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "os_account_standard:libaccountkits", + "os_account_standard:os_account_innerkits", + "permission_standard:libpermissionsdk_standard", + "power_manager_native:powermgr_client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "aafwk" + part_name = "form_runtime" +} diff --git a/services/formmgr/bundle.json b/services/formmgr/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..801f14db7b9bd31e77204b01183eacd83b48b98b --- /dev/null +++ b/services/formmgr/bundle.json @@ -0,0 +1,94 @@ +{ + "name": "@ohos/form_runtime", + "description": "提供卡片创建、卡片删除、卡片释放等能力,包含接口和服务", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "foundation/aafwk/standard/services/formmgr" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "form_runtime", + "subsystem": "aafwk", + "syscap": [], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "", + "ram": "", + "deps": { + "components": [ + "ability_runtime", + "ans_standard", + "appexecfwk_standard", + "ces_standard", + "hiviewdfx_hilog_native", + "ipc", + "napi", + "native_appdatamgr", + "miscservices_time", + "os_account_standard", + "permission_standard", + "power_manager_native", + "safwk", + "samgr_standard", + "utils_base" + ], + "third_party": [ + "node", + "jsoncpp", + "json" + ] + }, + "build": { + "sub_component": [ + "//foundation/aafwk/standard/sa_profile:form_sa_profile", + "//foundation/aafwk/standard/services:fms_services_target", + "//foundation/aafwk/standard/interfaces/innerkits:fms_innerkits_target", + "//foundation/aafwk/standard/frameworks/kits/fmskit:fmskit_native", + "//foundation/aafwk/standard/interfaces/kits/napi:form_napi_packages" + ], + "inner_kits": [ + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "header_files": [ + "form_death_callback.h", + "form_host_interface.h", + "form_host_stub.h", + "form_js_info.h", + "form_mgr_interface.h", + "form_mgr_stub.h", + "form_provider_data.h", + "form_provider_interface.h", + "form_provider_stub.h", + "form_supply_interface.h", + "form_supply_stub.h", + "provider_connect_stub.h", + "form_constants.h", + "form_js_info.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/form_manager:form_manager" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "header_files": [ + "form_callback_interface.h", + "form_host_client.h", + "form_mgr.h" + ] + }, + "name": "//foundation/aafwk/standard/frameworks/kits/fmskit:fmskit_native" + } + ], + "test": [ + "//foundation/aafwk/standard/services/formmgr/test:unittest" + ] + } + } +} \ No newline at end of file diff --git a/services/formmgr/include/form_ability_connection.h b/services/formmgr/include/form_ability_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..317ec9b850a6c1d2651374de10898b560230ca22 --- /dev/null +++ b/services/formmgr/include/form_ability_connection.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H + +#include "event_handler.h" +#include "form_item_info.h" +#include "provider_connect_stub.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormAbilityConnection + * Form Ability Connection Stub. + */ +class FormAbilityConnection : public ProviderConnectStub { +public: + FormAbilityConnection() = default; + virtual ~FormAbilityConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + /** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + + /** + * @brief remote object died event. + * @param remoteObject the remote object of service ability. + */ + void OnConnectDied(const wptr &remoteObject); + + /** + * @brief Get connectId. + * @return The ability connection id. + */ + long GetConnectId(); + + /** + * @brief Set connectId. + * @param connectId The ability connection id. + */ + void SetConnectId(long connectId); + /** + * @brief Get the provider Key + * + * @return The provider Key + */ + std::string GetProviderKey(); + /** + * @brief Set the Provider Key + * + * @param bundleName bundleName + * @param abilityName abilityName + */ + void SetProviderKey(const std::string &bundleName, const std::string &abilityName); + +private: + int64_t formId_ = 0; + std::string deviceId_ = ""; + std::string bundleName_ = ""; + std::string abilityName_ = ""; + bool isFreeInstall_ = false; + long connectId_ = 0; + + DISALLOW_COPY_AND_MOVE(FormAbilityConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_acquire_connection.h b/services/formmgr/include/form_acquire_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..8f680067d30c99f01fb0aa8245335f1c380cca70 --- /dev/null +++ b/services/formmgr/include/form_acquire_connection.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ACQUIRE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ACQUIRE_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "form_item_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormAcquireConnection + * Form Acquire Connection Stub. + */ +class FormAcquireConnection : public FormAbilityConnection { +public: + FormAcquireConnection(const int64_t formId, const FormItemInfo &info, const WantParams &wantParams); + virtual ~FormAcquireConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + FormItemInfo info_; + WantParams wantParams_; + + DISALLOW_COPY_AND_MOVE(FormAcquireConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ACQUIRE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_ams_helper.h b/services/formmgr/include/form_ams_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..ccfa296d667e4cb5fcd43b8f62e7646aeb40e0a0 --- /dev/null +++ b/services/formmgr/include/form_ams_helper.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_AMS_HELPER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_AMS_HELPER_H + +#include +#include +#include "ability_connect_callback_interface.h" +#include "ability_manager_interface.h" +#include "event_handler.h" +#include "iremote_object.h" +#include "uri.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; +using Want = OHOS::AAFwk::Want; +/** + * @class FormAmsHelper + * Ams helpler. + */ +class FormAmsHelper final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormAmsHelper) +public: + DISALLOW_COPY_AND_MOVE(FormAmsHelper); + /** + * @brief SetEventHandler. + * @param handler event handler + */ + inline void SetEventHandler(const std::shared_ptr &handler) + { + eventHandler_ = handler; + } + /** + * @brief acquire a form ability manager if it not existed, + * @return returns the ability manager ipc object or nullptr for failed. + */ + sptr GetAbilityManager(); + /** + * @brief Connect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ConnectServiceAbility( + const Want &want, const sptr &connect); + /** + * @brief Disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DisConnectServiceAbility(const sptr &connect); + /** + * @brief Disconnect ability delay, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DisConnectServiceAbilityDelay(const sptr &connect); + /** + * @brief Add the ability manager instance for debug. + * @param abilityManager the ability manager ipc object. + */ + void SetAbilityManager(const sptr &abilityManager); +private: + /** + * @brief Disconnect ability task, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + */ + void DisConnectAbilityTask(const sptr &connect); +private: + sptr abilityManager_ = nullptr; + std::shared_ptr eventHandler_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_AMS_HELPER_H diff --git a/services/formmgr/include/form_batch_delete_connection.h b/services/formmgr/include/form_batch_delete_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..3d3d1f75e1ca03f3ee024e9ea20bddebd22516b6 --- /dev/null +++ b/services/formmgr/include/form_batch_delete_connection.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BATCH_DELETE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BATCH_DELETE_CONNECTION_H + +#include + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormBatchDeleteConnection + * Form batch delete connection stub. + */ +class FormBatchDeleteConnection : public FormAbilityConnection { +public: + FormBatchDeleteConnection(const std::set &formIds, const std::string &bundleName, + const std::string &abilityName); + virtual ~FormBatchDeleteConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + std::set formIds_; + + DISALLOW_COPY_AND_MOVE(FormBatchDeleteConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BATCH_DELETE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_bms_helper.h b/services/formmgr/include/form_bms_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..4e5523ba3bc681a495af091c8a76ca6f767a5ad7 --- /dev/null +++ b/services/formmgr/include/form_bms_helper.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BMS_HELPER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BMS_HELPER_H + +#include +#include "ability_connect_callback_interface.h" +#include "ability_manager_interface.h" +#include "bundle_info.h" +#include "bundle_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; + +/** + * @class FormBmsHelper + * Bms helpler. + */ +class FormBmsHelper final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormBmsHelper) + +public: + DISALLOW_COPY_AND_MOVE(FormBmsHelper); + + /** + * @brief Notify module removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ + void NotifyModuleRemovable(const std::string &bundleName, const std::string &moduleName); + /** + * @brief Notify module not removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ + void NotifyModuleNotRemovable(const std::string &bundleName, const std::string &moduleName) const; + + /** + * @brief Acquire a bundle manager, if it not existed, + * @return returns the bundle manager ipc object, or nullptr for failed. + */ + sptr GetBundleMgr(); + + /** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ + void SetBundleManager(const sptr &bundleManager); + +private: + /** + * @brief Generate module key. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + * @return Module key. + */ + std::string GenerateModuleKey(const std::string &bundleName, const std::string &moduleName) const; + +private: + sptr iBundleMgr_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BMS_HELPER_H diff --git a/services/formmgr/include/form_cache_mgr.h b/services/formmgr/include/form_cache_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..d6fb1803dbeecd592d602d3eabc5315649df99c2 --- /dev/null +++ b/services/formmgr/include/form_cache_mgr.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CACHE_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CACHE_MGR_H + +#include +#include +#include +#include +#include + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormCacheMgr + * Form cache data manager. + */ +class FormCacheMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormCacheMgr) +public: + DISALLOW_COPY_AND_MOVE(FormCacheMgr); + + /** + * @brief Get form data. + * @param formId Form id. + * @param data Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetData(const int64_t formId, std::string &data) const; + + /** + * @brief Add form data. + * @param formId Form id. + * @param data Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool AddData(const int64_t formId, const std::string &data); + + /** + * @brief Delete form data. + * @param formId Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteData(const int64_t formId); + + /** + * @brief update form data. + * @param formId Form id. + * @param data Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UpdateData(const int64_t formId, const std::string &data); + /** + * @brief Check if form data is exist or not. + * @param formId, Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool IsExist(const int64_t formId) const; +private: + mutable std::mutex cacheMutex_; + std::map cacheData_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CACHE_MGR_H diff --git a/services/formmgr/include/form_cast_temp_connection.h b/services/formmgr/include/form_cast_temp_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..6a930ceca8a75c31d3f4d27e5134804c114af1eb --- /dev/null +++ b/services/formmgr/include/form_cast_temp_connection.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormCastTempConnection + * Cast temp form Connection Stub. + */ +class FormCastTempConnection : public FormAbilityConnection { +public: + FormCastTempConnection(const int64_t formId, const std::string &bundleName, + const std::string &abilityName); + virtual ~FormCastTempConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormCastTempConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_data_mgr.h b/services/formmgr/include/form_data_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..61ec4383af0df6d1792bd2cfc59a9fe015aa8a3a --- /dev/null +++ b/services/formmgr/include/form_data_mgr.h @@ -0,0 +1,420 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DATA_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DATA_MGR_H + +#include +#include +#include +#include +#include +#include + +#include "form_constants.h" +#include "form_host_record.h" +#include "form_id_key.h" +#include "form_info.h" +#include "form_item_info.h" +#include "form_js_info.h" +#include "form_record.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormDataMgr + * form data manager. + */ +class FormDataMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormDataMgr) +public: + DISALLOW_COPY_AND_MOVE(FormDataMgr); + /** + * @brief Allot form info by item info. + * @param formId The Id of the form. + * @param formInfo Form item info. + * @param callingUid The UID of the proxy. + * @param userId User ID. + * @return Returns form record. + */ + FormRecord AllotFormRecord(const FormItemInfo &formInfo, const int callingUid, + const int32_t userId = Constants::DEFAULT_USER_ID); + /** + * @brief Create form js info by form record. + * @param formId The Id of the form. + * @param record Form record. + * @param formInfo Js info. + * @return None. + */ + void CreateFormInfo(const int64_t formId, const FormRecord &record, FormJsInfo &formInfo); + /** + * @brief Delete form js info by form record. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteFormRecord(const int64_t formId); + /** + * @brief Clean removed forms for host. + * @param removedFormIds The id list of the forms. + */ + void CleanHostRemovedForms(const std::vector &removedFormIds); + /** + * @brief Allot form host record by caller token. + * @param info The form item info. + * @param callerToken callerToken + * @param formId The Id of the form. + * @param callingUid The UID of the proxy. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool AllotFormHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int64_t formId, const int callingUid); + /** + * @brief Check temp form count is max. + * @return Returns ERR_OK if the temp form not reached; returns ERR_MAX_SYSTEM_TEMP_FORMS is reached. + */ + int CheckTempEnoughForm() const; + /** + * @brief Check form count is max. + * @param currentUserId The current userId. + * @param callingUid The UID of the proxy. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + int CheckEnoughForm(const int callingUid, const int32_t currentUserId = Constants::DEFAULT_USER_ID) const; + /** + * @brief Delete temp form. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteTempForm(const int64_t formId); + /** + * @brief Check temp form is exist. + * @param formId The Id of the form. + * @return Returns true if the temp form is exist; returns false is not exist. + */ + bool ExistTempForm(const int64_t formId) const; + /** + * @brief Modify form temp flag by formId. + * @param formId The Id of the form. + * @param formTempFlg The form temp flag. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool ModifyFormTempFlg(const int64_t formId, const bool formTempFlg); + /** + * @brief Add form user uid from form record. + * @param formId The Id of the form. + * @param formUserUid The form user uid. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool AddFormUserUid(const int64_t formId, const int formUserUid); + /** + * @brief Delete form user uid from form record. + * @param formId The Id of the form. + * @param uid calling user id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteFormUserUid(const int64_t formId, const int uid); + /** + * @brief Update form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UpdateFormRecord(const int64_t formId, const FormRecord &formRecord); + /** + * @brief Get form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetFormRecord(const int64_t formId, FormRecord &formRecord) const; + /** + * @brief Get form record. + * @param bundleName Bundle name. + * @param formInfos The form record list. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetFormRecord(const std::string &bundleName, std::vector &formInfos); + /** + * @brief Check form record is exist. + * @param formId The Id of the form. + * @return Returns true if the form record is exist; returns false is not exist. + */ + bool ExistFormRecord(const int64_t formId) const; + /** + * @brief Has form user uids in form record. + * @param formId The Id of the form. + * @return Returns true if this form has form user uids; returns false is not has. + */ + bool HasFormUserUids(const int64_t formId) const; + /** + * @brief Get form host record. + * @param formId The id of the form. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetFormHostRecord(const int64_t formId, FormHostRecord &formHostRecord) const; + /** + * @brief Delete form host record. + * @param callerToken The client stub of the form host record. + * @param formId The id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteHostRecord(const sptr &callerToken, const int64_t formId); + /** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ + void HandleHostDied(const sptr &remoteHost); + /** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable. + */ + bool IsEnableRefresh(int64_t formId); + /** + * @brief Check calling uid is valid. + * @param formUserUids The form user uids. + * @return Returns true if this user uid is valid; returns false otherwise. + */ + bool IsCallingUidValid(const std::vector &formUserUids) const; + /** + * @brief Generate udid. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GenerateUdidHash(); + /** + * @brief Generate form id. + * @return form id. + */ + int64_t GenerateFormId(); + /** + * @brief Get udid. + * @return udid. + */ + int64_t GetUdidHash() const; + /** + * @brief Set udid. + * @param udidHash udid. + */ + void SetUdidHash(const int64_t udidHash); + + /** + * @brief Get the matched form host record by client stub. + * + * @param callerToken The client stub of the form host record. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called, returns false otherwise. + */ + bool GetMatchedHostClient(const sptr &callerToken, FormHostRecord &formHostRecord) const; + + /** + * @brief Set needRefresh for FormRecord. + * @param formId The Id of the form. + * @param needRefresh true or false. + */ + void SetNeedRefresh(const int64_t formId, const bool needRefresh); + /** + * @brief Set isCountTimerRefresh for FormRecord. + * @param formId The Id of the form. + * @param countTimerRefresh true or false. + */ + void SetCountTimerRefresh(const int64_t formId, const bool countTimerRefresh); + /** + * @brief Get updated form info. + * @param record FormRecord. + * @param targetForms Target forms. + * @param updatedForm Updated form info. + * @return Returns true on success, false on failure. + */ + bool GetUpdatedForm(const FormRecord &record, const std::vector &targetForms, FormInfo &updatedForm); + /** + * @brief Set isEnableUpdate for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + */ + void SetEnableUpdate(const int64_t formId, const bool enableUpdate); + /** + * @brief Set update info for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + * @param updateDuration Update duration. + * @param updateAtHour Update at hour. + * @param updateAtMin Update at minute. + */ + void SetUpdateInfo(const int64_t formId, const bool enableUpdate, const long updateDuration, + const int updateAtHour, const int updateAtMin); + /** + * @brief Clean removed form records. + * @param bundleName BundleName. + * @param removedForms The id list of the forms. + */ + void CleanRemovedFormRecords(const std::string &bundleName, std::set &removedForms); + /** + * @brief Clean removed temp form records. + * @param bundleName BundleName. + * @param removedForms The id list of the forms. + */ + void CleanRemovedTempFormRecords(const std::string &bundleName, std::set &removedForms); + /** + * @brief Get recreate form records. + * @param reCreateForms The id list of the forms. + */ + void GetReCreateFormRecordsByBundleName(const std::string &bundleName, std::set &reCreateForms); + /** + * @brief Set form isInited = true. + * @param formId The Id of the form. + * @param isInited isInited property + */ + void SetFormCacheInited(const int64_t formId, const bool isInited); + /** + * @brief Set versionUpgrade. + * @param formId The Id of the form. + * @param versionUpgrade true or false + */ + void SetVersionUpgrade(const int64_t formId, const bool versionUpgrade); + /** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param needRefresh true or false + */ + void UpdateHostNeedRefresh(const int64_t formId, const bool needRefresh); + /** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formRecord The form info. + * @return Returns true if form update, false if other. + */ + bool UpdateHostForm(const int64_t formId, const FormRecord &formRecord); + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @param refreshForms Refresh forms + * @return Returns ERR_OK on success, others on failure. + */ + int32_t UpdateHostFormFlag(std::vector formIds, const sptr &callerToken, + const bool flag, std::vector &refreshForms); + /** + * @brief Find matched form id. + * @param formId The form id. + * @return Matched form id. + */ + int64_t FindMatchedFormId(const int64_t formId); + /** + * @brief Clear host data by uId. + * @param uId The caller uId. + */ + void ClearHostDataByUId(const int uId); + /** + * @brief Get no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ + void GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, + std::map &foundFormsMap); + + /** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formProviderInfo FormProviderInfo object + */ + void UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo); + + /** + * @brief delete forms by userId. + * + * @param userId user ID. + * @param removedFormIds removed userId. + */ + void DeleteFormsByUserId(const int32_t userId, std::vector &removedFormIds); + /** + * @brief Clear form records for st limit value test. + */ + void ClearFormRecords(); +private: + /** + * @brief Create form record. + * @param formInfo The form item info. + * @param callingUid The UID of the proxy. + * @param userId User ID. + * @return Form record. + */ + FormRecord CreateFormRecord(const FormItemInfo &formInfo, const int callingUid, + const int32_t userId = Constants::DEFAULT_USER_ID) const; + /** + * @brief Create host record. + * @param info The form item info. + * @param callerToken The UID of the proxy. + * @param callingUid The UID of the proxy. + * @param record The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool CreateHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int callingUid, FormHostRecord &record); + /** + * @brief Parse update config. + * @param record The form record. + * @param info The form item info. + * @return None. + */ + void ParseUpdateConfig(FormRecord &record, const FormItemInfo &info) const; + /** + * @brief Parse update interval config. + * @param record The form record. + * @param configDuration interval duration. + */ + void ParseIntervalConfig(FormRecord &record, const int configDuration) const; + /** + * @brief Parse at time config. + * @param record The form record. + * @param info form item info. + */ + void ParseAtTimerConfig(FormRecord &record, const FormItemInfo &info) const; + /** + * @brief Get the temp forms from host and delete temp form in cache. + * @param record The form record. + * @param recordTempForms Getted the temp forms. + */ + void HandleHostDiedForTempForms(const FormHostRecord &record, std::vector &recordTempForms); + /** + * @brief Check if two forms is same or not. + * @param record FormRecord. + * @param formInfo FormInfo. + * @return Returns true on success, false on failure. + */ + bool IsSameForm(const FormRecord &record, const FormInfo &formInfo); + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ + bool IsFormCached(const FormRecord record); +private: + mutable std::mutex formRecordMutex_; + mutable std::mutex formHostRecordMutex_; + mutable std::mutex formTempMutex_; + std::map formRecords_; + std::vector clientRecords_; + std::vector tempForms_; + int64_t udidHash_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_DATA_MGR_H diff --git a/services/formmgr/include/form_db_cache.h b/services/formmgr/include/form_db_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..a4652652cb6f47a9f6df77581ffdaa8dbcdfa4b6 --- /dev/null +++ b/services/formmgr/include/form_db_cache.h @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DB_CACHE_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DB_CACHE_H + +#include +#include +#include +#include + +#include "appexecfwk_errors.h" +#include "form_id_key.h" +#include "form_record.h" +#include "form_storage_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +class FormDbCache final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormDbCache) +public: + DISALLOW_COPY_AND_MOVE(FormDbCache); + + /** + * @brief Load form data from DB to DbCache when starting. + * @return Void. + */ + void Start(); + + /** + * @brief Get all form data from DbCache. + * @param formDBInfos Storage all DbCache. + * @return Void + */ + void GetAllFormInfo(std::vector &formDBInfos); + + /** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SaveFormInfo(const FormDBInfo &formDBInfo); + + /** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure.(NoLock) + */ + ErrCode SaveFormInfoNolock(const FormDBInfo &formDBInfo); + + /** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DeleteFormInfo(int64_t formId); + + /** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDBRecord(const int64_t formId, FormRecord &record) const; + + /** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form db data + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDBRecord(const int64_t formId, FormDBInfo &record) const; + + /** + * @brief Use record save or update DB data and DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateDBRecord(const int64_t formId, const FormRecord &record) const; + + /** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @param removedDBForms Removed db form infos + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DeleteFormInfoByBundleName(const std::string &bundleName, std::vector &removedDBForms); + + /** + * @brief Get no host db record. + * @param uid The caller uid. + * @param noHostFormDBList no host db record list. + * @param foundFormsMap Form Id list. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, + std::map &foundFormsMap); + + /** + * @brief Get match count by bundleName and moduleName. + * @param bundleName BundleName. + * @param moduleName ModuleName. + * @return Returns match count. + */ + int GetMatchCount(const std::string &bundleName, const std::string &moduleName); + + /** + * @brief Get data storage. + * @return Returns data storage. + */ + std::shared_ptr GetDataStorage() const; + + /** + * @brief delete forms bu userId. + * @param userId user ID. + */ + void DeleteDBFormsByUserId(const int32_t userId); +private: + std::shared_ptr dataStorage_; + mutable std::mutex formDBInfosMutex_; + std::vector formDBInfos_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DB_CACHE_H diff --git a/services/formmgr/include/form_db_info.h b/services/formmgr/include/form_db_info.h new file mode 100644 index 0000000000000000000000000000000000000000..6913e9ad65de71c53bc889c6c1f209e4ff278e0a --- /dev/null +++ b/services/formmgr/include/form_db_info.h @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_INNER_FORM_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_INNER_FORM_INFO_H + +#include + +#include "form_record.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace AppExecFwk { +struct FormDBInfo { + int64_t formId; + int32_t userId; + std::string formName; + std::string bundleName; + std::string moduleName; + std::string abilityName; + std::vector formUserUids; + + /** + * @brief Constructors + * + */ + FormDBInfo() + { + formId = -1; + } + + /** + * @brief Constructors + * + */ + FormDBInfo(const int64_t formIdTmp, const FormRecord &formRecord) + { + formId = formIdTmp; + userId = formRecord.userId; + formName = formRecord.formName; + bundleName = formRecord.bundleName; + moduleName = formRecord.moduleName; + abilityName = formRecord.abilityName; + formUserUids = formRecord.formUserUids; + } + bool Contains(const int uId) const + { + return std::find(formUserUids.begin(), formUserUids.end(), uId) != formUserUids.end(); + } + void Remove(const int uId) + { + auto itUId = std::find(formUserUids.begin(), formUserUids.end(), uId); + if (itUId != formUserUids.end()) { + formUserUids.erase(itUId); + } + } + /** + * @brief overloaded == for Indicates the formDBInfo by formId + * @return Returns true if the data equal; returns false otherwise. + */ + bool operator== (const FormDBInfo &formDBInfo) const + { + return (this->formId == formDBInfo.formId); + } + /** + * @brief Compare two data + * @return Returns true if the data equal; returns false otherwise. + */ + bool Compare(const FormDBInfo &formDBInfo) const + { + if (formId != formDBInfo.formId) { + return false; + } + if (userId != formDBInfo.userId) { + return false; + } + if (formName != formDBInfo.formName) { + return false; + } + if (bundleName != formDBInfo.bundleName) { + return false; + } + if (moduleName != formDBInfo.moduleName) { + return false; + } + if (abilityName != formDBInfo.abilityName) { + return false; + } + if (formUserUids != formDBInfo.formUserUids) { + return false; + } + + return true; + } +}; + +class InnerFormInfo { +public: + /** + * @brief Constructors + */ + InnerFormInfo() + { + formDBInfo_.formId = -1; + } + /** + * @brief Constructors + * + */ + InnerFormInfo(const FormDBInfo &formDBInfo) + { + formDBInfo_.formId = formDBInfo.formId; + formDBInfo_.userId = formDBInfo.userId; + formDBInfo_.formName = formDBInfo.formName; + formDBInfo_.bundleName = formDBInfo.bundleName; + formDBInfo_.moduleName = formDBInfo.moduleName; + formDBInfo_.abilityName = formDBInfo.abilityName; + formDBInfo_.formUserUids = formDBInfo.formUserUids; + } + /** + * @brief Constructors + * + */ + InnerFormInfo(const InnerFormInfo &innerFormInfo) + { + formDBInfo_.formId = innerFormInfo.formDBInfo_.formId; + formDBInfo_.userId = innerFormInfo.formDBInfo_.userId; + formDBInfo_.formName = innerFormInfo.formDBInfo_.formName; + formDBInfo_.bundleName = innerFormInfo.formDBInfo_.bundleName; + formDBInfo_.moduleName = innerFormInfo.formDBInfo_.moduleName; + formDBInfo_.abilityName = innerFormInfo.formDBInfo_.abilityName; + formDBInfo_.formUserUids = innerFormInfo.formDBInfo_.formUserUids; + } + /** + * @brief Constructors + * + */ + InnerFormInfo(const int64_t formId, const FormRecord &formRecord) + { + formDBInfo_.formId = formId; + formDBInfo_.userId = formRecord.userId; + formDBInfo_.formName = formRecord.formName; + formDBInfo_.bundleName = formRecord.bundleName; + formDBInfo_.moduleName = formRecord.moduleName; + formDBInfo_.abilityName = formRecord.abilityName; + formDBInfo_.formUserUids = formRecord.formUserUids; + } + std::string ToString() const + { + nlohmann::json j; + j["formId"] = formDBInfo_.formId; + j["userId"] = formDBInfo_.userId; + j["formName"] = formDBInfo_.formName; + j["bundleName"] = formDBInfo_.bundleName; + j["moduleName"] = formDBInfo_.moduleName; + j["abilityName"] = formDBInfo_.abilityName; + j["formUserUids"] = formDBInfo_.formUserUids; + return j.dump(); + } + /** + * @brief Destructor + * + */ + virtual ~InnerFormInfo(){}; + /** + * @brief overloaded == for Indicates the formInfo by formId + * @return Returns true if the data equal; returns false otherwise. + */ + bool operator== (const InnerFormInfo &innerFormInfo) const + { + return (this->formDBInfo_.formId == innerFormInfo.formDBInfo_.formId); + } + + /** + * @brief Transform the InnerFormInfo object to json. + * @param jsonObject Indicates the obtained json object. + */ + void ToJson(nlohmann::json &jsonObject) const; + + /** + * @brief Transform the json object to InnerFormInfo object. + * @param jsonObject Indicates the obtained json object. + * @return Returns true on success, false on failure. + */ + bool FromJson(const nlohmann::json &jsonObject); + + /** + * @brief Get application form id. + * @return Returns the form id. + */ + int64_t GetFormId() const + { + return formDBInfo_.formId; + } + + /** + * @brief Set application form id. + * @param formId Indicates the form id to be set. + */ + void SetFormId(const int64_t formId) + { + formDBInfo_.formId = formId; + } + + /** + * @brief Get application user id. + * @return Returns the user id. + */ + int64_t GetUserId() const + { + return formDBInfo_.userId; + } + + /** + * @brief Set application user id. + * @param userId Indicates the user id to be set. + */ + void SetUserId(const int64_t userId) + { + formDBInfo_.userId = userId; + } + + /** + * @brief Get application form name. + * @return Returns the form name. + */ + std::string GetModuleName() const + { + return formDBInfo_.moduleName; + } + + /** + * @brief Set application form name. + * @param formName Indicates the form name to be set. + */ + void SetModuleName(const std::string &moduleName) + { + formDBInfo_.moduleName = moduleName; + } + + /** + * @brief Get application bundle name. + * @return Returns the bundle name. + */ + std::string GetBundleName() const + { + return formDBInfo_.bundleName; + } + + /** + * @brief Set application bundle name. + * @param bundleName Indicates the bundle name to be set. + */ + void SetBundleName(const std::string &bundleName) + { + formDBInfo_.bundleName = bundleName; + } + + /** + * @brief Get application ability name. + * @return Returns the ability name. + */ + std::string GetAbilityName() const + { + return formDBInfo_.abilityName; + } + + /** + * @brief Set application ability name. + * @param abilityName Indicates the ability name to be set. + */ + void SetAbilityName(const std::string &abilityName) + { + formDBInfo_.abilityName = abilityName; + } + + /** + * @brief Get application formName. + * @return Returns the formName. + */ + std::string GetFormName() const + { + return formDBInfo_.formName; + } + + /** + * @brief Set application formName. + * @param userId Indicates the formName to be set. + */ + void SetFormName(std::string formName) + { + formDBInfo_.formName = formName; + } + + /** + * @brief Get application user uids. + * @return Returns the user uids. + */ + std::vector GetUserUids() const + { + return formDBInfo_.formUserUids; + } + + /** + * @brief Set application user uids. + * @param userId Indicates the user uids to be set. + */ + void SetUserUids(const std::vector &formUserUids) + { + formDBInfo_.formUserUids.insert(formDBInfo_.formUserUids.end(), formUserUids.begin(), formUserUids.end()); + } + + /** + * @brief Set application formRecord + * @param formRecord Indicates the formRecord to be set. + */ + void SetFormDBInfo(const FormDBInfo &formDBInfo) + { + formDBInfo_ = formDBInfo; + } + + /** + * @brief Get application formRecord. + * @return Returns the formRecord + */ + FormDBInfo GetFormDBInfo() const + { + return formDBInfo_; + } + + void AddUserUid(const int callingUid); + bool DeleteUserUid(const int callingUid); + +private: + FormDBInfo formDBInfo_; +}; + +// void to_json(nlohmann::json &jsonObject, const FormDBInfo &info); +// void from_json(const nlohmann::json &jsonObject, FormDBInfo &info); +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_INNER_FORM_INFO_H diff --git a/services/formmgr/include/form_delete_connection.h b/services/formmgr/include/form_delete_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..b9151a25c13cbd6f09e5f62dc0864239ebb2d2ea --- /dev/null +++ b/services/formmgr/include/form_delete_connection.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormDeleteConnection + * Form Delete Connection Stub. + */ +class FormDeleteConnection : public FormAbilityConnection { +public: + FormDeleteConnection(const int64_t formId, const std::string &bundleName, const std::string &abilityName); + virtual ~FormDeleteConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormDeleteConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_dump_mgr.h b/services/formmgr/include/form_dump_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..961d92e4bba71b0369621c89a47c34fa28bf78a1 --- /dev/null +++ b/services/formmgr/include/form_dump_mgr.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DUMP_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DUMP_MGR_H + +#include + +#include "form_db_info.h" +#include "form_host_record.h" +#include "form_dump_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormDumpMgr + * Form dump mgr. + */ +class FormDumpMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormDumpMgr) +public: + DISALLOW_COPY_AND_MOVE(FormDumpMgr); + + /** + * @brief Dump all of form storage infos. + * @param storageInfos Form storage infos + * @param formInfos Form storage dump info. + */ + void DumpStorageFormInfos(const std::vector &storageInfos, std::string &formInfos) const; + /** + * @brief Dump form infos. + * @param formRecordInfos Form record infos. + * @param formInfos Form dump infos. + */ + void DumpFormInfos(const std::vector &formRecordInfos, std::string &formInfos) const; + /** + * @brief Dump form infos. + * @param formRecordInfo Form Host record info. + * @param formInfo Form dump info. + */ + void DumpFormHostInfo(const FormHostRecord &formHostRecord, std::string &formInfo) const; + /** + * @brief Dump form infos. + * @param formRecordInfo Form record info. + * @param formInfo Form dump info. + */ + void DumpFormInfo(const FormRecord &formRecordInfo, std::string &formInfo) const; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DUMP_MGR_H diff --git a/services/formmgr/include/form_event_notify_connection.h b/services/formmgr/include/form_event_notify_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..5a1520761ac9bc05b08c7ecf76a86e10d8b45710 --- /dev/null +++ b/services/formmgr/include/form_event_notify_connection.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormEventNotifyConnection + * Form Event Notify Connection Stub. + */ +class FormEventNotifyConnection : public FormAbilityConnection { +public: + FormEventNotifyConnection(const std::vector formEvents, const int32_t formVisibleType, + const std::string &bundleName, const std::string &abilityName); + virtual ~FormEventNotifyConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + std::vector formEvents_; + int32_t formVisibleType_; + DISALLOW_COPY_AND_MOVE(FormEventNotifyConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_host_callback.h b/services/formmgr/include/form_host_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..fafe033c0058126c61a7d653096fa8c38740fa20 --- /dev/null +++ b/services/formmgr/include/form_host_callback.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_HOST_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_HOST_CALLBACK_H + +#include + +#include "form_js_info.h" +#include "form_record.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostCallback + * FormHost callback is used to call form host service. + */ +class FormHostCallback { +public: + FormHostCallback() = default; + virtual ~FormHostCallback() = default; + /** + * @brief Request to give back a Form. + * @param formId The Id of the forms to create. + * @param record Form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + void OnAcquired(const int64_t formId, const FormRecord &record, const sptr &callerToken); + + /** + * @brief Form is updated. + * @param formId The Id of the form to update. + * @param record Form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + void OnUpdate(const int64_t formId, const FormRecord &record, const sptr &callerToken); + + /** + * @brief Form provider is uninstalled. + * @param formIds The Id list of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + void OnUninstall(std::vector &formIds, const sptr &callerToken); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_HOST_CALLBACK_H diff --git a/services/formmgr/include/form_host_record.h b/services/formmgr/include/form_host_record.h new file mode 100644 index 0000000000000000000000000000000000000000..b50a992c17f2de0d2f267c48bea28feef5d7e4ac --- /dev/null +++ b/services/formmgr/include/form_host_record.h @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H + +#include +#include +#include +#include "app_log_wrapper.h" +#include "form_host_callback.h" +#include "form_item_info.h" +#include "form_record.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostRecord + * Form host data. + */ +class FormHostRecord { +public: + /** + * @brief Create form host record. + * @param callback remote object. + * @param callingUid Calling uid. + */ + static FormHostRecord CreateRecord(const FormItemInfo &info, const sptr &callback, int callingUid); + /** + * @brief Add form id. + * @param formId The Id of the form. + */ + void AddForm(int64_t formId); + /** + * @brief Delete form id. + * @param formId The Id of the form. + */ + void DelForm(int64_t formId); + /** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ + bool IsEmpty() const; + /** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ + bool Contains(int64_t formId) const; + + /** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetEnableRefresh(int64_t formId, bool flag); + + /** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsEnableRefresh(int64_t formId) const; + + /** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetNeedRefresh(int64_t formId, bool flag); + /** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsNeedRefresh(int64_t formId) const; + + /** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnAcquire(int64_t id, const FormRecord &record); + + /** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnUpdate(int64_t id, const FormRecord &record); + /** + * Send form uninstall message to form host. + * + * @param id The Id of the form. + * @param record Form record. + */ + void OnFormUninstalled(std::vector &formIds); + + /** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ + void CleanResource(); + /** + * @brief Get callerUid_. + * @return callerUid_. + */ + int GetCallerUid() const + { + return callerUid_; + } + /** + * @brief Get clientStub_. + * @return clientStub_. + */ + sptr GetClientStub() const; + /** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ + sptr GetDeathRecipient() const; + /** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ + void SetCallerUid(const int callerUid); + /** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ + void SetClientStub(const sptr &clientStub); + /** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ + void SetClientImpl(const std::shared_ptr &clientImpl); + /** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ + void SetDeathRecipient(const sptr &deathRecipient); + /** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ + void AddDeathRecipient(const sptr& deathRecipient); + /** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ + std::string GetHostBundleName() const; + /** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ + void SetHostBundleName(const std::string &hostBundleName); + +private: + int callerUid_ = 0; + sptr clientStub_ = nullptr; + std::shared_ptr clientImpl_ = nullptr; + sptr deathRecipient_ = nullptr; + std::unordered_map forms_; + std::unordered_map needRefresh_; + std::string hostBundleName_ = ""; + + /** + * @class ClientDeathRecipient + * notices IRemoteBroker died. + */ + class ClientDeathRecipient : public IRemoteObject::DeathRecipient { + public: + /** + * @brief Constructor + */ + ClientDeathRecipient() = default; + ~ClientDeathRecipient() = default; + /** + * @brief handle remote object died event. + * @param remote remote object. + */ + void OnRemoteDied(const wptr &remote) override; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H \ No newline at end of file diff --git a/services/formmgr/include/form_id_key.h b/services/formmgr/include/form_id_key.h new file mode 100644 index 0000000000000000000000000000000000000000..53da57e89f19e5af8e4e03c0292c334dff6d6cd4 --- /dev/null +++ b/services/formmgr/include/form_id_key.h @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2021 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ID_KEY_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ID_KEY_H + +#include + +namespace OHOS { +namespace AppExecFwk { +struct FormIdKey { +public: + + std::string bundleName; + std::string moduleName; + std::string abilityName; + std::string formName; + int specificationId; + int orientation; + + bool operator== (const FormIdKey &formIdKey) const + { + return specificationId == formIdKey.specificationId + && orientation == formIdKey.orientation + && bundleName == formIdKey.bundleName + && moduleName == formIdKey.moduleName + && abilityName == formIdKey.abilityName + && formName == formIdKey.formName; + } + /** + * @brief overloaded == for Indicates the formDBInfo by formId + * @return Returns true if the data equal; returns false otherwise. + */ + bool operator< (const FormIdKey &formIdKey) const + { + return specificationId != formIdKey.specificationId + || orientation != formIdKey.orientation + || bundleName != formIdKey.bundleName + || moduleName != formIdKey.moduleName + || abilityName != formIdKey.abilityName + || formName != formIdKey.formName; + } + int hashCode() + { + return std::hash()(bundleName) + + std::hash()(moduleName) + + std::hash()(abilityName) + + std::hash()(formName) + + std::hash()(specificationId) + + std::hash()(orientation); + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ID_KEY_H diff --git a/services/formmgr/include/form_info_mgr.h b/services/formmgr/include/form_info_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..42bfdb441b6d62d01750d96631742b255f6820ad --- /dev/null +++ b/services/formmgr/include/form_info_mgr.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_INFO_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_INFO_MGR_H + +#include +#include +#include + +#include "appexecfwk_errors.h" +#include "bundle_info.h" +#include "form_info.h" + +namespace OHOS { +namespace AppExecFwk { +class FormInfoHelper { +public: + static ErrCode LoadFormConfigInfoByBundleName(const std::string &bundleName, std::vector &formInfos); + +private: + static ErrCode LoadAbilityFormConfigInfo(const BundleInfo &bundleInfo, std::vector &formInfos); + + static ErrCode LoadStageFormConfigInfo(const BundleInfo &bundleInfo, std::vector &formInfos); +}; + +class BundleFormInfo { +public: + explicit BundleFormInfo(std::string bundleName); + + ErrCode InitFromJson(const std::string &formInfosJson); + + ErrCode Update(); + + ErrCode Remove(); + + bool Empty(); + + ErrCode GetAllFormsInfo(std::vector &formInfos); + + ErrCode GetFormsInfoByModule(const std::string &moduleName, std::vector &formInfos); + +private: + std::string bundleName_ {}; + mutable std::shared_timed_mutex formInfosMutex_ {}; + std::vector formInfos_ {}; +}; + +class FormInfoMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormInfoMgr) + +public: + DISALLOW_COPY_AND_MOVE(FormInfoMgr); + + ErrCode Start(); + + ErrCode Update(const std::string &bundleName); + + ErrCode Remove(const std::string &bundleName); + + ErrCode GetAllFormsInfo(std::vector &formInfos); + + ErrCode GetFormsInfoByBundle(const std::string &bundleName, std::vector &formInfos); + + ErrCode GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfos); + +private: + std::shared_ptr GetOrCreateBundleFromInfo(const std::string &bundleName); + + mutable std::shared_timed_mutex bundleFormInfoMapMutex_ {}; + std::unordered_map> bundleFormInfoMap_ {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_INFO_MGR_H diff --git a/services/formmgr/include/form_info_storage_mgr.h b/services/formmgr/include/form_info_storage_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..a7d88f7d2f5ec45160af1f23d8adc935fac811a1 --- /dev/null +++ b/services/formmgr/include/form_info_storage_mgr.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_INFO_STORAGE_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_INFO_STORAGE_MGR_H + +#include +#include +#include +#include "appexecfwk_errors.h" +#include "distributed_kv_data_manager.h" +#include "kvstore_death_recipient.h" + +namespace OHOS { +namespace AppExecFwk { +class KvStoreDeathRecipientCallbackFormInfoStorage : public DistributedKv::KvStoreDeathRecipient { +public: + KvStoreDeathRecipientCallbackFormInfoStorage(); + + virtual ~KvStoreDeathRecipientCallbackFormInfoStorage(); + + virtual void OnRemoteDied() override; +}; + +/** + * @class FormInfoStorageMgr + * Form info storage. + */ +class FormInfoStorageMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormInfoStorageMgr) + +public: + DISALLOW_COPY_AND_MOVE(FormInfoStorageMgr); + + ErrCode LoadFormInfos(std::vector> &formInfos); + + ErrCode GetBundleFormInfos(const std::string &bundleName, std::string &formInfos); + + ErrCode SaveBundleFormInfos(const std::string &bundleName, const std::string &formInfos); + + ErrCode RemoveBundleFormInfos(const std::string &bundleName); + + ErrCode UpdateBundleFormInfos(const std::string &bundleName, const std::string &formInfos); + + bool ResetKvStore(); + +private: + void RegisterKvStoreDeathListener(); + + DistributedKv::Status GetKvStore(); + + bool CheckKvStore(); + + DistributedKv::Status GetEntries(std::vector &allEntries); + + const DistributedKv::AppId appId_ {"form_storage"}; + const DistributedKv::StoreId storeId_ {"form_infos"}; + DistributedKv::DistributedKvDataManager dataManager_; + std::shared_ptr kvStorePtr_; + mutable std::mutex kvStorePtrMutex_; + const int32_t MAX_TIMES = 600; // 1min + const int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_INFO_STORAGE_MGR_H diff --git a/services/formmgr/include/form_item_info.h b/services/formmgr/include/form_item_info.h new file mode 100644 index 0000000000000000000000000000000000000000..bb9f85873eac651f3bf99b980457212d80840b62 --- /dev/null +++ b/services/formmgr/include/form_item_info.h @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CONFIG_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CONFIG_INFO_H + +#include +#include +#include +#include +#include "form_info_base.h" +#include "form_record.h" + +namespace OHOS { +namespace AppExecFwk { +class FormItemInfo { +public: + /** + * @brief Get formId_. + * @return formId_. + */ + int64_t GetFormId() const; + /** + * @brief Set value of formId_. + * @param formId Form Id. + */ + void SetFormId(int64_t formId); + /** + * @brief Get packageName_. + * @return packageName_. + */ + std::string GetPackageName() const; + /** + * @brief Set value of packageName_. + * @param packageName Package name. + */ + void SetPackageName(const std::string &packageName); + /** + * @brief Get providerBundleName_. + * @return providerBundleName_. + */ + std::string GetProviderBundleName() const; + /** + * @brief Set value of providerBundleName_. + * @param providerBundleName Provider bundle Name. + */ + void SetProviderBundleName(const std::string &providerBundleName_); + /** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ + std::string GetHostBundleName() const; + /** + * @brief Set value of hostBundleName_. + * @param hostBundleName_ Host bundle Name. + */ + void SetHostBundleName(const std::string &hostBundleName_); + /** + * @brief Get moduleName_. + * @return moduleName_. + */ + std::string GetModuleName() const; + /** + * @brief Set value of moduleName_. + * @param moduleName Module Name. + */ + void SetModuleName(const std::string &moduleName); + /** + * @brief Get abilityName_. + * @return abilityName_. + */ + std::string GetAbilityName() const; + /** + * @brief Set value of abilityName_. + * @param abilityName Ability name. + */ + void SetAbilityName(const std::string &abilityName); + /** + * @brief Get formName_. + * @return formName_. + */ + std::string GetFormName() const; + /** + * @brief Set value of formName_. + * @param formName Form name. + */ + void SetFormName(const std::string &formName); + /** + * @brief Get jsComponentName_. + * @return jsComponentName_. + */ + std::string GetJsComponentName() const; + /** + * @brief Set value of jsComponentName_. + * @param jsComponentName Js component name. + */ + void SetJsComponentName(const std::string &jsComponentName); + /** + * @brief Get abilityModuleName_. + * @return abilityModuleName_. + */ + std::string GetAbilityModuleName() const; + /** + * @brief Set value of abilityModuleName_. + * @param abilityModuleName ability module name_. + */ + void SetAbilityModuleName(const std::string &abilityModuleName); + /** + * @brief Get specificationId_. + * @return specificationId_. + */ + int GetSpecificationId() const; + /** + * @brief Set value of specificationId_. + * @param specificationId Specification id. + */ + void SetSpecificationId(const int specificationId); + + /** + * @brief Obtains the updageFlag. + * @return Returns updageFlag. + */ + bool IsEnableUpdateFlag() const; + /** + * @brief Set value of updateFlag_. + * @param IsEnableUpdateFlag Enable update flag or not. + */ + void SetEnableUpdateFlag(bool IsEnableUpdateFlag); + /** + * @brief Get updateDuration_. + * @return updateDuration_. + */ + int GetUpdateDuration() const; + /** + * @brief Set value of updateDuration_. + * @param updateDuration Update duration. + */ + void SetUpdateDuration(int updateDuration); + /** + * @brief Get scheduledUpdateTime_. + * @return scheduledUpdateTime_. + */ + std::string GetScheduledUpdateTime() const; + /** + * @brief Set value of scheduledUpdateTime_. + * @param scheduledUpdateTime Scheduled update time. + */ + void SetScheduledUpdateTime(const std::string &scheduledUpdateTime); + /** + * @brief Get hapSourceDirs_. + * @param dirs Hap source dirs. + * @return Returns true on success, false on failure. + */ + bool GetHapSourceDirs(std::vector &dirs) const; + /** + * @brief Add hap source dir. + * @param hapSourceDir Hap source dir. + */ + void AddHapSourceDirs(const std::string &hapSourceDir); + /** + * @brief Set value of hapSourceDirs_. + * @param hapSourceDirs Hap source dirs. + */ + void SetHapSourceDirs(const std::vector &hapSourceDirs); + /** + * @brief Obtains the temporaryFlag. + * @return Returns temporaryFlag. + */ + bool IsTemporaryForm() const; + /** + * @brief Set value of temporaryFlag_. + * @param temporaryFlag Temporary flag. + */ + void SetTemporaryFlag(bool temporaryFlag); + /** + * @brief Obtains the hap source by ability module name. + * @param moduleName ability module name + * @return Returns hap source. + */ + std::string GetHapSourceByModuleName(const std::string &moduleName) const; + /** + * @brief Add module info. + * @param moduleName Module name. + * @param moduleSourceDir Module source dir. + */ + void AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir); + /** + * @brief Check if item valid or not. + * @return Valid or not + */ + bool IsValidItem() const; + /** + * @brief Check if item match or not. + * @return Match or not + */ + bool IsMatch(const FormRecord &record) const; + /** + * @brief Check if form config same or not. + * @return Same or not + */ + bool IsSameFormConfig(const FormRecord &record) const; + /** + * @brief Check if visible notify or not. + * @return visible notify or not + */ + bool IsFormVisibleNotify() const; + /** + * @brief Set value of formVisibleNotify_. + * @param isFormVisibleNotify visible notify or not. + */ + void SetFormVisibleNotify(bool isFormVisibleNotify); + /** + * @brief Get formSrc_. + * @return formSrc_. + */ + std::string GetFormSrc() const; + /** + * @brief Set value of formSrc_. + * @param formSrc form src. + */ + void SetFormSrc(const std::string &formSrc); + /** + * @brief Get formWindow_. + * @return formWindow_. + */ + FormWindow GetFormWindow() const; + /** + * @brief Set value of formWindow_. + * @param formWindow form window. + */ + void SetFormWindow(const FormWindow &formWindow); + /** + * @brief Get versionCode_. + * @return versionCode_. + */ + uint32_t GetVersionCode() const; + /** + * @brief Set value of versionCode_. + * @param versionCode bundle version code. + */ + void SetVersionCode(const uint32_t versionCode); + /** + * @brief Get versionName_. + * @return versionName_. + */ + std::string GetVersionName() const; + /** + * @brief Set value of versionName_. + * @param versionName bundle version name. + */ + void SetVersionName(const std::string &versionName); + /** + * @brief Get compatibleVersion_. + * @return compatibleVersion_. + */ + uint32_t GetCompatibleVersion() const; + /** + * @brief Set value of compatibleVersion_. + * @param compatibleVersion API compatible version. + */ + void SetCompatibleVersion(const uint32_t &compatibleVersion); + /** + * @brief Get icon_. + * @return icon_. + */ + std::string GetIcon() const; + /** + * @brief Set value of icon_. + * @param icon ability icon. + */ + void SetIcon(const std::string &icon); + +private: + /** + * @brief Equal or not. + * @param left left string. + * @param right right string. + * @return Equal or not + */ + bool IsEqual(const std::string &left, const std::string &right); + +private: + int64_t formId_ = -1; + std::string packageName_ = ""; + std::string providerBundleName_ = ""; + std::string hostBundleName_ = ""; + std::string moduleName_ = ""; + std::string abilityName_ = ""; + std::string formName_ = ""; + int32_t specificationId_ = 0; + bool updateFlag_ = false; + int32_t updateDuration_ = 0; + std::string scheduledUpdateTime_ = ""; + std::vector hapSourceDirs_; + bool temporaryFlag_ = false; + bool formVisibleNotify_ = false; + std::string formSrc_ = ""; + FormWindow formWindow_; + uint32_t versionCode_ = 0; + std::string versionName_ = ""; + uint32_t compatibleVersion_ = 0; + std::string icon_ = ""; + + std::string jsComponentName_ = ""; + std::string abilityModuleName_ = ""; + std::unordered_map moduleInfoMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CONFIG_INFO_H diff --git a/services/formmgr/include/form_mgr_adapter.h b/services/formmgr/include/form_mgr_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..cc66dc131df39137fb21d85a69ef6f8f53b2b3e9 --- /dev/null +++ b/services/formmgr/include/form_mgr_adapter.h @@ -0,0 +1,496 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H + +#include +#include + +#include "bundle_info.h" +#include "bundle_mgr_interface.h" +#include "form_info.h" +#include "form_host_record.h" +#include "form_item_info.h" +#include "form_js_info.h" +#include "form_provider_data.h" +#include "form_db_info.h" +#include "ipc_types.h" +#include "iremote_object.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +using WantParams = OHOS::AAFwk::WantParams; +/** + * @class FormMgrAdapter + * Form request handler from form host. + */ +class FormMgrAdapter final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormMgrAdapter) +public: + DISALLOW_COPY_AND_MOVE(FormMgrAdapter); + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, FormJsInfo &formInfo); + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DeleteForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Release forms with formIds, send formIds to form Mgr service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache); + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formProviderData form provider data. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const std::string &bundleName, const FormProviderData &formProviderData); + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ + int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want); + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * + * @param formIds The vector of form Ids. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType); + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int CastTempForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpStorageFormInfos(std::string &formInfos) const; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) const; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const; + /** + * @brief Dump form timer by form id. + * @param formId The id of the form. + * @param formInfo Form timer. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) const; + + /** + * @brief set next refresh time. + * @param formId The id of the form. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshTime(const int64_t formId, const int64_t nextTime); + + /** + * @brief enable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int EnableUpdateForm(const std::vector formIDs, const sptr &callerToken); + + /** + * @brief disable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DisableUpdateForm(const std::vector formIDs, const sptr &callerToken); + + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken); + + /** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void AcquireProviderFormInfo(const int64_t formId, const Want &want, const sptr &remoteObject); + /** + * @brief Notify form provider for delete form. + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns forms count to add. + */ + int BatchAddFormRecords(const Want &want); + /** + * @brief Clear form records for st limit value test. + * @return Returns forms count to delete. + */ + int ClearFormRecords(); + + /** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + int DistributedDataAddForm(const Want &want); + + /** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ + int DistributedDataDeleteForm(const std::string &formId); + + /** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ + int GetAllFormsInfo(std::vector &formInfos); + + /** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ + int GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos); + + /** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ + int GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector &formInfos); +private: + /** + * @brief Get form configure info. + * @param want The want of the request. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetFormConfigInfo(const Want& want, FormItemInfo &formItemInfo); + /** + * @brief Get bundle info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param packageName Package name. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundleInfo, std::string &packageName); + /** + * @brief Get form info. + * @param want The want of the request. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo); + /** + * @brief Get form configure info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetFormItemInfo(const AAFwk::Want &want, const BundleInfo &bundleInfo, const FormInfo &formInfo, + FormItemInfo &formItemInfo); + /** + * @brief Dimension valid check. + * @param formInfo Form info. + * @param dimensionId Dimension id. + * @return Returns true on success, false on failure. + */ + bool IsDimensionValid(const FormInfo &formInfo, int dimensionId) const; + /** + * @brief Create form configure info. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param itemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode CreateFormItemInfo(const BundleInfo& bundleInfo, const FormInfo& formInfo, FormItemInfo& itemInfo); + /** + * @brief Allocate form by formId. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AllotFormById(const FormItemInfo &info, const sptr &callerToken, + const WantParams &wantParams, FormJsInfo &formInfo); + /** + * @brief Allocate form by form configure info. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AllotFormByInfo(const FormItemInfo &info, const sptr &callerToken, + const WantParams& wantParams, FormJsInfo &formInfo); + /** + * @brief Acquire form data from form provider. + * @param formId The Id of the form.. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AcquireProviderFormInfoAsync(const int64_t formId, const FormItemInfo &info, const WantParams &wantParams); + + /** + * @brief Handle release form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleReleaseForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Handle delete form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleDeleteForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Handle delete temp form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleDeleteTempForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Handle delete form storage. + * @param dbRecord Form storage information. + * @param uid calling user id. + * @param formId The form id. + * @return Function result and has other host flag. + */ + ErrCode HandleDeleteFormCache(FormRecord &dbRecord, const int uid, const int64_t formId); + + /** + * @brief Padding udid hash. + * @param formId The form id. + * @return Padded form id. + */ + int64_t PaddingUDIDHash(const int64_t formId) const; + + /** + * @brief Add existed form record. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param record Form data. + * @param formId The form id. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddExistFormRecord(const FormItemInfo &info, const sptr &callerToken, + const FormRecord &record, const int64_t formId, const WantParams &wantParams, FormJsInfo &formInfo); + + /** + * @brief Add new form record. + * @param info Form configure info. + * @param formId The form id. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddNewFormRecord(const FormItemInfo &info, const int64_t formId, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo); + + /** + * @brief Send event notify to form provider. The event notify type include FORM_VISIBLE and FORM_INVISIBLE. + * + * @param providerKey The provider key string which consists of the provider bundle name and ability name. + * @param formIdsByProvider The map of form Ids and their event type which have the same provider. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleEventNotify(const std::string &providerKey, const std::vector &formIdsByProvider, + const int32_t formVisibleType); + + /** + * @brief Increase the timer refresh count. + * + * @param formId The form id. + * @return none. + */ + void IncreaseTimerRefreshCount(const int64_t formId); + + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleUpdateFormFlag(const std::vector formIds, + const sptr &callerToken, const bool flag); + + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ + bool IsFormCached(const FormRecord record); + + /** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param nextTime next refresh time. + * @param userId User ID. + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshtTimeLocked(const int64_t formId, const int64_t nextTime, const int32_t userId = 0); + + /** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param bundleName Provider ability bundleName. + * @return Returns true or false. + */ + bool IsUpdateValid(const int64_t formId, const std::string &bundleName); + /** + * @brief Handle cast temp form. + * @param formId The form id. + * @param record Form information. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleCastTempForm(const int64_t formId, const FormRecord &record); + + /** + * @brief Add form timer. + * @param formRecord Form information. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddFormTimer(const FormRecord &formRecord); + + /** + * @brief get bundleName. + * @param bundleName for output. + * @return Returns true on success, others on failure. + */ + bool GetBundleName(std::string &bundleName); + + /** + * @brief Update provider info to host + * + * @param matchedFormId The Id of the form + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param formRecord Form storage information + * @return Returns true on success, false on failure. + */ + bool UpdateProviderInfoToHost(const int64_t matchedFormId, const sptr &callerToken, + const int32_t formVisibleType, FormRecord &formRecord); + + /** + * @brief If the form provider is system app and the config item 'formVisibleNotify' is true, + * notify the form provider that the current form is visible. + * + * @param bundleName BundleName + * @return Returns true if the form provider is system app, false if not. + */ + bool CheckIsSystemAppByBundleName(const sptr &iBundleMgr, const std::string &bundleName); + /** + * @brief Create eventMaps for event notify. + * + * @param matchedFormId The Id of the form + * @param formRecord Form storage information + * @param eventMaps eventMaps for event notify + * @return Returns true on success, false on failure. + */ + bool CreateHandleEventMap(const int64_t matchedFormId, const FormRecord &formRecord, + std::map> &eventMaps); + /** + * @brief Get current user ID. + * @param callingUid calling Uid. + * @return Returns user ID. + */ + int32_t GetCurrentUserId(const int callingUid); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H diff --git a/services/formmgr/include/form_mgr_service.h b/services/formmgr/include/form_mgr_service.h new file mode 100644 index 0000000000000000000000000000000000000000..ffb36aa484b0f3f1bcedeb7c93efe18d7b05e074 --- /dev/null +++ b/services/formmgr/include/form_mgr_service.h @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_SERVICE_H + +#include +#include +#include +#include +#include +#include + +#include "event_handler.h" +#include "form_mgr_stub.h" +#include "form_provider_data.h" +#include "form_sys_event_receiver.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +/** + * @class FormMgrService + * FormMgrService provides a facility for managing form life cycle. + */ +class FormMgrService : public SystemAbility, + public FormMgrStub, + public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(FormMgrService); + DECLEAR_SYSTEM_ABILITY(FormMgrService); +public: + /** + * @brief Start envent for the form manager service. + */ + void OnStart() override; + /** + * @brief Stop envent for the form manager service. + */ + void OnStop() override; + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo) override; + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DeleteForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) override; + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param FormProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const std::string &bundleName, + const FormProviderData &FormProviderData) override; + + /** + * @brief set next refresh time. + * @param formId The id of the form. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshTime(const int64_t formId, const int64_t nextTime) override; + + /** + * @brief lifecycle update. + * @param formIds formIds of hostclient. + * @param callerToken Caller ability token. + * @param updateType update type,enable or disable. + * @return Returns true on success, false on failure. + */ + int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType) override; + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) override; + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType) override; + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int CastTempForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpStorageFormInfos(std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) override; + /** + * @brief Dump form timer by form id. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) override; + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) override; + + /** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + int BatchAddFormRecords(const Want &want) override; + /** + * @brief Clear form records for st limit value test. + * @return Returns ERR_OK on success, others on failure. + */ + int ClearFormRecords() override; + + /** + * @brief Check whether if the form manager service is ready. + * @return Returns true if the form manager service is ready; returns false otherwise. + */ + bool IsReady() const; + + /** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + int DistributedDataAddForm(const Want &want) override; + + /** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ + int DistributedDataDeleteForm(const std::string &formId) override; + + /** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ + int GetAllFormsInfo(std::vector &formInfos) override; + + /** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ + int GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) override; + + /** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ + int GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, + std::vector &formInfos) override; + +private: + /** + * @brief initialization of form manager service. + */ + ErrCode Init(); + + /** + * @brief Permission check by callingUid. + * @param formId the id of the form. + * @return Returns true on success, false on failure. + */ + bool CheckFormPermission(); + + /** + * @brief Permission check. + * @param bundleName bundleName. + * @return Returns true on success, false on failure. + */ + bool CheckFormPermission(const std::string &bundleName) const; +private: + ServiceRunningState state_; + + std::shared_ptr runner_ = nullptr; + std::shared_ptr handler_ = nullptr; + std::shared_ptr formSysEventReceiver_ = nullptr; + + bool resetFlag = false; + + mutable std::mutex instanceMutex_; + + sptr remote = nullptr; + + static const int32_t ENABLE_FORM_UPDATE = 5; + + DISALLOW_COPY_AND_MOVE(FormMgrService); +}; +static bool resetFlag = false; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_SERVICE_H diff --git a/services/formmgr/include/form_msg_event_connection.h b/services/formmgr/include/form_msg_event_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..96cb09ae57adff5757e7926c6bf6180884764334 --- /dev/null +++ b/services/formmgr/include/form_msg_event_connection.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormMsgEventConnection + * Form Refresh Connection Stub. + */ +class FormMsgEventConnection : public FormAbilityConnection { +public: + FormMsgEventConnection(const int64_t formId, const Want &want, + const std::string &bundleName, const std::string &abilityName); + virtual ~FormMsgEventConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormMsgEventConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_provider_mgr.h b/services/formmgr/include/form_provider_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..2cee0158a3885d16727939228ba9eec47253e242 --- /dev/null +++ b/services/formmgr/include/form_provider_mgr.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_MGRR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_MGRR_H +#include +#include +#include "form_provider_info.h" +#include "form_record.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormProviderMgr + * Form provider manager. + */ +class FormProviderMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormProviderMgr) +public: + DISALLOW_COPY_AND_MOVE(FormProviderMgr); + + /** + * @brief handle for acquire back event from provider. + * @param formId The id of the form. + * @param providerFormInfo provider form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AcquireForm(const int64_t formId, const FormProviderInfo &formProviderInfo); + /** + * @brief handle for update form event from provider. + * @param formId The id of the form. + * @param providerFormInfo provider form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateForm(const int64_t formId, const FormProviderInfo &formProviderInfo); + /** + * handle for update form event from provider. + * + * @param formId The id of the form. + * @param formRecord The form's record. + * @param formProviderData provider form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateForm(const int64_t formId, FormRecord &formRecord, const FormProviderData &formProviderData); + /** + * @brief Refresh form. + * + * @param formId The form id. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode RefreshForm(const int64_t formId, const Want &want); + /** + * @brief Connect ams for refresh form + * + * @param formId The form id. + * @param record Form data. + * @param want The want of the form. + * @param isTimerRefresh The flag of timer refresh. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ConnectAmsForRefresh(const int64_t formId, const FormRecord &record, const Want &want, + const bool isTimerRefresh); + /** + * @brief Notify provider form delete. + * @param formId The form id. + * @param record Form information. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode NotifyProviderFormDelete(const int64_t formId, const FormRecord &formRecord); + /** + * @brief Notify provider forms batch delete. + * @param bundleName BundleName. + * @param bundleName AbilityName. + * @param formIds form id list. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode NotifyProviderFormsBatchDelete(const std::string &bundleName, const std::string &abilityName, + const std::set &formIds); + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param record Form record. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const FormRecord &record, const Want &want); +private: + FormRecord GetFormAbilityInfo(const FormRecord &record) const; + /** + * @brief Increase the timer refresh count. + * + * @param formId The form id. + */ + void IncreaseTimerRefreshCount(const int64_t formId); + bool IsFormCached(const FormRecord &record); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_MGRR_H diff --git a/services/formmgr/include/form_record.h b/services/formmgr/include/form_record.h new file mode 100644 index 0000000000000000000000000000000000000000..4e25828e41eabfa4cea66d93c7502e59ca944a96 --- /dev/null +++ b/services/formmgr/include/form_record.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_RECORD_H + +#include +#include "form_info_base.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormRecord + * Form data. + */ +class FormRecord { +public: + int64_t formId; + bool isInited = false; + bool needFreeInstall = false; + bool versionUpgrade = false; + bool needRefresh = false; + bool isCountTimerRefresh = false; + std::string packageName = ""; + std::string bundleName = ""; + std::string moduleName = ""; + std::string abilityName = ""; + std::string formName = ""; + int32_t specification; + bool isEnableUpdate = false; + long updateDuration = false; + int updateAtHour = 0; + int updateAtMin = 0; + FormProviderInfo formProviderInfo; + std::vector hapSourceDirs; + std::string jsFormCodePath = ""; + bool formTempFlg = false; + std::vector formUserUids; + bool formVisibleNotify = false; + int formVisibleNotifyState = 0; + int32_t userId = 0; + std::string formSrc = ""; + FormWindow formWindow; + uint32_t versionCode = 0; + std::string versionName = ""; + uint32_t compatibleVersion = 0; + std::string icon = ""; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_RECORD_H diff --git a/services/formmgr/include/form_refresh_connection.h b/services/formmgr/include/form_refresh_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..87a0505d9dd670cba2a83840e239a129cfc43e88 --- /dev/null +++ b/services/formmgr/include/form_refresh_connection.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormRefreshConnection + * Form Refresh Connection Stub. + */ +class FormRefreshConnection : public FormAbilityConnection { +public: + FormRefreshConnection(const int64_t formId, const Want &want, + const std::string &bundleName, const std::string &abilityName); + virtual ~FormRefreshConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormRefreshConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_refresh_limiter.h b/services/formmgr/include/form_refresh_limiter.h new file mode 100644 index 0000000000000000000000000000000000000000..5f24db68e0e9f2030c620ab18f578241dc6a2ec2 --- /dev/null +++ b/services/formmgr/include/form_refresh_limiter.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_REFRESH_LIMITER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_REFRESH_LIMITER_H + +#include +#include +#include +#include "form_timer.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormRefreshLimiter + * Form refresh limite manager. + */ +class FormRefreshLimiter { +public: + /** + * @brief Add form limit info by formId. + * @param formId The form id. + * @return Returns true on success, false on failure. + */ + bool AddItem(int64_t formId); + /** + * @brief Delete form limit info by formId. + * @param formId The form id. + */ + void DeleteItem(int64_t formId); + /** + * @brief Reset limit info. + */ + void ResetLimit(); + /** + * @brief Refresh enable or not. + * @param formId The form id. + * @return Returns ERR_OK on success, others on failure. + */ + bool IsEnableRefresh(int64_t formId); + /** + * @brief Get refresh count. + * @param formId The form id. + * @return refresh count. + */ + int GetRefreshCount(int64_t formId) const; + /** + * @brief Increase refresh count. + * @param formId The form id. + */ + void Increase(int64_t formId); + /** + * @brief Mark remind flag. + * @param formId The form id. + */ + void MarkRemind(int64_t formId); + /** + * @brief Get remind list. + * @return remind list. + */ + std::vector GetRemindList() const; + /** + * @brief Get remind list and reset limit. + * @return remind list. + */ + std::vector GetRemindListAndResetLimit(); + /** + * @brief Get item count. + * @return Item count. + */ + int GetItemCount() const; +private: + mutable std::mutex limiterMutex_; + std::map limiterMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_REFRESH_LIMITER_H \ No newline at end of file diff --git a/services/formmgr/include/form_storage_mgr.h b/services/formmgr/include/form_storage_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..4160305513009d91b93b12034955bb21f0318482 --- /dev/null +++ b/services/formmgr/include/form_storage_mgr.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_STORAGE_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_STORAGE_MGR_H + +#include +#include +#include +#include + +#include "appexecfwk_errors.h" +#include "distributed_kv_data_manager.h" +#include "form_db_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormStorageMgr + * Form data storage. + */ +class FormStorageMgr { +public: + FormStorageMgr(); + virtual ~FormStorageMgr(); + /** + * @brief Load all form data from DB to innerFormInfos. + * @param innerFormInfos Storage all form data. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode LoadFormData(std::vector &innerFormInfos); + + /** + * @brief Get form data from DB to innerFormInfo with formId. + * @param innerFormInfo Storage form data. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo); + + /** + * @brief Save or update the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be save. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SaveStorageFormInfo(const InnerFormInfo &innerFormInfo); + + /** + * @brief Modify the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo); + + /** + * @brief Delete the form data in DB. + * @param formId The form data Id. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DeleteStorageFormInfo(const std::string &formId); + + void RegisterKvStoreDeathListener(); + bool ResetKvStore(); + +private: + void SaveEntries( + const std::vector &allEntries, std::vector &innerFormInfos); + DistributedKv::Status GetEntries(std::vector &allEntries); + void TryTwice(const std::function &func); + bool CheckKvStore(); + DistributedKv::Status GetKvStore(); + +private: + const DistributedKv::AppId appId_ {"form_storage"}; + const DistributedKv::StoreId storeId_ {"installed_form_datas"}; + DistributedKv::DistributedKvDataManager dataManager_; + std::shared_ptr kvStorePtr_; + // std::shared_ptr dataChangeListener_; + mutable std::mutex kvStorePtrMutex_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_STORAGE_MGR_H diff --git a/services/formmgr/include/form_supply_callback.h b/services/formmgr/include/form_supply_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..244721cffcbaed0dc85e257531c4647420ac6d7c --- /dev/null +++ b/services/formmgr/include/form_supply_callback.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H + +#include "form_ability_connection.h" +#include "form_supply_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyCallback + * form supply service stub. + */ +class FormSupplyCallback : public FormSupplyStub { +public: + FormSupplyCallback() = default; + virtual ~FormSupplyCallback() = default; + static sptr GetInstance(); + + /** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; + + /** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnEventHandle(const Want &want) override; + + /** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ + void AddConnection(sptr connection); + /** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ + void RemoveConnection(long connectId); + +private: + /** + * @brief check if disconnect ability or not. + * @param connection The ability connection. + */ + bool CanDisConnect(sptr &connection); +private: + static std::mutex mutex_; + static sptr instance_; + + mutable std::mutex conMutex_; + std::map> connections_; + DISALLOW_COPY_AND_MOVE(FormSupplyCallback); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H diff --git a/services/formmgr/include/form_sys_event_receiver.h b/services/formmgr/include/form_sys_event_receiver.h new file mode 100644 index 0000000000000000000000000000000000000000..b1ba1aa01cc586745bcfaea021dd6baf4a5bd350 --- /dev/null +++ b/services/formmgr/include/form_sys_event_receiver.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_RECEIVER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_RECEIVER_H + +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "form_id_key.h" +#include "form_info.h" +#include "form_record.h" +#include "form_timer.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSysEventReceiver + * Receive system common event. + */ +class FormSysEventReceiver : public EventFwk::CommonEventSubscriber { +public: + FormSysEventReceiver() = default; + FormSysEventReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo); + virtual ~FormSysEventReceiver() = default; + /** + * @brief System common event receiver. + * @param eventData Common event data. + */ + virtual void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; +private: + void HandleProviderUpdated(const std::string &bundleName); + bool ProviderFormUpdated(const int64_t formId, const FormRecord &formRecord, + const std::vector &targetForms); + void HandleBundleFormInfoChanged(const std::string &bundleName); + void HandleBundleFormInfoRemoved(const std::string &bundleName); + void HandleProviderRemoved(const std::string &bundleName); + void HandleBundleDataCleared(const std::string &bundleName, const int uid); + void HandleFormHostDataCleared(const int uid); + void ClearFormDBRecordData(const int uid, std::map &removedFormsMap); + void ClearTempFormRecordData(const int uid, std::map &removedFormsMap); + void BatchDeleteNoHostDBForms(const int uid, std::map> &noHostFormDbMap, + std::map &removedFormsMap); + void HandleUserIdRemoved(const int32_t userId); // multiuser + /** + * @brief Delete no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ + void BatchDeleteNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, + std::map &foundFormsMap); + void ReCreateForm(const int64_t formId); + bool IsSameForm(const FormRecord &record, const FormInfo &formInfo); + void GetTimerCfg(const bool updateEnabled, const int updateDuration, const std::string &configUpdateAt, + FormTimerCfg &cfg); + void HandleTimerUpdate(const int64_t formId, const FormRecord &record, const FormTimerCfg &timerCfg); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_RECEIVER_H \ No newline at end of file diff --git a/services/formmgr/include/form_task_mgr.h b/services/formmgr/include/form_task_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..7403f50a0d0f6b7f23736fc3de24c23df17416d7 --- /dev/null +++ b/services/formmgr/include/form_task_mgr.h @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TASK_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TASK_MGR_H + +#include +#include + +#include "event_handler.h" +#include "form_item_info.h" +#include "form_js_info.h" +#include "form_provider_info.h" +#include "form_record.h" +#include "ipc_types.h" +#include "iremote_object.h" +#include "form_record.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +using WantParams = OHOS::AAFwk::WantParams; +/** + * @class FormTaskMgr + * form task manager. + */ +class FormTaskMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormTaskMgr) + +public: + DISALLOW_COPY_AND_MOVE(FormTaskMgr); + + /** + * @brief SetEventHandler. + * @param handler event handler + */ + inline void SetEventHandler(const std::shared_ptr &handler) + { + eventHandler_ = handler; + } + + /** + * @brief Acquire form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostAcquireTask(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Delete form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostDeleteTask(const int64_t formId, const Want &want, const sptr &remoteObject); + /** + * @brief Notify provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostProviderBatchDeleteTask(std::set &formIds, const Want &want, + const sptr &remoteObject); + /** + * @brief Refresh form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void PostRefreshTask(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Cast temp form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void PostCastTempTask(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Post form data to form host(task) when acquire form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + + void PostAcquireTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Post form data to form host(task) when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + void PostUpdateTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Handel form host died(task). + * @param remoteHost Form host proxy object. + */ + void PostHostDiedTask(const sptr &remoteHost); + + /** + * @brief Post event notify to form provider. + * + * @param formEvent The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ + void PostEventNotifyTask(const std::vector &formEvent, const int32_t formVisibleType, const Want &want, + const sptr &remoteObject); + + /** + * @brief Post message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostFormEventTask(const int64_t formId, const std::string &message, const Want &want, + const sptr &remoteObject); + + /** + * @brief Post uninstall message to form host(task). + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ + void PostUninstallTaskToHost(const std::vector &formIds, const sptr &remoteObject); +private: + /** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void AcquireProviderFormInfo(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Notify form provider for delete form. + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Notify form provider for updating form. + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Event notify to form provider. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ + void EventNotify(const std::vector &formEvents, const int32_t formVisibleType, const Want &want, + const sptr &remoteObject); + + /** + * @brief Notify form provider for cast temp form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyCastTemp(const int64_t formId, const Want &want, const sptr &remoteObject); + /** + * @brief Post form data to form host when acquire form.. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + void AcquireTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Post form data to form host when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + void UpdateTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ + void HostDied(const sptr &remoteHost); + + /** + * @brief Post provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void ProviderBatchDelete(std::set &formIds, const Want &want, const sptr &remoteObject); + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &remoteObject); + + /** + * @brief Handle uninstall message. + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ + void FormUninstall(const std::vector &formIds, const sptr &remoteObject); + + /** + * @brief Create form data for form host. + * @param formId The Id of the form. + * @param record Form record. + * @return Form data. + */ + FormJsInfo CreateFormJsInfo(const int64_t formId, const FormRecord &record); + +private: + std::shared_ptr eventHandler_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TASK_MGR_H diff --git a/services/formmgr/include/form_timer.h b/services/formmgr/include/form_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..e52bac2530ccd5acfe5e7b8292e030d066869fac --- /dev/null +++ b/services/formmgr/include/form_timer.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H + +namespace OHOS { +namespace AppExecFwk { +/** + * @enum UpdateType + * Update type. + */ +enum UpdateType { + TYPE_INTERVAL_CHANGE, + TYPE_ATTIME_CHANGE, + TYPE_INTERVAL_TO_ATTIME, + TYPE_ATTIME_TO_INTERVAL, + TYPE_INTERVAL_ONCE, +}; +/** + * @class FormTimer + * form timer task. + */ +class FormTimer { +public: + int64_t formId; + int32_t userId; + int64_t period; + int hour; + int min; + bool isUpdateAt; + int64_t refreshTime; + bool isEnable = true; + bool isCountTimer = false; + UpdateType type = UpdateType::TYPE_INTERVAL_CHANGE; + + FormTimer() + { + formId = -1; + userId = -1; + period = -1; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = false; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + + FormTimer(int64_t id, bool countTimer, int32_t uId = 0) + { + formId = id; + userId = uId; + period = -1; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = countTimer; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + + FormTimer(int64_t id, long repeatTime, int32_t uId = 0) + { + formId = id; + userId = uId; + period = repeatTime; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = true; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + + FormTimer(int64_t id, int hourTime, int minTime, int32_t uId = 0) + { + formId = id; + userId = uId; + hour = hourTime; + min = minTime; + period = -1; + isUpdateAt = true; + isCountTimer = false; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + ~FormTimer(void){ + } +}; +/** + * @class UpdateAtItem + * Update item at time. + */ +class UpdateAtItem { +public: + int updateAtTime = -1; + FormTimer refreshTask; +}; +/** + * @class DynamicRefreshItem + * Dynamic refresh item. + */ +class DynamicRefreshItem { +public: + int64_t formId = 0L; + int64_t settedTime = -1L; + int32_t userId = -1; + DynamicRefreshItem(){} + + DynamicRefreshItem(int64_t id, int64_t time, int32_t uId = 0) + { + formId = id; + settedTime = time; + userId = uId; + } + ~DynamicRefreshItem(void){ + } +}; +/** + * @struct LimitInfo + * Limit info about a form. + */ +struct LimitInfo { + int refreshCount = 0; + bool isReported = false; + bool remindFlag = false; +}; + +/** + * @struct FormTimerCfg + * Form timer config info. + */ +struct FormTimerCfg { + bool enableUpdate = false; + int64_t updateDuration = 0L; + int updateAtHour = -1; + int updateAtMin = -1; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H diff --git a/services/formmgr/include/form_timer_mgr.h b/services/formmgr/include/form_timer_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..23e9cf5da7878c83c7c3c9ea05277f8eb1ba93a2 --- /dev/null +++ b/services/formmgr/include/form_timer_mgr.h @@ -0,0 +1,376 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_MGR_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "form_refresh_limiter.h" +#include "form_timer.h" +#include "thread_pool.h" +#include "time_service_client.h" +// #include "timer.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::Notification::WantAgent; +/** + * @class FormTimerMgr + * form timer task manager. + */ +class FormTimerMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormTimerMgr) +public: + DISALLOW_COPY_AND_MOVE(FormTimerMgr); + /** + * @brief Add form timer by timer task. + * @param task The form timer task. + * @return Returns true on success, false on failure. + */ + bool AddFormTimer(const FormTimer &task); + /** + * @brief Add duration form timer. + * @param formId The Id of the form. + * @param updateDuration Update duration. + * @param userId User ID. + * @return Returns true on success, false on failure. + */ + bool AddFormTimer(const int64_t formId, const long updateDuration, const int32_t userId = 0); + /** + * @brief Add scheduled form timer. + * @param formId The Id of the form. + * @param updateAtHour Hour + * @param updateAtMin Min + * @param userId User ID. + * @return Returns true on success, false on failure. + */ + bool AddFormTimer(const int64_t formId, const long updateAtHour, const long updateAtMin, const int32_t userId = 0); + /** + * @brief Remove form timer by form id. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool RemoveFormTimer(const int64_t formId); + /** + * @brief Update form timer. + * @param formId The Id of the form. + * @param type Timer type. + * @param timerCfg Timer config. + * @return Returns true on success, false on failure. + */ + bool UpdateFormTimer(const int64_t formId, const UpdateType &type, const FormTimerCfg &timerCfg); + /** + * @brief Is limiter enable refresh. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool IsLimiterEnableRefresh(const int64_t formId); + /** + * @brief Increase refresh count. + * @param formId The Id of the form. + */ + void IncreaseRefreshCount(const int64_t formId); + /** + * @brief Set next refresh time. + * @param formId The Id of the form. + * @param nextGapTime Next gap time. + * @param userId User ID. + * @return Returns true on success, false on failure. + */ + bool SetNextRefreshTime(const int64_t formId, const long nextGapTime, const int32_t userId = 0); + /** + * @brief Get refresh count. + * @param formId The Id of the form. + * @return Returns refresh count. + */ + int GetRefreshCount(const int64_t formId) const; + /** + * @brief Mark remind. + * @param formId The Id of the form. + * @return true or false. + */ + void MarkRemind(const int64_t formId); + + /** + * @brief Handle system time changed. + * @return Returns true on success, false on failure. + */ + bool HandleSystemTimeChanged(); + /** + * @brief Reset form limiter. + * @return Returns true on success, false on failure. + */ + bool HandleResetLimiter(); + /** + * @brief Update attime trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ + bool OnUpdateAtTrigger(long updateTime); + /** + * @brief Dynamic time trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ + bool OnDynamicTimeTrigger(long updateTime); + /** + * @brief Get interval timer task. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool GetIntervalTimer(const int64_t formId, FormTimer &formTimer); + /** + * @brief Get update at timer. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool GetUpdateAtTimer(const int64_t formId, UpdateAtItem &updateAtItem); + /** + * @brief Get dynamic refresh item. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool GetDynamicItem(const int64_t formId, DynamicRefreshItem &dynamicItem); +private: + /** + * @brief Add update at timer. + * @param task Update time task. + * @return Returns true on success, false on failure. + */ + bool AddUpdateAtTimer(const FormTimer &task); + /** + * @brief Add update at timer item. + * @param task Update at timer item. + */ + void AddUpdateAtItem(const UpdateAtItem &atItem); + /** + * @brief Add update interval timer task. + * @param task Update interval timer task. + * @return Returns true on success, false on failure. + */ + bool AddIntervalTimer(const FormTimer &task); + /** + * @brief interval timer task timeout. + */ + void OnIntervalTimeOut(); + /** + * @brief Get remind tasks. + * @param remindTasks Remind tasks. + * @return Returns true on success, false on failure. + */ + bool GetRemindTasks(std::vector &remindTasks); + /** + * @brief Set enableFlag for interval timer task. + * @param formId The Id of the form. + * @param flag Enable flag. + */ + void SetIntervalEnableFlag(int64_t formId, bool flag); + /** + * @brief Update Interval timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool UpdateIntervalValue(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Update update at timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool UpdateAtTimerValue(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Interval timer task to update at timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool IntervalToAtTimer(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Update at timer task to interval timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool AtTimerToIntervalTimer(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Delete interval timer task. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool DeleteIntervalTimer(const int64_t formId); + /** + * @brief Delete update at timer. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool DeleteUpdateAtTimer(const int64_t formId); + /** + * @brief Update at timer task alarm. + * @return Returns true on success, false on failure. + */ + bool UpdateAtTimerAlarm(); + /** + * @brief Update limiter task alarm. + * @return Returns true on success, false on failure. + */ + bool UpdateLimiterAlarm(); + /** + * @brief Clear limiter timer resource. + */ + void ClearLimiterTimerResource(); + /** + * @brief Delete dynamic refresh item. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool DeleteDynamicItem(const int64_t formId); + /** + * @brief Update dynamic refresh task alarm. + * @return Returns true on success, false on failure. + */ + bool UpdateDynamicAlarm(); + /** + * @brief Clear dynamic refresh resource. + */ + void ClearDynamicResource(); + /** + * @brief Fint next at timer item. + * @param nowTime Update time. + * @param updateAtItem Next at timer item. + * @return Returns true on success, false on failure. + */ + bool FindNextAtTimerItem(const int nowTime, UpdateAtItem &updateAtItem); + /** + * @brief Clear update at timer resource. + */ + void ClearUpdateAtTimerResource(); + + /** + * @brief Execute Form timer task. + * @param task Form timer task. + */ + void ExecTimerTask(const FormTimer &task); + + /** + * @brief Init. + */ + void Init(); + /** + * @brief Ensure init interval timer resource. + */ + void EnsureInitIntervalTimer(); + /** + * @brief Clear interval timer resource. + */ + void ClearIntervalTimer(); + /** + * @brief Creat thread pool for timer task. + */ + void CreatTaskThreadExecutor(); + /** + * @brief Set enable flag. + * @param formId The Id of the form. + * @param flag Enable flag. + */ + void SetEnableFlag(int64_t formId, bool flag); + /** + * @brief Get WantAgent. + * @param updateAtTime The next update time. + * @return Returns WantAgent. + */ + std::shared_ptr GetUpdateAtWantAgent(long updateAtTime); + /** + * @brief Get WantAgent. + * @return Returns WantAgent. + */ + std::shared_ptr GetLimiterWantAgent(); + /** + * @brief Get WantAgent. + * @param nextTime The next update time. + * @return Returns WantAgent. + */ + std::shared_ptr GetDynamicWantAgent(long nextTime); + + /** + * @brief check if user is active or not. + * @param userId User ID. + * @return true:active, false:inactive + */ + bool IsActiveUser(const int32_t userId); +private: + /** + * @class TimerReceiver + * timer event receiver. + */ + class TimerReceiver : public EventFwk::CommonEventSubscriber { + public: + TimerReceiver() = default; + TimerReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo); + virtual ~TimerReceiver() = default; + /** + * @brief Receive common event. + * @param eventData Common event data. + */ + virtual void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + }; + + struct { + bool operator()(DynamicRefreshItem a, DynamicRefreshItem b) const + { + return (a.settedTime > b.settedTime ? true : false); + } + } CompareDynamicRefreshItem; + + mutable std::mutex intervalMutex_; + mutable std::mutex updateAtMutex_; + mutable std::mutex dynamicMutex_; + mutable std::mutex refreshMutex_; + FormRefreshLimiter refreshLimiter_; + std::map intervalTimerTasks_; + std::list updateAtTimerTasks_; + std::vector dynamicRefreshTasks_; + std::shared_ptr timerReceiver_ = nullptr; + std::unique_ptr taskExecutor_ = nullptr; + + uint64_t intervalTimerId_ = 0L; + uint64_t updateAtTimerId_ = 0L; + uint64_t dynamicAlarmTimerId_ = 0L; + uint64_t limiterTimerId_= 0L; + + std::shared_ptr currentUpdateAtWantAgent = nullptr; + std::shared_ptr currentDynamicWantAgent = nullptr; + std::shared_ptr currentLimiterWantAgent = nullptr; + + long dynamicWakeUpTime_ = LONG_MAX; + long atTimerWakeUpTime_ = LONG_MAX; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_MGR_H \ No newline at end of file diff --git a/services/formmgr/include/form_timer_option.h b/services/formmgr/include/form_timer_option.h new file mode 100644 index 0000000000000000000000000000000000000000..661eb03253609a6a662c0628fc3f51cbe6486ccd --- /dev/null +++ b/services/formmgr/include/form_timer_option.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H + +#include "itimer_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormTimerOption + * form timer option. + */ +class FormTimerOption : public OHOS::MiscServices::ITimerInfo { +public: + FormTimerOption(); + virtual ~FormTimerOption(); + virtual void OnTrigger() override; + virtual void SetType(const int &type) override; + virtual void SetRepeat(bool repeat) override; + virtual void SetInterval(const uint64_t &interval) override; + virtual void SetWantAgent(std::shared_ptr wantAgent) override; + void SetCallbackInfo(std::function callBack); + +private: + std::function callBack; +}; + +FormTimerOption::FormTimerOption() +{ +} + +FormTimerOption::~FormTimerOption() +{ +} + +void FormTimerOption::OnTrigger() +{ + if (this->callBack) { + this->callBack(); + } +} + +void FormTimerOption::SetCallbackInfo(std::function callBack) +{ + this->callBack = callBack; +} + +void FormTimerOption::SetType(const int &type) +{ + this->type = type; +} + +void FormTimerOption::SetRepeat(bool repeat) +{ + this->repeat = repeat; +} + +void FormTimerOption::SetInterval(const uint64_t &interval) +{ + this->interval = interval; +} + +void FormTimerOption::SetWantAgent(std::shared_ptr wantAgent) +{ + this->wantAgent = wantAgent; +} +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H \ No newline at end of file diff --git a/services/formmgr/include/form_util.h b/services/formmgr/include/form_util.h new file mode 100644 index 0000000000000000000000000000000000000000..dbf93dccd4ab66464a11d503addfe1aa2e0302d1 --- /dev/null +++ b/services/formmgr/include/form_util.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormUtil + * form utils. + */ +class FormUtil { +public: + /** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ + static void CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, + Want &want); + /** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param userId user id. + */ + static void CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t userId); + + /** + * @brief create udid for form. + * @return udid. + */ + static std::string GenerateUdid(); + + /** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ + static int64_t GenerateFormId(int64_t udidHash); + + /** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash. + * @return new form id. + */ + static int64_t PaddingUDIDHash(uint64_t formId, uint64_t udidHash); + + /** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ + static bool GenerateUdidHash(int64_t &udidHash); + /** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ + static long GetCurrentNanosecond(); + /** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ + static long GetCurrentMillisecond(); + /** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ + static long GetMillisecondFromTm(struct tm &tmAtTime); + + /** + * @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ + static std::vector StringSplit(const std::string &in, const std::string &delim); + + /** + * @brief get current active account id. + * @return int current active account id. + */ + static int GetCurrentAccountId(); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H \ No newline at end of file diff --git a/services/formmgr/include/kvstore_death_recipient_callback.h b/services/formmgr/include/kvstore_death_recipient_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..99993006340d128a8dd21562ddcb028a06cab8ad --- /dev/null +++ b/services/formmgr/include/kvstore_death_recipient_callback.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_KVSTORE_DEATH_RECIPIENT_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_KVSTORE_DEATH_RECIPIENT_CALLBACK_H + +#include "kvstore_death_recipient.h" + +namespace OHOS { +namespace AppExecFwk { +class KvStoreDeathRecipientCallback : public DistributedKv::KvStoreDeathRecipient { +public: + KvStoreDeathRecipientCallback(); + virtual ~KvStoreDeathRecipientCallback(); + + virtual void OnRemoteDied() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_KVSTORE_DEATH_RECIPIENT_CALLBACK_H \ No newline at end of file diff --git a/services/formmgr/src/form_ability_connection.cpp b/services/formmgr/src/form_ability_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d797ea517ab6f6a187b833287959f18e2b323c07 --- /dev/null +++ b/services/formmgr/src/form_ability_connection.cpp @@ -0,0 +1,125 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ability_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAbilityConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, formId_, resultCode); + return; + } + + if (isFreeInstall_) { + // Handle free install for form provider app + APP_LOGI("%{public}s current is Free Install.", __func__); + } +} + +/** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + APP_LOGD("%{public}s, element:%{public}s, resultCode:%{public}d", __func__, element.GetURI().c_str(), resultCode); + if (connectId_ != 0) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId_); + connectId_ = 0; + } else { + APP_LOGE("%{public}s fail, connectId_ invalidate. connectId_: %{public}ld", __func__, connectId_); + } +} + +/** + * @brief Remote object died event. + * @param remoteObject the remote object of service ability. + */ +void FormAbilityConnection::OnConnectDied(const wptr &remoteObject) +{ + if (connectId_ != 0) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId_); + connectId_ = 0; + } else { + APP_LOGE("%{public}s fail, connectId_ invalidate. connectId_: %{public}ld", __func__, connectId_); + } +} + +/** + * @brief Set connectId. + * @param connectId The ability connection id. + */ +void FormAbilityConnection::SetConnectId(long connectId) +{ + APP_LOGI("%{public}s, connectId_: %{public}ld", __func__, connectId); + connectId_ = connectId; +} + +/** + * @brief Get connectId. + * @return The ability connection id. + */ +long FormAbilityConnection::GetConnectId() +{ + return connectId_; +} + +/** + * @brief Get the provider Key + * + * @return The provider Key + */ +std::string FormAbilityConnection::GetProviderKey() +{ + if (bundleName_.empty() || abilityName_.empty()) { + return ""; + } + return bundleName_ + "::" + abilityName_; +} + +/** + * @brief Set the Provider Key + * + * @param bundleName bundleName + * @param abilityName abilityName + */ +void FormAbilityConnection::SetProviderKey(const std::string &bundleName, const std::string &abilityName) +{ + bundleName_ = bundleName; + abilityName_ = abilityName; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_acquire_connection.cpp b/services/formmgr/src/form_acquire_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1545bdbfa4f39790b704487dc66f472d5a12fc3 --- /dev/null +++ b/services/formmgr/src/form_acquire_connection.cpp @@ -0,0 +1,71 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_acquire_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormAcquireConnection::FormAcquireConnection( + const int64_t formId, + const FormItemInfo &info, + const WantParams &wantParams) + :formId_(formId), + info_(info), + wantParams_(wantParams) +{ + SetProviderKey(info.GetProviderBundleName(), info.GetAbilityName()); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAcquireConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + Want want; + want.SetParams(wantParams_); + FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); + if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + } else { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + } + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_ams_helper.cpp b/services/formmgr/src/form_ams_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..079fadac8689f06d68ed0c397841e095e5118149 --- /dev/null +++ b/services/formmgr/src/form_ams_helper.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ams_helper.h" +#include "ability_manager_interface.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +const int FORM_DISCONNECT_DELAY_TIME = 5000; // ms +FormAmsHelper::FormAmsHelper(){} +FormAmsHelper::~FormAmsHelper(){} + +/** + * @brief acquire a form ability manager, if it not existed, + * @return returns the ability manager ipc object, or nullptr for failed. + */ +sptr FormAmsHelper::GetAbilityManager() +{ + if (abilityManager_ == nullptr) { + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + APP_LOGE("%{public}s:fail to get registry", __func__); + return nullptr; + } + sptr remoteObject = systemManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + APP_LOGE("%{public}s:fail to connect AbilityMgrService", __func__); + return nullptr; + } + APP_LOGD("connect AbilityMgrService success"); + + abilityManager_ = iface_cast(remoteObject); + } + + return abilityManager_; +} + +/** + * @brief ConnectAbility, connect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormAmsHelper::ConnectServiceAbility( + const Want &want, const sptr &connect) +{ + APP_LOGI("%{public}s called.", __func__); + sptr ams = GetAbilityManager(); + if (ams == nullptr) { + APP_LOGE("%{public}s:ability service not connect", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ams->ConnectAbility(want, connect, nullptr); +} +/** + * @brief Disconnect ability, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormAmsHelper::DisConnectServiceAbility(const sptr &connect) +{ + APP_LOGI("%{public}s called.", __func__); + sptr ams = GetAbilityManager(); + if (ams == nullptr) { + APP_LOGE("%{public}s:ability service not connect", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ams->DisconnectAbility(connect); +} +/** + * @brief Disconnect ability delay, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormAmsHelper::DisConnectServiceAbilityDelay(const sptr &connect) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return ERR_INVALID_OPERATION; + } + std::function disConnectAbilityFunc = std::bind( + &FormAmsHelper::DisConnectAbilityTask, + this, + connect); + if (!eventHandler_->PostTask(disConnectAbilityFunc, FORM_DISCONNECT_DELAY_TIME)) { + APP_LOGE("%{public}s, failed to disconnect ability", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} +/** + * @brief Add the ability manager instance for debug. + * @param abilityManager the ability manager ipc object. + */ +void FormAmsHelper::SetAbilityManager(const sptr &abilityManager) +{ + abilityManager_ = abilityManager; +} + +/** + * @brief Disconnect ability task, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + */ +void FormAmsHelper::DisConnectAbilityTask(const sptr &connect) +{ + sptr ams = GetAbilityManager(); + if (ams == nullptr) { + APP_LOGE("%{public}s, ability service not connect", __func__); + return; + } + ams->DisconnectAbility(connect); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_batch_delete_connection.cpp b/services/formmgr/src/form_batch_delete_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5c090ba3fc4a569db347a36b80db1dde0f82005 --- /dev/null +++ b/services/formmgr/src/form_batch_delete_connection.cpp @@ -0,0 +1,57 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_batch_delete_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormBatchDeleteConnection::FormBatchDeleteConnection(const std::set &formIds, + const std::string &bundleName, const std::string &abilityName) + :formIds_(formIds) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormBatchDeleteConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostProviderBatchDeleteTask(formIds_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_bms_helper.cpp b/services/formmgr/src/form_bms_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0c3101b957b7e1bcc71b89d71cceb5f01c636e8 --- /dev/null +++ b/services/formmgr/src/form_bms_helper.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_bms_helper.h" +#include "ability_manager_interface.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +FormBmsHelper::FormBmsHelper() +{} + +FormBmsHelper::~FormBmsHelper() +{} + +/** + * @brief Acquire a bundle manager, if it not existed. + * @return returns the bundle manager ipc object, or nullptr for failed. + */ +sptr FormBmsHelper::GetBundleMgr() +{ + APP_LOGI("%{public}s called.", __func__); + + if (iBundleMgr_ == nullptr) { + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + APP_LOGE("%{public}s error, failed to get bundle manager service.", __func__); + return nullptr; + } + + iBundleMgr_ = iface_cast(remoteObject); + if (iBundleMgr_ == nullptr) { + APP_LOGE("%{public}s error, failed to get bundle manager service", __func__); + return nullptr; + } + } + return iBundleMgr_; +} + +/** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ +void FormBmsHelper::SetBundleManager(const sptr &bundleManager) +{ + APP_LOGI("%{public}s called.", __func__); + + iBundleMgr_ = bundleManager; +} +/** + * @brief Notify module removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ +void FormBmsHelper::NotifyModuleRemovable(const std::string &bundleName, const std::string &moduleName) +{ + APP_LOGI("%{public}s, bundleName:%{public}s, moduleName:%{public}s", + __func__, bundleName.c_str(), moduleName.c_str()); + if (bundleName.empty() || moduleName.empty()) { + return; + } + + std::string key = GenerateModuleKey(bundleName, moduleName); + APP_LOGI("%{public}s, begin to notify %{public}s removable", __func__, key.c_str()); + sptr iBundleMgr = GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s, failed to get IBundleMgr.", __func__); + return; + } + + std::string originId = IPCSkeleton::ResetCallingIdentity(); + + IPCSkeleton::SetCallingIdentity(originId); +} +/** + * @brief Notify module not removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ +void FormBmsHelper::NotifyModuleNotRemovable(const std::string &bundleName, const std::string &moduleName) const +{ + std::string key = GenerateModuleKey(bundleName, moduleName); + APP_LOGI("%{public}s, begin to notify %{public}s not removable", __func__, key.c_str()); +} + +std::string FormBmsHelper::GenerateModuleKey(const std::string &bundleName, const std::string &moduleName) const +{ + return bundleName + "#" + moduleName; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_cache_mgr.cpp b/services/formmgr/src/form_cache_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3921b34522e02ee8e015d835d0ea88e6e4420c00 --- /dev/null +++ b/services/formmgr/src/form_cache_mgr.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "form_cache_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +FormCacheMgr::FormCacheMgr() +{ + APP_LOGI("create form cache manager instance"); +} +FormCacheMgr::~FormCacheMgr() +{ + APP_LOGI("destroy form cache manager instance"); +} + +/** + * @brief Get form data. + * @param formId, Form id. + * @param data, Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::GetData(const int64_t formId, std::string &data) const +{ + APP_LOGI("get cache data"); + std::lock_guard lock(cacheMutex_); + if (cacheData_.empty()) { + APP_LOGE("form cache is empty"); + return false; + } + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGE("cache data not find"); + return false; + } + + data = formData->second; + + return true; +} + +/** + * @brief Add form data. + * @param formId, Form id. + * @param data, Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::AddData(const int64_t formId, const std::string &data) +{ + APP_LOGI("add new cache data"); + std::lock_guard lock(cacheMutex_); + std::pair::iterator, bool> retVal + = cacheData_.emplace(formId, data); + + return retVal.second; +} + +/** + * @brief Delete form data. + * @param formId, Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::DeleteData(const int64_t formId) +{ + APP_LOGI("delete cache data"); + std::lock_guard lock(cacheMutex_); + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGW("cache data is not exist"); + return true; + } + + return cacheData_.erase(formId); +} + +/** + * @brief Update form data. + * @param formId, Form id. + * @param data, Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::UpdateData(const int64_t formId, const std::string &data) +{ + APP_LOGI("update cache data"); + std::lock_guard lock(cacheMutex_); + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGE("cache data is not exist"); + return false; + } + + formData->second = data; + return true; +} +/** + * @brief Check if form data is exist or not. + * @param formId, Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::IsExist(const int64_t formId) const +{ + APP_LOGI("get cache data"); + std::lock_guard lock(cacheMutex_); + if (cacheData_.empty()) { + APP_LOGE("form cache is empty"); + return false; + } + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGE("cache data not find"); + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_cast_temp_connection.cpp b/services/formmgr/src/form_cast_temp_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..20e4db2c60078e716eaa971f67914f04d05c67fa --- /dev/null +++ b/services/formmgr/src/form_cast_temp_connection.cpp @@ -0,0 +1,58 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_cast_temp_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" + +namespace OHOS { +namespace AppExecFwk { +FormCastTempConnection::FormCastTempConnection(const int64_t formId, const std::string &bundleName, + const std::string &abilityName) + :formId_(formId) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormCastTempConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostCastTempTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_data_mgr.cpp b/services/formmgr/src/form_data_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2a9408b0d703abb14ff93339db96710909679fc --- /dev/null +++ b/services/formmgr/src/form_data_mgr.cpp @@ -0,0 +1,1211 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_cache_mgr.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_provider_mgr.h" +#include "form_util.h" +#include "ipc_skeleton.h" + + +namespace OHOS { +namespace AppExecFwk { +FormDataMgr::FormDataMgr() +{ + APP_LOGI("create form data manager instance"); + udidHash_ = 0L; +} +FormDataMgr::~FormDataMgr() +{ + APP_LOGI("destroy form data manager instance"); +} + +/** + * @brief Allot form info by item info. + * @param formInfo Form item info. + * @param callingUid The UID of the proxy. + * @param userId User ID. + * @return Returns form record. + */ +FormRecord FormDataMgr::AllotFormRecord(const FormItemInfo &formInfo, const int callingUid, const int32_t userId) +{ + APP_LOGI("%{public}s, allot form info", __func__); + if (formInfo.IsTemporaryForm() && !ExistTempForm(formInfo.GetFormId())) { + std::lock_guard lock(formTempMutex_); + tempForms_.emplace_back(formInfo.GetFormId()); + } + FormRecord record; + { + std::lock_guard lock(formRecordMutex_); + if (formRecords_.empty()) { // formRecords_ is empty, create a new one + APP_LOGD("%{public}s, form info not exist", __func__); + record = CreateFormRecord(formInfo, callingUid, userId); + formRecords_.emplace(formInfo.GetFormId(), record); + } else { + auto info = formRecords_.find(formInfo.GetFormId()); + if (info == formRecords_.end()) { + APP_LOGD("%{public}s, form info not find", __func__); + record = CreateFormRecord(formInfo, callingUid, userId); + formRecords_.emplace(formInfo.GetFormId(), record); + } else { + record = info->second; + } + } + } + APP_LOGI("%{public}s end", __func__); + return record; +} +/** + * @brief Delete form js info by form record. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteFormRecord(const int64_t formId) +{ + APP_LOGI("%{public}s, delete form info", __func__); + std::lock_guard lock(formRecordMutex_); + auto iter = formRecords_.find(formId); + if (iter == formRecords_.end()) { + APP_LOGE("%{public}s, form info is not exist", __func__); + return true; + } + formRecords_.erase(iter); + return true; +} +/** + * @brief Allot form host record by caller token. + * @param info The form item info. + * @param callerToken callerToken + * @param formId The Id of the form. + * @param callingUid The UID of the proxy. + * @param record Form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::AllotFormHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int64_t formId, const int callingUid) +{ + APP_LOGI("%{public}s, allot form Host info", __func__); + std::lock_guard lock(formHostRecordMutex_); + for (auto &record : clientRecords_) { + if (callerToken == record.GetClientStub()) { + record.AddForm(formId); + APP_LOGI("%{public}s end", __func__); + return true; + } + } + FormHostRecord hostRecord; + bool isCreated = CreateHostRecord(info, callerToken, callingUid, hostRecord); + if (isCreated) { + hostRecord.AddForm(formId); + clientRecords_.emplace_back(hostRecord); + APP_LOGI("%{public}s end", __func__); + return true; + } + APP_LOGI("%{public}s end", __func__); + return false; +} +/** + * @brief Create host record. + * @param info The form item info. + * @param callerToken The UID of the proxy. + * @param callingUid The UID of the proxy. + * @param record The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::CreateHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int callingUid, FormHostRecord& record) +{ + if (callerToken == nullptr) { + APP_LOGE("%{public}s, invalid param", __func__); + return false; + } + + record = FormHostRecord::CreateRecord(info, callerToken, callingUid); + return true; +} +/** + * @brief Create form record. + * @param formInfo The form item info. + * @param callingUid The UID of the proxy. + * @param userId User ID. + * @return Form record. + */ +FormRecord FormDataMgr::CreateFormRecord(const FormItemInfo &formInfo, const int callingUid, const int32_t userId) const +{ + APP_LOGI("%{public}s, create form info", __func__); + FormRecord newRecord; + newRecord.formId = formInfo.GetFormId(); + newRecord.userId = userId; + newRecord.packageName = formInfo.GetPackageName(); + newRecord.bundleName = formInfo.GetProviderBundleName(); + newRecord.moduleName = formInfo.GetModuleName(); + newRecord.abilityName = formInfo.GetAbilityName(); + newRecord.formName = formInfo.GetFormName(); + newRecord.specification = formInfo.GetSpecificationId(); + newRecord.isEnableUpdate = formInfo.IsEnableUpdateFlag(); + newRecord.formTempFlg = formInfo.IsTemporaryForm(); + newRecord.formVisibleNotify = formInfo.IsFormVisibleNotify(); + newRecord.jsFormCodePath = formInfo.GetHapSourceByModuleName(newRecord.moduleName); + newRecord.formSrc = formInfo.GetFormSrc(); + newRecord.formWindow = formInfo.GetFormWindow(); + newRecord.versionName = formInfo.GetVersionName(); + newRecord.versionCode = formInfo.GetVersionCode(); + newRecord.compatibleVersion = formInfo.GetCompatibleVersion(); + newRecord.icon = formInfo.GetIcon(); + + newRecord.formVisibleNotifyState = 0; + if (newRecord.isEnableUpdate) { + ParseUpdateConfig(newRecord, formInfo); + } + if (std::find(newRecord.formUserUids.begin(), newRecord.formUserUids.end(), + callingUid) == newRecord.formUserUids.end()) { + newRecord.formUserUids.emplace_back(callingUid); + } + + formInfo.GetHapSourceDirs(newRecord.hapSourceDirs); + APP_LOGI("%{public}s end", __func__); + return newRecord; +} +/** + * @brief Create form js info by form record. + * @param formId The Id of the form. + * @param record Form record. + * @param formInfo Js info. + * @return None. + */ +void FormDataMgr::CreateFormInfo(const int64_t formId, const FormRecord &record, FormJsInfo &formInfo) +{ + formInfo.formId = formId; + formInfo.bundleName = record.bundleName; + formInfo.abilityName = record.abilityName; + formInfo.formName = record.formName; + formInfo.formTempFlg = record.formTempFlg; + formInfo.formSrc = record.formSrc; + formInfo.formWindow = record.formWindow; + formInfo.versionCode = record.versionCode; + formInfo.versionName = record.versionName; + formInfo.compatibleVersion = record.compatibleVersion; + formInfo.icon = record.icon; +} +/** + * @brief Check temp form count is max. + * @return Returns ERR_OK if the temp form not reached; returns ERR_MAX_SYSTEM_TEMP_FORMS is reached. + */ +int FormDataMgr::CheckTempEnoughForm() const +{ + if (tempForms_.size() >= Constants::MAX_TEMP_FORMS) { + APP_LOGW("%{public}s, already exist %{public}d temp forms in system", __func__, Constants::MAX_TEMP_FORMS); + return ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS; + } + return ERR_OK; +} +/** + * @brief Check form count is max. + * @param callingUid The UID of the proxy. + * @param currentUserId The current userId. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +int FormDataMgr::CheckEnoughForm(const int callingUid, const int32_t currentUserId) const +{ + APP_LOGI("%{public}s, callingUid: %{public}d, current userId: %{public}d", __func__, callingUid, currentUserId); + + int formsInSystem = 0; + int callingUidFormCounts = 0; + for (auto &recordPair : formRecords_) { + FormRecord record = recordPair.second; + if ((record.userId == currentUserId) && !record.formTempFlg) { + if (++formsInSystem >= Constants::MAX_FORMS) { + APP_LOGW("%{public}s, already exist %{public}d forms in system", __func__, Constants::MAX_FORMS); + return ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS; + } + for (auto &userUid : record.formUserUids) { + if (userUid == callingUid) { + if (++callingUidFormCounts >= Constants::MAX_RECORD_PER_APP) { + APP_LOGW("%{public}s, already use %{public}d forms", __func__, Constants::MAX_RECORD_PER_APP); + return ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT; + } + break; + } + } + } + } + return ERR_OK; +} +/** + * @brief Delete temp form. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteTempForm(const int64_t formId) +{ + std::lock_guard lock(formTempMutex_); + auto iter = std::find(tempForms_.begin(), tempForms_.end(), formId); + if (iter == tempForms_.end()) { + APP_LOGE("%{public}s, temp form is not exist", __func__); + return false; + } + tempForms_.erase(iter); + return true; +} +/** + * @brief Check temp form is exist. + * @param formId The Id of the form. + * @return Returns true if the temp form is exist; returns false is not exist. + */ +bool FormDataMgr::ExistTempForm(const int64_t formId) const +{ + return (std::find(tempForms_.begin(), tempForms_.end(), formId) != tempForms_.end()); +} +/** + * @brief Check calling uid is valid. + * @param formUserUids The form user uids. + * @return Returns true if this user uid is valid; returns false otherwise. + */ +bool FormDataMgr::IsCallingUidValid(const std::vector &formUserUids) const +{ + if (formUserUids.size() != 0) { + for (auto &userUid : formUserUids) { + if (userUid == IPCSkeleton::GetCallingUid()) { + return true; + } + } + } + return false; +} +/** + * @brief Modify form temp flag by formId. + * @param formId The Id of the form. + * @param formTempFlg The form temp flag. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::ModifyFormTempFlg(const int64_t formId, const bool formTempFlg) +{ + APP_LOGI("%{public}s, modify form temp flag by formId", __func__); + std::lock_guard lock(formRecordMutex_); + if (!ExistFormRecord(formId)) { + APP_LOGE("%{public}s, form info is not exist", __func__); + return false; + } + formRecords_[formId].formTempFlg = formTempFlg; + return true; +} +/** + * @brief Add form user uid from form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::AddFormUserUid(const int64_t formId, const int formUserUid) +{ + APP_LOGI("%{public}s, add form user uid by formId", __func__); + std::lock_guard lock(formRecordMutex_); + if (!ExistFormRecord(formId)) { + APP_LOGE("%{public}s, form info is not exist", __func__); + return false; + } + if (std::find(formRecords_[formId].formUserUids.begin(), formRecords_[formId].formUserUids.end(), + formUserUid) == formRecords_[formId].formUserUids.end()) { + formRecords_[formId].formUserUids.emplace_back(formUserUid); + } + return true; +} +/** + * @brief Delete form user uid from form record. + * @param formId The Id of the form. + * @param uid calling user id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteFormUserUid(const int64_t formId, const int uid) +{ + APP_LOGI("%{public}s, delete form user uid from form record", __func__); + std::lock_guard lock(formRecordMutex_); + if (ExistFormRecord(formId)) { + auto iter = std::find(formRecords_.at(formId).formUserUids.begin(), + formRecords_.at(formId).formUserUids.end(), uid); + if (iter != formRecords_.at(formId).formUserUids.end()) { + formRecords_.at(formId).formUserUids.erase(iter); + } + return true; + } else { + APP_LOGE("%{public}s, form info not find", __func__); + return false; + } +} +/** + * @brief Update form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::UpdateFormRecord(const int64_t formId, const FormRecord &formRecord) +{ + APP_LOGI("%{public}s, get form record by formId", __func__); + std::lock_guard lock(formRecordMutex_); + auto info = formRecords_.find(formId); + if (info != formRecords_.end()) { + formRecords_[formId] = formRecord; + return true; + } + return false; +} +/** + * @brief Get form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GetFormRecord(const int64_t formId, FormRecord &formRecord) const +{ + APP_LOGI("%{public}s, get form record by formId", __func__); + std::lock_guard lock(formRecordMutex_); + auto info = formRecords_.find(formId); + if (info == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return false; + } + formRecord = info->second; + + APP_LOGI("%{public}s, get form record successfully", __func__); + return true; +} +/** + * @brief Get form record. + * @param bundleName Bundle name. + * @param formInfos The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GetFormRecord(const std::string &bundleName, std::vector &formInfos) +{ + APP_LOGI("%{public}s, get form record by bundleName", __func__); + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + if (bundleName == itFormRecord->second.bundleName) { + formInfos.emplace_back(itFormRecord->second); + } + } + if (formInfos.size() > 0) { + return true; + } else { + APP_LOGI("%{public}s, form info not find", __func__); + return false; + } +} +/** + * @brief Check form record is exist. + * @param formId The Id of the form. + * @return Returns true if the form record is exist; returns false is not exist. + */ +bool FormDataMgr::ExistFormRecord(const int64_t formId) const +{ + APP_LOGI("%{public}s, check form record is exist", __func__); + return (formRecords_.count(formId) > 0); +} +/** + * @brief Has form user uids in form record. + * @param formId The Id of the form. + * @return Returns true if this form has form user uids; returns false is not has. + */ +bool FormDataMgr::HasFormUserUids(const int64_t formId) const +{ + APP_LOGI("%{public}s, check form has user uids", __func__); + FormRecord record; + if (GetFormRecord(formId, record)) { + return record.formUserUids.empty() ? false : true; + } + return false; +} +/** + * @brief Get form host record. + * @param formId The id of the form. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GetFormHostRecord(const int64_t formId, FormHostRecord &formHostRecord) const +{ + APP_LOGI("%{public}s, get form host record by formId", __func__); + std::lock_guard lock(formHostRecordMutex_); + for (auto &record : clientRecords_) { + if (record.Contains(formId)) { + formHostRecord = record; + return true; + } + } + + APP_LOGE("%{public}s, form host record not find", __func__); + return false; +} +/** + * @brief Delete form host record. + * @param callerToken The client stub of the form host record. + * @param formId The id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteHostRecord(const sptr &callerToken, const int64_t formId) +{ + APP_LOGI("%{public}s start, delete form host record", __func__); + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator iter; + for (iter = clientRecords_.begin(); iter != clientRecords_.end(); ++iter) { + if (callerToken == iter->GetClientStub()) { + iter->DelForm(formId); + if (iter->IsEmpty()) { + iter->CleanResource(); + iter = clientRecords_.erase(iter); + } + break; + } + } + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Clean removed forms form host. + * @param removedFormIds The id list of the forms. + */ +void FormDataMgr::CleanHostRemovedForms(const std::vector &removedFormIds) +{ + APP_LOGI("%{public}s start, delete form host record by formId list", __func__); + std::vector matchedIds; + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + for (const int64_t& formId : removedFormIds) { + if (itHostRecord->Contains(formId)) { + matchedIds.emplace_back(formId); + itHostRecord->DelForm(formId); + } + } + if (!matchedIds.empty()) { + APP_LOGI("%{public}s, OnFormUninstalled called", __func__); + itHostRecord->OnFormUninstalled(matchedIds); + } + } + + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ +void FormDataMgr::HandleHostDied(const sptr &remoteHost) +{ + std::vector recordTempForms; + { + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { + if (remoteHost == itHostRecord->GetClientStub()) { + HandleHostDiedForTempForms(*itHostRecord, recordTempForms); + APP_LOGI("find died client, remove it"); + itHostRecord->CleanResource(); + itHostRecord = clientRecords_.erase(itHostRecord); + break; + } else { + itHostRecord++; + } + } + } + { + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + int64_t formId = itFormRecord->first; + // if temp form, remove it + if (std::find(recordTempForms.begin(), recordTempForms.end(), formId) != recordTempForms.end()) { + FormRecord formRecord = itFormRecord->second; + itFormRecord = formRecords_.erase(itFormRecord); + FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, formRecord); + } else { + itFormRecord++; + } + } + } +} + +/** + * @brief Get the temp forms from host and delete temp form in cache. + * @param record The form record. + * @param recordTempForms Getted the temp forms. + */ +void FormDataMgr::HandleHostDiedForTempForms(const FormHostRecord &record, std::vector &recordTempForms) +{ + std::lock_guard lock(formTempMutex_); + std::vector::iterator itForm; + for (itForm = tempForms_.begin(); itForm != tempForms_.end();) { + if (record.Contains(*itForm)) { + recordTempForms.emplace_back(*itForm); + itForm = tempForms_.erase(itForm); + } else { + itForm++; + } + } +} + +/** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable. + */ +bool FormDataMgr::IsEnableRefresh(int64_t formId) +{ + std::lock_guard lock(formHostRecordMutex_); + for (auto &record : clientRecords_) { + if (record.IsEnableRefresh(formId)) { + return true; + } + } + + return false; +} +/** + * @brief Generate form id. + * @return form id. + */ +int64_t FormDataMgr::GenerateFormId() +{ + // generate udidHash_ + if (udidHash_ < 0) { + APP_LOGE("%{public}s fail, generateFormId no invalid udidHash_", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + return FormUtil::GenerateFormId(udidHash_); +} +/** + * @brief Generate udid. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GenerateUdidHash() +{ + if (udidHash_ != Constants::INVALID_UDID_HASH) { + return true; + } + + bool bGenUdid = FormUtil::GenerateUdidHash(udidHash_); + if (!bGenUdid) { + APP_LOGE("%{public}s, Failed to generate udid.", __func__); + return false; + } + + return true; +} +/** + * @brief Get udid. + * @return udid. + */ +int64_t FormDataMgr::GetUdidHash() const +{ + return udidHash_; +} +/** + * @brief Set udid. + * @param udidHash udid. + */ +void FormDataMgr::SetUdidHash(const int64_t udidHash) +{ + udidHash_ = udidHash; +} + +/** + * @brief Get the matched form host record by client stub. + * + * @param callerToken The client stub of the form host record. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called, returns false otherwise. + */ +bool FormDataMgr::GetMatchedHostClient(const sptr &callerToken, FormHostRecord &formHostRecord) const +{ + APP_LOGI("%{public}s, get the matched form host record by client stub.", __func__); + std::lock_guard lock(formHostRecordMutex_); + for (const FormHostRecord &record : clientRecords_) { + if (callerToken == record.GetClientStub()) { + formHostRecord = record; + return true; + } + } + + APP_LOGE("%{public}s, form host record not find.", __func__); + return false; +} + +/** + * @brief Set needRefresh for FormRecord. + * @param formId The Id of the form. + * @param needRefresh true or false. + */ +void FormDataMgr::SetNeedRefresh(const int64_t formId, const bool needRefresh) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.needRefresh = needRefresh; +} + +/** + * @brief Set isCountTimerRefresh for FormRecord. + * @param formId The Id of the form. + * @param countTimerRefresh true or false. + */ +void FormDataMgr::SetCountTimerRefresh(const int64_t formId, const bool countTimerRefresh) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.isCountTimerRefresh = countTimerRefresh; +} + +/** + * @brief Get updated form. + * @param record FormRecord. + * @param targetForms Target forms. + * @param updatedForm Updated formnfo. + * @return Returns true on success, false on failure. + */ +bool FormDataMgr::GetUpdatedForm( + const FormRecord &record, + const std::vector &targetForms, + FormInfo &updatedForm) +{ + if (targetForms.empty()) { + APP_LOGE("%{public}s error, targetForms is empty.", __func__); + return false; + } + + for (const FormInfo &item : targetForms) { + if (IsSameForm(record, item)) { + updatedForm = item; + APP_LOGD("%{public}s, find matched form.", __func__); + return true; + } + } + return false; +} +/** + * @brief Set isEnableUpdate for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + */ +void FormDataMgr::SetEnableUpdate(const int64_t formId, const bool enableUpdate) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.isEnableUpdate = enableUpdate; +} +/** + * @brief Set update info for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + * @param updateDuration Update duration. + * @param updateAtHour Update at hour. + * @param updateAtMin Update at minute. + */ +void FormDataMgr::SetUpdateInfo( + const int64_t formId, + const bool enableUpdate, + const long updateDuration, + const int updateAtHour, + const int updateAtMin) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + + itFormRecord->second.isEnableUpdate = enableUpdate; + itFormRecord->second.updateDuration = updateDuration; + itFormRecord->second.updateAtHour = updateAtHour; + itFormRecord->second.updateAtMin = updateAtMin; +} +/** + * @brief Check if two forms is same or not. + * @param record FormRecord. + * @param formInfo FormInfo. + * @return Returns true on success, false on failure. + */ +bool FormDataMgr::IsSameForm(const FormRecord &record, const FormInfo &formInfo) +{ + if (record.bundleName == formInfo.bundleName + && record.moduleName == formInfo.moduleName + && record.abilityName == formInfo.abilityName + && record.formName == formInfo.name + && std::find(formInfo.supportDimensions.begin(), formInfo.supportDimensions.end(), record.specification) + != formInfo.supportDimensions.end()) { + return true; + } + + return false; +} +/** + * @brief Clean removed form records. + * @param removedForms The id list of the forms. + */ +void FormDataMgr::CleanRemovedFormRecords(const std::string &bundleName, std::set &removedForms) +{ + APP_LOGI("%{public}s, clean removed form records", __func__); + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + auto itForm = std::find(removedForms.begin(), removedForms.end(), itFormRecord->first); + if (itForm != removedForms.end()) { + itFormRecord = formRecords_.erase(itFormRecord); + } else { + itFormRecord++; + } + } +} +/** + * @brief Clean removed temp form records. + * @param bundleName BundleName. + * @param removedForms The id list of the forms. + */ +void FormDataMgr::CleanRemovedTempFormRecords(const std::string &bundleName, std::set &removedForms) +{ + APP_LOGI("%{public}s, clean removed form records", __func__); + std::set removedTempForms; + { + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + if (itFormRecord->second.formTempFlg && bundleName == itFormRecord->second.bundleName) { + removedTempForms.emplace(itFormRecord->second.formId); + itFormRecord = formRecords_.erase(itFormRecord); + } else { + itFormRecord++; + } + } + } + + if (removedTempForms.size() > 0) { + std::lock_guard lock(formTempMutex_); + std::vector::iterator itTemp; + for (itTemp = tempForms_.begin();itTemp != tempForms_.end();) { + if (removedTempForms.find(*itTemp) != removedTempForms.end()) { + itTemp = tempForms_.erase(itTemp); + } else { + itTemp++; + } + } + removedForms.merge(removedTempForms); + } +} +/** + * @brief Get recreate form records. + * @param reCreateForms The id list of the forms. + */ +void FormDataMgr::GetReCreateFormRecordsByBundleName(const std::string &bundleName, std::set &reCreateForms) +{ + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + if (bundleName == itFormRecord->second.bundleName) { + reCreateForms.emplace(itFormRecord->second.formId); + } + } +} +/** + * @brief Set form isInited = true. + * @param formId The Id of the form. + * @param isInited isInited property + */ +void FormDataMgr::SetFormCacheInited(const int64_t formId, bool isInited) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.isInited = isInited; + itFormRecord->second.needRefresh = !isInited; +} +/** + * @brief Set versionUpgrade. + * @param formId The Id of the form. + * @param versionUpgrade true or false + */ +void FormDataMgr::SetVersionUpgrade(const int64_t formId, const bool versionUpgrade) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.versionUpgrade = versionUpgrade; +} +/** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param needRefresh true or false + */ +void FormDataMgr::UpdateHostNeedRefresh(const int64_t formId, const bool needRefresh) +{ + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + if (itHostRecord->Contains(formId)) { + itHostRecord->SetNeedRefresh(formId, needRefresh); + } + } +} + +/** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formProviderInfo FormProviderInfo object + */ +void FormDataMgr::UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.formProviderInfo = formProviderInfo; +} +/** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formRecord The form info. + * @return Returns true if form update, false if other. + */ +bool FormDataMgr::UpdateHostForm(const int64_t formId, const FormRecord &formRecord) +{ + bool isUpdated = false; + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + bool enableRefresh = itHostRecord->IsEnableRefresh(formId); + APP_LOGI("formId:%{public}" PRId64 " enableRefresh:%{public}d", formId, enableRefresh); + if (enableRefresh) { + // update form + itHostRecord->OnUpdate(formId, formRecord); + // set needRefresh + itHostRecord->SetNeedRefresh(formId, false); + isUpdated = true; + } + } + return isUpdated; +} +/** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @param refreshForms Refresh forms + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormDataMgr::UpdateHostFormFlag( + std::vector formIds, + const sptr &callerToken, + const bool flag, + std::vector &refreshForms) +{ + APP_LOGI("%{public}s start, flag: %{public}d", __func__, flag); + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + if (callerToken == itHostRecord->GetClientStub()) { + for (const int64_t formId : formIds) { + if (formId <= 0) { + APP_LOGW("%{public}s, formId %{public}" PRId64 " is less than 0", __func__, formId); + continue; + } + + int64_t matchedFormId = FindMatchedFormId(formId); + if (!itHostRecord->Contains(matchedFormId)) { + APP_LOGW("%{public}s, form %{public}d is not owned by this client, don't need to update flag", + __func__, (int32_t)formId); + continue; + } + + itHostRecord->SetEnableRefresh(matchedFormId, flag); + // set disable + if (!flag) { + APP_LOGI("%{public}s, flag is disable", __func__); + continue; + } + FormRecord formRecord; + if (GetFormRecord(matchedFormId, formRecord)) { + if (formRecord.needRefresh) { + APP_LOGI("%{public}s, formRecord need refresh", __func__); + refreshForms.emplace_back(matchedFormId); + continue; + } + } else { + APP_LOGW("%{public}s, not exist such form:%{public}" PRId64 "", __func__, matchedFormId); + continue; + } + + // if set enable flag, should check whether to refresh form + if (!itHostRecord->IsNeedRefresh(matchedFormId)) { + APP_LOGI("%{public}s, host need not refresh", __func__); + continue; + } + + if (IsFormCached(formRecord)) { + APP_LOGI("%{public}s, form cached", __func__); + itHostRecord->OnUpdate(matchedFormId, formRecord); + itHostRecord->SetNeedRefresh(matchedFormId, false); + } else { + APP_LOGI("%{public}s, form no cache", __func__); + refreshForms.emplace_back(matchedFormId); + continue; + } + } + APP_LOGI("%{public}s end.", __func__); + return ERR_OK; + } + } + APP_LOGE("%{public}s, can't find target client", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; +} +/** + * @brief Find matched form id. + * @param formId The form id. + * @return Matched form id. + */ +int64_t FormDataMgr::FindMatchedFormId(const int64_t formId) +{ + uint64_t unsignedFormId = static_cast(formId); + if ((unsignedFormId & 0xffffffff00000000L) != 0) { + return formId; + } + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + uint64_t unsignedFormId = static_cast(formId); + uint64_t unsignedItFormRecordFirst = static_cast(itFormRecord->first); + if ((unsignedItFormRecordFirst & 0x00000000ffffffffL) == (unsignedFormId & 0x00000000ffffffffL)) { + return itFormRecord->first; + } + } + return formId; +} + +/** + * @brief Clear host data by uId. + * @param uId The caller uId. + */ +void FormDataMgr::ClearHostDataByUId(const int uId) +{ + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { + if (itHostRecord->GetCallerUid() == uId) { + itHostRecord->CleanResource(); + itHostRecord = clientRecords_.erase(itHostRecord); + } else { + itHostRecord++; + } + } +} +/** + * @brief Get no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ +void FormDataMgr::GetNoHostTempForms( + const int uid, std::map> &noHostTempFormsMap, + std::map &foundFormsMap) +{ + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + if (itFormRecord->second.formTempFlg) { + auto itUid = std::find(itFormRecord->second.formUserUids.begin(), + itFormRecord->second.formUserUids.end(), uid); + if (itUid != itFormRecord->second.formUserUids.end()) { + itFormRecord->second.formUserUids.erase(itUid); + if (itFormRecord->second.formUserUids.empty()) { + FormIdKey formIdKey; + formIdKey.bundleName = itFormRecord->second.bundleName; + formIdKey.abilityName = itFormRecord->second.abilityName; + formIdKey.moduleName = ""; + formIdKey.formName = ""; + formIdKey.specificationId = 0; + formIdKey.orientation = 0; + auto itIdsSet = noHostTempFormsMap.find(formIdKey); + if (itIdsSet == noHostTempFormsMap.end()) { + std::set formIdsSet; + formIdsSet.emplace(itFormRecord->second.formId); + noHostTempFormsMap.emplace(formIdKey, formIdsSet); + } else { + itIdsSet->second.emplace(itFormRecord->second.formId); + } + } + } else { + foundFormsMap.emplace(itFormRecord->second.formId, false); + } + } + } +} +/** + * @brief Parse update config. + * @param record The form record. + * @param info The form item info. + */ +void FormDataMgr::ParseUpdateConfig(FormRecord &record, const FormItemInfo &info) const +{ + int configDuration = info.GetUpdateDuration(); + if (configDuration > 0) { + ParseIntervalConfig(record, configDuration); + } else { + ParseAtTimerConfig(record, info); + } +} + +/** + * @brief Parse update interval config. + * @param record The form record. + * @param configDuration interval duration. + */ +void FormDataMgr::ParseIntervalConfig(FormRecord &record, const int configDuration) const +{ + APP_LOGI("%{public}s, configDuration:%{public}d", __func__, configDuration); + if (configDuration <= Constants::MIN_CONFIG_DURATION) { + record.updateDuration = Constants::MIN_PERIOD; + } else if (configDuration >= Constants::MAX_CONFIG_DURATION) { + record.updateDuration = Constants::MAX_PERIOD; + } else { + record.updateDuration = configDuration * Constants::TIME_CONVERSION; + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Parse at time config. + * @param record The form record. + * @param info form item info. + */ +void FormDataMgr::ParseAtTimerConfig(FormRecord &record, const FormItemInfo &info) const +{ + record.isEnableUpdate = false; + record.updateDuration = 0; + std::string configAtTime = info.GetScheduledUpdateTime(); + APP_LOGI("%{public}s, parseAsUpdateAt updateAt:%{public}s", __func__, configAtTime.c_str()); + if (configAtTime.empty()) { + return; + } + + std::vector temp = FormUtil::StringSplit(configAtTime, Constants::TIME_DELIMETER); + if (temp.size() != Constants::UPDATE_AT_CONFIG_COUNT) { + APP_LOGE("%{public}s, invalid config", __func__); + return; + } + int hour = -1; + int min = -1; + hour = std::stoi(temp[0]); + min = std::stoi(temp[1]); + if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min > + Constants::MAX_MININUTE) { + APP_LOGE("%{public}s, time is invalid", __func__); + return; + } + record.updateAtHour = hour; + record.updateAtMin = min; + record.isEnableUpdate = true; +} +/** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ +bool FormDataMgr::IsFormCached(const FormRecord record) +{ + if (record.versionUpgrade) { + return false; + } + return FormCacheMgr::GetInstance().IsExist(record.formId); +} +/** + * @brief delete forms by userId. + * + * @param userId user ID. + * @param removedFormIds removed userId. + */ +void FormDataMgr::DeleteFormsByUserId(const int32_t userId, std::vector &removedFormIds) +{ + APP_LOGI("%{public}s, delete forms by userId", __func__); + + // handle formRecords_ + std::vector removedTempForms; + { + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + if (userId == itFormRecord->second.userId) { + if (itFormRecord->second.formTempFlg) { + removedTempForms.emplace_back(itFormRecord->second.formId); + } + removedFormIds.emplace_back(itFormRecord->second.formId); + itFormRecord = formRecords_.erase(itFormRecord); + } else { + itFormRecord++; + } + } + } + + // handle tempForms_ + if (removedTempForms.size() > 0) { + std::lock_guard lock(formTempMutex_); + std::vector::iterator itTemp; + for (itTemp = tempForms_.begin();itTemp != tempForms_.end();) { + if (std::find(removedTempForms.begin(), removedTempForms.end(), *itTemp) != removedTempForms.end()) { + itTemp = tempForms_.erase(itTemp); + } else { + itTemp++; + } + } + } +} +/** + * @brief Clear form records for st limit value test. + */ +void FormDataMgr::ClearFormRecords() +{ + { + std::lock_guard lock(formRecordMutex_); + formRecords_.clear(); + } + { + std::lock_guard lock(formTempMutex_); + tempForms_.clear(); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_db_cache.cpp b/services/formmgr/src/form_db_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0888c12ab6508cf6bbd67a1f72983fe3b1dec445 --- /dev/null +++ b/services/formmgr/src/form_db_cache.cpp @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "form_bms_helper.h" +#include "form_db_cache.h" +#include "form_db_info.h" + +namespace OHOS { +namespace AppExecFwk { +FormDbCache::FormDbCache() +{ + APP_LOGI("FormDbCache is created"); + dataStorage_ = std::make_shared(); + formDBInfos_.clear(); +} + +FormDbCache::~FormDbCache() +{ + APP_LOGI("FormDbCache is destroyed"); +} + +/** + * @brief Load form data from DB to DbCache when starting. + * @return Void. + */ +void FormDbCache::Start() +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock(formDBInfosMutex_); + std::vector innerFormInfos; + innerFormInfos.clear(); + if (dataStorage_->LoadFormData(innerFormInfos) != ERR_OK) { + APP_LOGE("%{public}s, LoadFormData failed.", __func__); + return; + } + + for (unsigned int i = 0; i < innerFormInfos.size(); i++) { + FormDBInfo formDBInfo = innerFormInfos.at(i).GetFormDBInfo(); + formDBInfos_.emplace_back(formDBInfo); + } +} + +/** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::SaveFormInfo(const FormDBInfo &formDBInfo) +{ + APP_LOGI("%{public}s called, formId:%{public}" PRId64 "", __func__, formDBInfo.formId); + std::lock_guard lock(formDBInfosMutex_); + auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), formDBInfo); + if (iter != formDBInfos_.end()) { + if (iter->Compare(formDBInfo) == false) { + APP_LOGW("%{public}s, need update, formId[%{public}" PRId64 "].", __func__, formDBInfo.formId); + *iter = formDBInfo; + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->ModifyStorageFormInfo(innerFormInfo); + } else { + APP_LOGW("%{public}s, already exist, formId[%{public}" PRId64 "].", __func__, formDBInfo.formId); + return ERR_OK; + } + } else { + formDBInfos_.emplace_back(formDBInfo); + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->SaveStorageFormInfo(innerFormInfo); + } +} + +/** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure.(NoLock) + */ +ErrCode FormDbCache::SaveFormInfoNolock(const FormDBInfo &formDBInfo) +{ + APP_LOGI("%{public}s called, formId:%{public}" PRId64 "", __func__, formDBInfo.formId); + auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), formDBInfo); + if (iter != formDBInfos_.end()) { + if (iter->Compare(formDBInfo) == false) { + APP_LOGW("%{public}s, need update, formId[%{public}" PRId64 "].", __func__, formDBInfo.formId); + *iter = formDBInfo; + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->ModifyStorageFormInfo(innerFormInfo); + } else { + APP_LOGW("%{public}s, already exist, formId[%{public}" PRId64 "].", __func__, formDBInfo.formId); + return ERR_OK; + } + } else { + formDBInfos_.emplace_back(formDBInfo); + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->SaveStorageFormInfo(innerFormInfo); + } +} + +/** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::DeleteFormInfo(int64_t formId) +{ + std::lock_guard lock(formDBInfosMutex_); + FormDBInfo tmpForm; + tmpForm.formId = formId; + auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), tmpForm); + if (iter == formDBInfos_.end()) { + APP_LOGW("%{public}s, not find formId[%{public}" PRId64 "]", __func__, formId); + } else { + formDBInfos_.erase(iter); + } + if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { + return ERR_OK; + } else { + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } +} +/** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @param removedDBForms Removed db form infos + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::DeleteFormInfoByBundleName(const std::string &bundleName, std::vector &removedDBForms) +{ + std::lock_guard lock(formDBInfosMutex_); + std::vector::iterator itRecord; + for (itRecord = formDBInfos_.begin(); itRecord != formDBInfos_.end(); ) { + if (bundleName == itRecord->bundleName) { + int64_t formId = itRecord->formId; + if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { + removedDBForms.emplace_back(*itRecord); + itRecord = formDBInfos_.erase(itRecord); + } else { + itRecord++; + } + } else { + itRecord++; + } + } + return ERR_OK; +} + +/** + * @brief Get all form data from DbCache. + * @param formDBInfos Storage all DbCache. + * @return Void. + */ +void FormDbCache::GetAllFormInfo(std::vector &formDBInfos) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock(formDBInfosMutex_); + formDBInfos = formDBInfos_; +} + +/** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormRecord &record) const +{ + std::lock_guard lock(formDBInfosMutex_); + for (const FormDBInfo &dbInfo : formDBInfos_) { + if (dbInfo.formId == formId) { + record.userId = dbInfo.userId; + record.formName = dbInfo.formName; + record.bundleName = dbInfo.bundleName; + record.moduleName = dbInfo.moduleName; + record.abilityName = dbInfo.abilityName; + record.formUserUids = dbInfo.formUserUids; + return ERR_OK; + } + } + APP_LOGE("%{public}s, not find formId[%{public}" PRId64 "]", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; +} +/** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form db data + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormDBInfo &record) const +{ + std::lock_guard lock(formDBInfosMutex_); + for (const FormDBInfo &dbInfo : formDBInfos_) { + if (dbInfo.formId == formId) { + record = dbInfo; + return ERR_OK; + } + } + APP_LOGE("%{public}s, not find formId[%{public}" PRId64 "]", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; +} +/** + * @brief Use record save or update DB data and DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::UpdateDBRecord(const int64_t formId, const FormRecord &record) const +{ + FormDBInfo formDBInfo(formId, record); + return FormDbCache::GetInstance().SaveFormInfo(formDBInfo); +} +/** + * @brief Get no host db record. + * @param uid The caller uid. + * @param noHostFormDBList no host db record list. + * @param foundFormsMap Form Id list. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, std::map &foundFormsMap) +{ + std::lock_guard lock(formDBInfosMutex_); + for (FormDBInfo& dbInfo : formDBInfos_) { + if (dbInfo.Contains(uid)) { + dbInfo.Remove(uid); + if (dbInfo.formUserUids.empty()) { + FormIdKey formIdKey; + formIdKey.bundleName = dbInfo.bundleName; + formIdKey.abilityName = dbInfo.abilityName; + formIdKey.moduleName = ""; + formIdKey.formName = ""; + formIdKey.specificationId = 0; + formIdKey.orientation = 0; + auto itIdsSet = noHostFormDBList.find(formIdKey); + if (itIdsSet == noHostFormDBList.end()) { + std::set formIdsSet; + formIdsSet.emplace(dbInfo.formId); + noHostFormDBList.emplace(formIdKey, formIdsSet); + } else { + itIdsSet->second.emplace(dbInfo.formId); + } + } else { + foundFormsMap.emplace(dbInfo.formId, false); + SaveFormInfoNolock(dbInfo); + FormBmsHelper::GetInstance().NotifyModuleNotRemovable(dbInfo.bundleName, dbInfo.moduleName); + } + } + } + return ERR_OK; +} +/** + * @brief Get match count by bundleName and moduleName. + * @param bundleName BundleName. + * @param moduleName ModuleName. + * @return Returns match count. + */ +int FormDbCache::GetMatchCount(const std::string &bundleName, const std::string &moduleName) +{ + int32_t matchCount {0}; + std::vector formDBInfos; + std::lock_guard lock(formDBInfosMutex_); + for (FormDBInfo &dbInfo : formDBInfos_) { + if (dbInfo.bundleName == bundleName && dbInfo.moduleName == moduleName) { + ++matchCount; + } + } + return matchCount; +} +/** + * @brief delete forms bu userId. + * + * @param userId user ID. + */ +void FormDbCache::DeleteDBFormsByUserId(const int32_t userId) +{ + std::lock_guard lock(formDBInfosMutex_); + std::vector::iterator itRecord; + for (itRecord = formDBInfos_.begin(); itRecord != formDBInfos_.end();) { + if (userId == itRecord->userId) { + int64_t formId = itRecord->formId; + if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { + itRecord = formDBInfos_.erase(itRecord); + } else { + APP_LOGE("%{public}s, failed to delete form, formId[%{public}" PRId64 "]", __func__, formId); + itRecord++; + } + } else { + itRecord++; + } + } +} +std::shared_ptr FormDbCache::GetDataStorage() const +{ + return dataStorage_; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_db_info.cpp b/services/formmgr/src/form_db_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6467d3eb2d0ca3efa7275e57b02b8ebb0315ec9 --- /dev/null +++ b/services/formmgr/src/form_db_info.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_db_info.h" + +#include "json_util.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string INNER_FORM_INFO_FORM_ID = "formId"; +const std::string INNER_FORM_INFO_USER_ID = "userId"; +const std::string INNER_FORM_INFO_FORM_NAME = "formName"; +const std::string INNER_FORM_INFO_BUNDLE_NAME = "bundleName"; +const std::string INNER_FORM_INFO_MODULE_NAME = "moduleName"; +const std::string INNER_FORM_INFO_ABILITY_NAME = "abilityName"; +const std::string INNER_FORM_INFO_FORM_USER_UIDS = "formUserUids"; +} + +/** + * @brief Transform the InnerFormInfo object to json. + * @param jsonObject Indicates the obtained json object. + * @return + */ +void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject[INNER_FORM_INFO_FORM_ID] = formDBInfo_.formId; + jsonObject[INNER_FORM_INFO_USER_ID] = formDBInfo_.userId; + jsonObject[INNER_FORM_INFO_FORM_NAME] = formDBInfo_.formName; + jsonObject[INNER_FORM_INFO_BUNDLE_NAME] = formDBInfo_.bundleName; + jsonObject[INNER_FORM_INFO_MODULE_NAME] = formDBInfo_.moduleName; + jsonObject[INNER_FORM_INFO_ABILITY_NAME] = formDBInfo_.abilityName; + jsonObject[INNER_FORM_INFO_FORM_USER_UIDS] = formDBInfo_.formUserUids; +} + +/** + * @brief Transform the json object to InnerFormInfo object. + * @param jsonObject Indicates the obtained json object. + * @return + */ +bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) +{ + const auto &jsonObjectEnd = jsonObject.end(); + int32_t parseResult = ERR_OK; + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_FORM_ID, + formDBInfo_.formId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_USER_ID, + formDBInfo_.userId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_FORM_NAME, + formDBInfo_.formName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_BUNDLE_NAME, + formDBInfo_.bundleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_MODULE_NAME, + formDBInfo_.moduleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_ABILITY_NAME, + formDBInfo_.abilityName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_FORM_USER_UIDS, + formDBInfo_.formUserUids, + JsonType::ARRAY, + false, + parseResult, + ArrayType::NUMBER); + return parseResult == ERR_OK; +} + +void InnerFormInfo::AddUserUid(const int callingUid) +{ + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + formDBInfo_.formUserUids.push_back(callingUid); + } +} + +bool InnerFormInfo::DeleteUserUid(const int callingUid) +{ + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + return false; + } + formDBInfo_.formUserUids.erase(iter); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_delete_connection.cpp b/services/formmgr/src/form_delete_connection.cpp new file mode 100755 index 0000000000000000000000000000000000000000..c75e3090d84f1aac65dcd8e771dbcbc91cede1fe --- /dev/null +++ b/services/formmgr/src/form_delete_connection.cpp @@ -0,0 +1,60 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_delete_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormDeleteConnection::FormDeleteConnection(const int64_t formId, const std::string &bundleName, + const std::string &abilityName) + :formId_(formId) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormDeleteConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + APP_LOGD("%{public}s, connectId :%{public}ld", __func__, this->GetConnectId()); + FormTaskMgr::GetInstance().PostDeleteTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_dump_mgr.cpp b/services/formmgr/src/form_dump_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51a2ae50ec4ae8c02b965968f878d57564d272b1 --- /dev/null +++ b/services/formmgr/src/form_dump_mgr.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "form_cache_mgr.h" +#include "form_dump_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string LINE_SEPARATOR = "\n"; + +FormDumpMgr::FormDumpMgr(){} +FormDumpMgr::~FormDumpMgr(){} +/** + * @brief Dump all of form storage infos. + * @param storageInfos Form storage infos + * @param formInfos Form storage dump info. + */ +void FormDumpMgr::DumpStorageFormInfos(const std::vector &storageInfos, std::string &formInfos) const +{ + for (const auto &info : storageInfos) { + formInfos += " FormId #" + std::to_string(info.formId); + formInfos += " formName [" + info.formName + "]"; + formInfos += " userId [" + std::to_string(info.userId) + "]"; + formInfos += " bundleName [" + info.bundleName + "]"; + formInfos += " moduleName [" + info.moduleName + "]"; + formInfos += " abilityName [" + info.abilityName + "]"; + formInfos += " formUserUids ["; + for (auto &uId : info.formUserUids) { + formInfos += " Uid [" + std::to_string(uId) + "]"; + } + formInfos += "]" + LINE_SEPARATOR; + } +} +/** + * @brief Dump form infos. + * @param formRecordInfos Form record infos. + * @param formInfos Form dump infos. + */ +void FormDumpMgr::DumpFormInfos(const std::vector &formRecordInfos, std::string &formInfos) const +{ + APP_LOGI("%{public}s called.", __func__); + for (const auto &info : formRecordInfos) { + formInfos += " FormId [" + std::to_string(info.formId) + "]"; + formInfos += " formName [" + info.formName + "]"; + formInfos += " bundleName [" + info.bundleName + "]"; + formInfos += " moduleName [" + info.moduleName + "]"; + formInfos += " abilityName [" + info.abilityName + "]"; + formInfos += " isInited [" + std::to_string(info.isInited) + "]"; + formInfos += " needRefresh [" + std::to_string(info.needRefresh) + "]"; + formInfos += " isEnableUpdate [" + std::to_string(info.isEnableUpdate) + "]"; + formInfos += " isCountTimerRefresh [" + std::to_string(info.isCountTimerRefresh) + "]"; + formInfos += " specification [" + std::to_string(info.specification) + "]"; + formInfos += " updateDuration [" + std::to_string(info.updateDuration) + "]"; + formInfos += " updateAtHour [" + std::to_string(info.updateAtHour) + "]"; + formInfos += " updateAtMin [" + std::to_string(info.updateAtMin) + "]"; + formInfos += " formTempFlg [" + std::to_string(info.formTempFlg) + "]"; + formInfos += " formVisibleNotify [" + std::to_string(info.formVisibleNotify) + "]"; + formInfos += " formVisibleNotifyState [" + std::to_string(info.formVisibleNotifyState) + "]"; + formInfos += " userId [" + std::to_string(info.userId) + "]"; + + if (info.hapSourceDirs.size() > 0) { + formInfos += " hapSourceDirs ["; + for (auto &hapDir : info.hapSourceDirs) { + formInfos += " hapSourceDir [" + hapDir + "]"; + } + formInfos += "]"; + } + + if (info.formUserUids.size() > 0) { + formInfos += " formUserUids ["; + for (auto &uId : info.formUserUids) { + formInfos += " Uid [" + std::to_string(uId) + "]"; + } + formInfos += "]"; + } + + // formCacheData + std::string strCacheData; + if (FormCacheMgr::GetInstance().GetData(info.formId, strCacheData)) { + formInfos += " formCacheData ["; + formInfos += strCacheData; + formInfos += "]" + LINE_SEPARATOR; + } + } + + APP_LOGI("%{public}s success. Form infos:%{public}s", __func__, formInfos.c_str()); +} +/** + * @brief Dump form infos. + * @param formRecordInfo Form Host record info. + * @param formInfo Form dump info. + */ +void FormDumpMgr::DumpFormHostInfo(const FormHostRecord &formHostRecord, std::string &formInfo) const +{ + APP_LOGI("%{public}s called.", __func__); + formInfo += " ================FormHostRecord================="; + formInfo += " callerUid [" + std::to_string(formHostRecord.GetCallerUid()) + "]"; + formInfo += " hostBundleName [" + formHostRecord.GetHostBundleName() + "]"; + APP_LOGI("%{public}s success. Host Form infos:%{public}s", __func__, formInfo.c_str()); +} + +/** + * @brief Dump form infos. + * @param formRecordInfo Form record info. + * @param formInfo Form dump info. + */ +void FormDumpMgr::DumpFormInfo(const FormRecord &formRecordInfo, std::string &formInfo) const +{ + APP_LOGI("%{public}s called.", __func__); + formInfo += " ================FormRecord================="; + formInfo += " FormId [" + std::to_string(formRecordInfo.formId) + "]"; + formInfo += " formName [" + formRecordInfo.formName + "]"; + formInfo += " bundleName [" + formRecordInfo.bundleName + "]"; + formInfo += " moduleName [" + formRecordInfo.moduleName + "]"; + formInfo += " abilityName [" + formRecordInfo.abilityName + "]"; + formInfo += " isInited [" + std::to_string(formRecordInfo.isInited) + "]"; + formInfo += " needRefresh [" + std::to_string(formRecordInfo.needRefresh) + "]"; + formInfo += " isEnableUpdate [" + std::to_string(formRecordInfo.isEnableUpdate) + "]"; + formInfo += " isCountTimerRefresh [" + std::to_string(formRecordInfo.isCountTimerRefresh) + "]"; + formInfo += " specification [" + std::to_string(formRecordInfo.specification) + "]"; + formInfo += " updateDuration [" + std::to_string(formRecordInfo.updateDuration) + "]"; + formInfo += " updateAtHour [" + std::to_string(formRecordInfo.updateAtHour) + "]"; + formInfo += " updateAtMin [" + std::to_string(formRecordInfo.updateAtMin) + "]"; + formInfo += " formTempFlg [" + std::to_string(formRecordInfo.formTempFlg) + "]"; + formInfo += " formVisibleNotify [" + std::to_string(formRecordInfo.formVisibleNotify) + "]"; + formInfo += " formVisibleNotifyState [" + std::to_string(formRecordInfo.formVisibleNotifyState) + "]"; + formInfo += " formSrc [" + formRecordInfo.formSrc + "]"; + formInfo += " designWidth [" + std::to_string(formRecordInfo.formWindow.designWidth) + "]"; + formInfo += " autoDesignWidth [" + std::to_string(formRecordInfo.formWindow.autoDesignWidth) + "]"; + formInfo += " versionCode [" + std::to_string(formRecordInfo.versionCode) + "]"; + formInfo += " versionName [" + formRecordInfo.versionName + "]"; + formInfo += " compatibleVersion [" + std::to_string(formRecordInfo.compatibleVersion) + "]"; + formInfo += " icon [" + formRecordInfo.icon + "]"; + formInfo += " userId [" + std::to_string(formRecordInfo.userId) + "]"; + + if (formRecordInfo.hapSourceDirs.size() > 0) { + formInfo += " hapSourceDirs ["; + for (auto &hapDir : formRecordInfo.hapSourceDirs) { + formInfo += " hapSourceDir [" + hapDir + "]"; + } + formInfo += "]"; + } + + if (formRecordInfo.formUserUids.size() > 0) { + formInfo += " formUserUids ["; + for (auto &uId : formRecordInfo.formUserUids) { + formInfo += " Uid [" + std::to_string(uId) + "]"; + } + formInfo += "]"; + } + + // formCacheData + std::string strCacheData; + if (FormCacheMgr::GetInstance().GetData(formRecordInfo.formId, strCacheData)) { + formInfo += " formCacheData ["; + formInfo += strCacheData; + formInfo += "]" + LINE_SEPARATOR; + } + + APP_LOGI("%{public}s success. Form infos:%{public}s", __func__, formInfo.c_str()); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_event_notify_connection.cpp b/services/formmgr/src/form_event_notify_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..987e5efd4219f02a8fb820dc595f8438e9256f47 --- /dev/null +++ b/services/formmgr/src/form_event_notify_connection.cpp @@ -0,0 +1,60 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_event_notify_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormEventNotifyConnection::FormEventNotifyConnection(const std::vector formEvents, + const int32_t formVisibleType, const std::string &bundleName, const std::string &abilityName) + :formEvents_(formEvents), + formVisibleType_(formVisibleType) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormEventNotifyConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostEventNotifyTask(formEvents_, formVisibleType_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_host_callback.cpp b/services/formmgr/src/form_host_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b634cf2fcef8aa5da4e3f3e9148eeedc8bca42c1 --- /dev/null +++ b/services/formmgr/src/form_host_callback.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_host_callback.h" +#include "form_host_interface.h" +#include "form_task_mgr.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Request to give back a Form. + * @param formId The Id of the forms to create. + * @param record Form record. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +void FormHostCallback::OnAcquired(const int64_t formId, const FormRecord& record, + const sptr &callerToken) +{ + APP_LOGD("FormHostCallback OnAcquired, formId:%{public}" PRId64 "", formId); + FormTaskMgr::GetInstance().PostAcquireTaskToHost(formId, record, callerToken); +} + + +/** +* @brief Form is updated. +* @param formId The Id of the form to update. +* @param record Form record. +* @param callerToken Caller ability token. +* @return Returns ERR_OK on success, others on failure. +*/ +void FormHostCallback::OnUpdate(const int64_t formId, const FormRecord &record, const sptr &callerToken) +{ + APP_LOGI("%{public}s start.", __func__); + + // check formId + if (formId < 0) { + APP_LOGE("%{public}s: OnUpdate invalid param, formId:%{public}" PRId64 ".", __func__, formId); + return; + } + + if (callerToken == nullptr) { + APP_LOGE("%{public}s: callerToken can not be NULL", __func__); + return; + } + + // post updateTask to host + FormTaskMgr::GetInstance().PostUpdateTaskToHost(formId, record, callerToken); +} + +/** + * @brief Form provider is uninstalled + * @param formIds The Id list of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +void FormHostCallback::OnUninstall(std::vector &formIds, const sptr &callerToken) +{ + // check formId + if (formIds.size() <= 0) { + APP_LOGE("%{public}s: OnUninstall invalid param, formIds is empty.", __func__); + return; + } + + if (callerToken == nullptr) { + APP_LOGE("%{public}s: callerToken can not be NULL", __func__); + return; + } + // post updateTask to host + FormTaskMgr::GetInstance().PostUninstallTaskToHost(formIds, callerToken); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_host_record.cpp b/services/formmgr/src/form_host_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e634837bcaa94634d670382b11fe49f201b91329 --- /dev/null +++ b/services/formmgr/src/form_host_record.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_host_record.h" +#include "form_task_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Add form id. + * @param formId The Id of the form. + */ +void FormHostRecord::AddForm(int64_t formId) +{ + if (forms_.find(formId) != forms_.end()) { + return; + } + forms_[formId] = true; +} +/** + * @brief Delete form id. + * @param formId The Id of the form. + */ +void FormHostRecord::DelForm(int64_t formId) +{ + forms_.erase(formId); +} +/** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ +bool FormHostRecord::IsEmpty() const +{ + return forms_.empty(); +} +/** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ +bool FormHostRecord::Contains(int64_t formId) const +{ + return forms_.find(formId) != forms_.end(); +} + +/** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetEnableRefresh(int64_t formId, bool flag) +{ + if (forms_.find(formId) == forms_.end()) { + return; + } + forms_[formId] = flag; +} +/** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsEnableRefresh(int64_t formId) const +{ + auto result = forms_.find(formId); + if (result != forms_.end()) { + return result->second; + } + return false; +} +/** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetNeedRefresh(int64_t formId, bool flag) +{ + needRefresh_[formId] = flag; +} +/** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsNeedRefresh(int64_t formId) const +{ + auto result = needRefresh_.find(formId); + if (result != needRefresh_.end()) { + return result->second; + } + return false; +} +/** + * @brief Get clientStub_. + * @return clientStub_. + */ +sptr FormHostRecord::GetClientStub() const +{ + return clientStub_; +} + +/** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnAcquire(int64_t id, const FormRecord &record) +{ + APP_LOGD("FormHostRecord OnAcquire"); + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be NULL", __func__); + return; + } + + clientImpl_->OnAcquired(id, record, clientStub_); +} + +/** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnUpdate(int64_t id, const FormRecord &record) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + + clientImpl_->OnUpdate(id, record, clientStub_); +} + +/** + * @brief Send form uninstall message to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnFormUninstalled(std::vector &formIds) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + clientImpl_->OnUninstall(formIds, clientStub_); +} +/** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::CleanResource() +{ + if (clientStub_ != nullptr && deathRecipient_ != nullptr) { + clientStub_->RemoveDeathRecipient(deathRecipient_); + clientStub_ = nullptr; + deathRecipient_ = nullptr; + } +} +/** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ +void FormHostRecord::SetCallerUid(const int callerUid) +{ + callerUid_ = callerUid; +} +/** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ +void FormHostRecord::SetClientStub(const sptr &clientStub) +{ + clientStub_ = clientStub; +} +/** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ +void FormHostRecord::SetClientImpl(const std::shared_ptr &clientImpl) +{ + clientImpl_ = clientImpl; +} +/** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ +sptr FormHostRecord::GetDeathRecipient() const +{ + return deathRecipient_; +} +/** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ +void FormHostRecord::SetDeathRecipient(const sptr &deathRecipient) +{ + deathRecipient_ = deathRecipient; +} +/** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ +void FormHostRecord::AddDeathRecipient(const sptr &deathRecipient) +{ + clientStub_->AddDeathRecipient(deathRecipient); +} + +/** + * @brief Create form host record. + * @param info The form item info. + * @param callback remote object. + * @param callingUid Calling uid. + */ +FormHostRecord FormHostRecord::CreateRecord(const FormItemInfo &info, + const sptr &callback, int callingUid) +{ + FormHostRecord record; + record.SetHostBundleName(info.GetHostBundleName()); + record.SetCallerUid(callingUid); + record.SetClientStub(callback); + record.SetClientImpl(std::make_shared()); + record.SetDeathRecipient(new FormHostRecord::ClientDeathRecipient()); + record.AddDeathRecipient(record.GetDeathRecipient()); + + return record; +} + +/** + * @brief handle remote object died event. + * @param remote remote object. + */ +void FormHostRecord::ClientDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGD("Form remote died"); + FormTaskMgr::GetInstance().PostHostDiedTask(remote.promote()); +} + +/** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ +std::string FormHostRecord::GetHostBundleName() const +{ + return hostBundleName_; +} +/** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ +void FormHostRecord::SetHostBundleName(const std::string &hostBundleName) +{ + hostBundleName_ = hostBundleName; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_info_mgr.cpp b/services/formmgr/src/form_info_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..370e25f79517bae37c98b16c761f1d59f2de04bc --- /dev/null +++ b/services/formmgr/src/form_info_mgr.cpp @@ -0,0 +1,351 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_info_mgr.h" + +#include + +#include "app_log_wrapper.h" +#include "bundle_mgr_client.h" +#include "extension_form_profile.h" +#include "form_bms_helper.h" +#include "form_info_storage_mgr.h" +#include "form_util.h" +#include "json_serializer.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string FORM_METADATA_NAME = "ohos.extension.form"; +} // namespace + +ErrCode FormInfoHelper::LoadFormConfigInfoByBundleName(const std::string &bundleName, std::vector &formInfos) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is invalid"); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("GetBundleMgr, failed to get IBundleMgr."); + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + } + + BundleInfo bundleInfo; + if (!iBundleMgr->GetBundleInfo(bundleName, GET_BUNDLE_WITH_EXTENSION_INFO, + bundleInfo, FormUtil::GetCurrentAccountId())) { + APP_LOGE("failed to get bundle info."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + + ErrCode errCode = LoadAbilityFormConfigInfo(bundleInfo, formInfos); + if (errCode != ERR_OK) { + APP_LOGE("failed to load FA form config info, error code=%{public}d.", errCode); + } + + errCode = LoadStageFormConfigInfo(bundleInfo, formInfos); + if (errCode != ERR_OK) { + APP_LOGE("failed to load stage form config info, error code=%{public}d.", errCode); + } + + return ERR_OK; +} + +ErrCode FormInfoHelper::LoadStageFormConfigInfo(const BundleInfo &bundleInfo, std::vector &formInfos) +{ + std::shared_ptr client = DelayedSingleton::GetInstance(); + if (client == nullptr) { + APP_LOGE("failed to get BundleMgrClient."); + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + } + + for (auto const &extensionInfo: bundleInfo.extensionInfos) { + if (extensionInfo.type != ExtensionAbilityType::FORM) { + continue; + } + + std::vector profileInfos {}; + if (!client->GetResConfigFile(extensionInfo, FORM_METADATA_NAME, profileInfos)) { + APP_LOGE("failed to get form metadata."); + continue; + } + + for (const auto &profileInfo: profileInfos) { + std::vector extensionFormInfos; + ErrCode errCode = ExtensionFormProfile::TransformTo(profileInfo, extensionFormInfos); + if (errCode != ERR_OK) { + APP_LOGW("failed to transform profile to extension form info"); + continue; + } + for (const auto &extensionFormInfo: extensionFormInfos) { + formInfos.emplace_back(extensionInfo, extensionFormInfo); + } + } + } + return ERR_OK; +} + +ErrCode FormInfoHelper::LoadAbilityFormConfigInfo(const BundleInfo &bundleInfo, std::vector &formInfos) +{ + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("failed to get IBundleMgr."); + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + } + + const std::string &bundleName = bundleInfo.name; + for (const auto &modelInfo: bundleInfo.hapModuleInfos) { + const std::string &moduleName = modelInfo.moduleName; + std::vector formInfoVec {}; + if (!iBundleMgr->GetFormsInfoByModule(bundleName, moduleName, formInfoVec)) { + continue; + } + for (const auto &formInfo: formInfoVec) { + // check form info + formInfos.push_back(formInfo); + } + } + + return ERR_OK; +} + +BundleFormInfo::BundleFormInfo(std::string bundleName) : bundleName_(std::move(bundleName)) +{ +} + +ErrCode BundleFormInfo::InitFromJson(const std::string &formInfosJson) +{ + nlohmann::json jsonObject = nlohmann::json::parse(formInfosJson, nullptr, false); + if (jsonObject.is_discarded()) { + APP_LOGE("bad profile"); + return ERR_APPEXECFWK_PARSE_BAD_PROFILE; + } + std::unique_lock guard(formInfosMutex_); + formInfos_ = jsonObject.get>(); + return ERR_OK; +} + +ErrCode BundleFormInfo::Update() +{ + std::unique_lock guard(formInfosMutex_); + ErrCode errCode = FormInfoHelper::LoadFormConfigInfoByBundleName(bundleName_, formInfos_); + if (errCode != ERR_OK) { + return errCode; + } + if (formInfos_.empty()) { + return ERR_OK; + } + + nlohmann::json jsonObject = formInfos_; + if (jsonObject.is_discarded()) { + APP_LOGE("bad form infos."); + return ERR_APPEXECFWK_PARSE_BAD_PROFILE; + } + std::string formInfoStr = jsonObject.dump(Constants::DUMP_INDENT); + errCode = FormInfoStorageMgr::GetInstance().UpdateBundleFormInfos(bundleName_, formInfoStr); + return errCode; +} + +ErrCode BundleFormInfo::Remove() +{ + std::unique_lock guard(formInfosMutex_); + formInfos_.clear(); + ErrCode errCode = FormInfoStorageMgr::GetInstance().RemoveBundleFormInfos(bundleName_); + return errCode; +} + +bool BundleFormInfo::Empty() +{ + std::shared_lock guard(formInfosMutex_); + return formInfos_.empty(); +} + +ErrCode BundleFormInfo::GetAllFormsInfo(std::vector &formInfos) +{ + std::shared_lock guard(formInfosMutex_); + for (const auto &formInfo: formInfos_) { + formInfos.push_back(formInfo); + } + return ERR_OK; +} + +ErrCode BundleFormInfo::GetFormsInfoByModule(const std::string &moduleName, std::vector &formInfos) +{ + std::shared_lock guard(formInfosMutex_); + for (const auto &formInfo: formInfos_) { + if (formInfo.moduleName == moduleName) { + formInfos.push_back(formInfo); + } + } + return ERR_OK; +} + +FormInfoMgr::FormInfoMgr() +{ + APP_LOGI("FormInfoMgr is created"); +} + +FormInfoMgr::~FormInfoMgr() = default; + +ErrCode FormInfoMgr::Start() +{ + std::vector> formInfos; + ErrCode errCode = FormInfoStorageMgr::GetInstance().LoadFormInfos(formInfos); + if (errCode != ERR_OK) { + APP_LOGE("LoadFormData failed."); + return errCode; + } + + std::unique_lock guard(bundleFormInfoMapMutex_); + for (const auto &item: formInfos) { + const std::string &bundleName = item.first; + const std::string &formInfosJson = item.second; + auto bundleFormInfoPtr = std::make_shared(bundleName); + errCode = bundleFormInfoPtr->InitFromJson(formInfosJson); + if (errCode != ERR_OK) { + continue; + } + APP_LOGE("load bundle %{public}s form infos success.", bundleName.c_str()); + bundleFormInfoMap_[bundleName] = bundleFormInfoPtr; + } + APP_LOGI("load bundle form infos from db done."); + return ERR_OK; +} + +ErrCode FormInfoMgr::Update(const std::string &bundleName) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + auto bundleFormInfoPtr = std::make_shared(bundleName); + ErrCode errCode = bundleFormInfoPtr->Update(); + if (errCode != ERR_OK) { + return errCode; + } + + if (bundleFormInfoPtr->Empty()) { + // no forms found, no need to be inserted into the map + return ERR_OK; + } + + std::unique_lock guard(bundleFormInfoMapMutex_); + bundleFormInfoMap_[bundleName] = bundleFormInfoPtr; + APP_LOGE("update forms info success, bundleName=%{public}s.", bundleName.c_str()); + return ERR_OK; +} + +ErrCode FormInfoMgr::Remove(const std::string &bundleName) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + std::unique_lock guard(bundleFormInfoMapMutex_); + auto bundleFormInfoIter = bundleFormInfoMap_.find(bundleName); + if (bundleFormInfoIter == bundleFormInfoMap_.end()) { + // BundleFormInfo not found, no need to remove + return ERR_OK; + } + + ErrCode errCode = ERR_OK; + if (bundleFormInfoIter->second != nullptr) { + errCode = bundleFormInfoIter->second->Remove(); + } + bundleFormInfoMap_.erase(bundleFormInfoIter); + APP_LOGE("remove forms info success, bundleName=%{public}s.", bundleName.c_str()); + return errCode; +} + +ErrCode FormInfoMgr::GetAllFormsInfo(std::vector &formInfos) +{ + std::shared_lock guard(bundleFormInfoMapMutex_); + for (const auto &bundleFormInfo: bundleFormInfoMap_) { + if (bundleFormInfo.second != nullptr) { + bundleFormInfo.second->GetAllFormsInfo(formInfos); + } + } + return ERR_OK; +} + +ErrCode FormInfoMgr::GetFormsInfoByBundle(const std::string &bundleName, std::vector &formInfos) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + std::shared_lock guard(bundleFormInfoMapMutex_); + auto bundleFormInfoIter = bundleFormInfoMap_.find(bundleName); + if (bundleFormInfoIter == bundleFormInfoMap_.end()) { + APP_LOGE("no forms found."); + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + if (bundleFormInfoIter->second != nullptr) { + bundleFormInfoIter->second->GetAllFormsInfo(formInfos); + } + return ERR_OK; +} + +ErrCode FormInfoMgr::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfos) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + std::shared_lock guard(bundleFormInfoMapMutex_); + auto bundleFormInfoIter = bundleFormInfoMap_.find(bundleName); + if (bundleFormInfoIter == bundleFormInfoMap_.end()) { + APP_LOGE("no forms found for %{public}s.", bundleName.c_str()); + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + if (bundleFormInfoIter->second != nullptr) { + bundleFormInfoIter->second->GetFormsInfoByModule(moduleName, formInfos); + } + return ERR_OK; +} + +std::shared_ptr FormInfoMgr::GetOrCreateBundleFromInfo(const std::string &bundleName) +{ + { + std::shared_lock guard(bundleFormInfoMapMutex_); + auto bundleFormInfoIter = bundleFormInfoMap_.find(bundleName); + if (bundleFormInfoIter != bundleFormInfoMap_.end()) { + // found + return bundleFormInfoIter->second; + } + } + + // not found + std::unique_lock guard(bundleFormInfoMapMutex_); + auto bundleFormInfoIter = bundleFormInfoMap_.find(bundleName); + // try to find again + if (bundleFormInfoIter != bundleFormInfoMap_.end()) { + // found + return bundleFormInfoIter->second; + } + auto bundleFormInfoPtr = std::make_shared(bundleName); + bundleFormInfoMap_[bundleName] = bundleFormInfoPtr; + return bundleFormInfoPtr; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_info_storage_mgr.cpp b/services/formmgr/src/form_info_storage_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b19a809a23872387139223be55045dcc28fcd09f --- /dev/null +++ b/services/formmgr/src/form_info_storage_mgr.cpp @@ -0,0 +1,324 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_info_storage_mgr.h" +#include +#include +#include "app_log_wrapper.h" +#include "kvstore_death_recipient_callback.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t CHECK_TIMES = 300; +const int32_t CHECK_INTERVAL = 100000; // 100ms +} // namespace + +KvStoreDeathRecipientCallbackFormInfoStorage::KvStoreDeathRecipientCallbackFormInfoStorage() +{ + APP_LOGI("create kvstore death recipient callback instance %{public}p", this); +} + +KvStoreDeathRecipientCallbackFormInfoStorage::~KvStoreDeathRecipientCallbackFormInfoStorage() +{ + APP_LOGI("destroy kvstore death recipient callback instance %{public}p", this); +} + +void KvStoreDeathRecipientCallbackFormInfoStorage::OnRemoteDied() +{ + APP_LOGI("OnRemoteDied, register data change listener begin"); + std::thread([] { + int32_t times = 0; + FormInfoStorageMgr &formInfoStorageMgr = FormInfoStorageMgr::GetInstance(); + while (times < CHECK_TIMES) { + times++; + // init kvStore. + if (formInfoStorageMgr.ResetKvStore()) { + // register data change listener again. + APP_LOGI("current times is %{public}d", times); + break; + } + usleep(CHECK_INTERVAL); + } + }).detach(); + + APP_LOGI("OnRemoteDied, register data change listener end"); +} + +FormInfoStorageMgr::FormInfoStorageMgr() +{ + DistributedKv::Status status = GetKvStore(); + if (status == DistributedKv::Status::IPC_ERROR) { + status = GetKvStore(); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + RegisterKvStoreDeathListener(); + APP_LOGI("FormInfoStorageMgr is created"); +} + +FormInfoStorageMgr::~FormInfoStorageMgr() +{ + dataManager_.CloseKvStore(appId_, kvStorePtr_); +} + +ErrCode FormInfoStorageMgr::LoadFormInfos(std::vector> &formInfos) +{ + APP_LOGI("FormInfoStorageMgr load all form infos"); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + DistributedKv::Status status; + std::vector allEntries; + status = GetEntries(allEntries); + if (status == DistributedKv::Status::IPC_ERROR) { + status = GetEntries(allEntries); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("get entries error: %{public}d", status); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + for (const auto &item: allEntries) { + formInfos.emplace_back(item.key.ToString(), item.value.ToString()); + } + + return ERR_OK; +} + +ErrCode FormInfoStorageMgr::GetBundleFormInfos(const std::string &bundleName, std::string &formInfos) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + APP_LOGI("FormInfoStorageMgr get form info, bundleName=%{public}s", bundleName.c_str()); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + DistributedKv::Status status = DistributedKv::Status::ERROR; + std::vector allEntries; + DistributedKv::Key key(bundleName); + if (kvStorePtr_) { + // sync call GetEntries, the callback will be trigger at once + status = kvStorePtr_->GetEntries(key, allEntries); + } + + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("get entries error: %{public}d", status); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + if (allEntries.empty()) { + APP_LOGE("%{public}s not match any FormInfo", bundleName.c_str()); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + formInfos = allEntries.front().value.ToString(); + return ERR_OK; +} + +ErrCode FormInfoStorageMgr::SaveBundleFormInfos(const std::string &bundleName, const std::string &formInfos) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + APP_LOGI("FormInfoStorageMgr save form info, bundleName=%{public}s", bundleName.c_str()); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + DistributedKv::Key key(bundleName); + DistributedKv::Value value(formInfos); + DistributedKv::Status status; + { + std::lock_guard lock(kvStorePtrMutex_); + status = kvStorePtr_->Put(key, value); + if (status == DistributedKv::Status::IPC_ERROR) { + status = kvStorePtr_->Put(key, value); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + } + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("save formInfos to kvStore error: %{public}d", status); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + return ERR_OK; +} + +ErrCode FormInfoStorageMgr::RemoveBundleFormInfos(const std::string &bundleName) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + APP_LOGI("FormInfoStorageMgr remove form info, bundleName=%{public}s", bundleName.c_str()); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + DistributedKv::Key key(bundleName); + DistributedKv::Status status; + { + std::lock_guard lock(kvStorePtrMutex_); + status = kvStorePtr_->Delete(key); + if (status == DistributedKv::Status::IPC_ERROR) { + status = kvStorePtr_->Delete(key); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + } + + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("remove formInfos from kvStore error: %{public}d", status); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + return ERR_OK; +} + +ErrCode FormInfoStorageMgr::UpdateBundleFormInfos(const std::string &bundleName, const std::string &formInfos) +{ + if (bundleName.empty()) { + APP_LOGE("bundleName is empty."); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + APP_LOGI("FormInfoStorageMgr update form info, bundleName=%{public}s", bundleName.c_str()); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + DistributedKv::Key key(bundleName); + DistributedKv::Status status; + std::lock_guard lock(kvStorePtrMutex_); + status = kvStorePtr_->Delete(key); + if (status == DistributedKv::Status::IPC_ERROR) { + status = kvStorePtr_->Delete(key); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + if (status != DistributedKv::Status::SUCCESS && status != DistributedKv::Status::KEY_NOT_FOUND) { + APP_LOGE("update formInfos to kvStore error: %{public}d", status); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + DistributedKv::Value value(formInfos); + status = kvStorePtr_->Put(key, value); + if (status == DistributedKv::Status::IPC_ERROR) { + status = kvStorePtr_->Put(key, value); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("update formInfos to kvStore error: %{public}d", status); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + return ERR_OK; +} + +DistributedKv::Status FormInfoStorageMgr::GetKvStore() +{ + DistributedKv::Options options = { + .createIfMissing = true, + .encrypt = false, + .autoSync = true, + .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION + }; + + DistributedKv::Status status = dataManager_.GetSingleKvStore(options, appId_, storeId_, kvStorePtr_); + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("return error: %{public}d", status); + } else { + APP_LOGI("get kvStore success"); + } + return status; +} + +bool FormInfoStorageMgr::CheckKvStore() +{ + if (kvStorePtr_ != nullptr) { + return true; + } + int32_t tryTimes = MAX_TIMES; + while (tryTimes > 0) { + DistributedKv::Status status = GetKvStore(); + if (status == DistributedKv::Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + APP_LOGI("CheckKvStore, Times: %{public}d", tryTimes); + usleep(SLEEP_INTERVAL); + tryTimes--; + } + return kvStorePtr_ != nullptr; +} + +void FormInfoStorageMgr::RegisterKvStoreDeathListener() +{ + APP_LOGI("register kvStore death listener"); + std::shared_ptr callback = + std::make_shared(); + dataManager_.RegisterKvStoreServiceDeathRecipient(callback); +} + +bool FormInfoStorageMgr::ResetKvStore() +{ + std::lock_guard lock(kvStorePtrMutex_); + kvStorePtr_ = nullptr; + DistributedKv::Status status = GetKvStore(); + if (status == DistributedKv::Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + APP_LOGW("failed"); + return false; +} + +DistributedKv::Status FormInfoStorageMgr::GetEntries(std::vector &allEntries) +{ + DistributedKv::Status status = DistributedKv::Status::ERROR; + // if prefix is empty, get all entries. + DistributedKv::Key key(""); + if (kvStorePtr_) { + // sync call GetEntries, the callback will be trigger at once + status = kvStorePtr_->GetEntries(key, allEntries); + } + APP_LOGI("get all entries status: %{public}d", status); + return status; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_item_info.cpp b/services/formmgr/src/form_item_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0262e8de61db690cea3cc1e0eca7e58234e3b9d0 --- /dev/null +++ b/services/formmgr/src/form_item_info.cpp @@ -0,0 +1,467 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "form_item_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Get formId_. + * @return formId_. + */ +int64_t FormItemInfo::GetFormId() const +{ + return formId_; +} +/** + * @brief Get packageName_. + * @return packageName_. + */ +std::string FormItemInfo::GetPackageName() const +{ + return packageName_; +} +/** + * @brief Get providerBundleName_. + * @return providerBundleName_. + */ +std::string FormItemInfo::GetProviderBundleName() const +{ + return providerBundleName_; +} +/** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ +std::string FormItemInfo::GetHostBundleName() const +{ + return hostBundleName_; +} +/** + * @brief Get moduleName_. + * @return moduleName_. + */ +std::string FormItemInfo::GetModuleName() const +{ + return moduleName_; +} +/** + * @brief Get abilityName_. + * @return abilityName_. + */ +std::string FormItemInfo::GetAbilityName() const +{ + return abilityName_; +} +/** + * @brief Get formName_. + * @return formName_. + */ +std::string FormItemInfo::GetFormName() const +{ + return formName_; +} +/** + * @brief Get jsComponentName_. + * @return jsComponentName_. + */ +std::string FormItemInfo::GetJsComponentName() const +{ + return jsComponentName_; +} +/** + * @brief Get abilityModuleName_. + * @return abilityModuleName_. + */ +std::string FormItemInfo::GetAbilityModuleName() const +{ + return abilityModuleName_; +} +/** + * @brief Get specificationId_. + * @return specificationId_. + */ +int FormItemInfo::GetSpecificationId() const +{ + return specificationId_; +} + +/** + * @brief Obtains the updageFlag. + * @return Returns updageFlag. + */ +bool FormItemInfo::IsEnableUpdateFlag() const +{ + return updateFlag_; +} +/** + * @brief Get updateDuration_. + * @return updateDuration_. + */ +int FormItemInfo::GetUpdateDuration() const +{ + return updateDuration_; +} +/** + * @brief Get scheduledUpdateTime_. + * @return scheduledUpdateTime_. + */ +std::string FormItemInfo::GetScheduledUpdateTime() const +{ + return scheduledUpdateTime_; +} + +/** + * @brief Get hapSourceDirs_. + * @param dirs Hap source dirs. + * @return Returns true on success, false on failure. + */ +bool FormItemInfo::GetHapSourceDirs(std::vector &dirs) const +{ + if (hapSourceDirs_.size() > 0) { + dirs.assign(hapSourceDirs_.begin(), hapSourceDirs_.end()); + return true; + } + return false; +} +/** + * @brief Set value of hapSourceDirs_. + * @param hapSourceDirs Hap source dirs. + */ +void FormItemInfo::SetHapSourceDirs(const std::vector &hapSourceDirs) +{ + hapSourceDirs_ = hapSourceDirs; +} +/** + * @brief Obtains the temporaryFlag. + * @return Returns temporaryFlag. + */ +bool FormItemInfo::IsTemporaryForm() const +{ + return temporaryFlag_; +} + +/** + * @brief Obtains the hap source by ability module name. + * @param moduleName ability module name + * @return Returns hap source. + */ +std::string FormItemInfo::GetHapSourceByModuleName(const std::string &moduleName) const +{ + auto iter = moduleInfoMap_.find(moduleName); + if (iter != moduleInfoMap_.end()) { + return iter->second; + } + return ""; +} +/** + * @brief Check if item valid or not. + * @return Valid or not + */ +bool FormItemInfo::IsValidItem() const +{ + if (providerBundleName_.empty() || moduleName_.empty() + || abilityName_.empty() || formName_.empty()) { + return false; + } + return true; +} +/** + * @brief Check if item match or not. + * @return Match or not + */ +bool FormItemInfo::IsMatch(const FormRecord &record) const +{ + APP_LOGD("match data"); + APP_LOGD("FormRecord.bundleName : %{public}s", record.bundleName.c_str()); + APP_LOGD("FormRecord.moduleName : %{public}s", record.moduleName.c_str()); + APP_LOGD("FormRecord.abilityName : %{public}s", record.abilityName.c_str()); + APP_LOGD("FormRecord.formName : %{public}s", record.formName.c_str()); + APP_LOGD("FormRecord.specification : %{public}d", record.specification); + + APP_LOGD("FormItemInfo.providerBundleName_ : %{public}s", providerBundleName_.c_str()); + APP_LOGD("FormItemInfo.moduleName : %{public}s", moduleName_.c_str()); + APP_LOGD("FormItemInfo.abilityName : %{public}s", abilityName_.c_str()); + APP_LOGD("FormItemInfo.formName : %{public}s", formName_.c_str()); + APP_LOGD("FormItemInfo.specification : %{public}d", specificationId_); + + return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) + && (record.abilityName == abilityName_) && (record.formName == formName_) + && (record.specification == specificationId_); +} +/** + * @brief Check if form config same or not. + * @return Same or not + */ +bool FormItemInfo::IsSameFormConfig(const FormRecord &record) const +{ + return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) + && (record.abilityName == abilityName_) && (record.formName == formName_); +} + +/** + * @brief Check if visible notify or not. + * @return visible notify or not + */ +bool FormItemInfo::IsFormVisibleNotify() const +{ + return formVisibleNotify_; +} +/** + * @brief Equal or not. + * @param left left string. + * @param right right string. + * @return Equal or not + */ +bool FormItemInfo::IsEqual(const std::string &left, const std::string &right) +{ + return left == right; +} +/** + * @brief Set value of formId_. + * @param formId Form Id. + */ +void FormItemInfo::SetFormId(int64_t formId) +{ + formId_ = formId; +} +/** + * @brief Set value of packageName_. + * @param packageName Package name. + */ +void FormItemInfo::SetPackageName(const std::string &packageName) +{ + packageName_ = packageName; +} +/** + * @brief Set value of providerBundleName_. + * @param providerBundleName Provider bundle Name. + */ +void FormItemInfo::SetProviderBundleName(const std::string &providerBundleName) +{ + providerBundleName_ = providerBundleName; +} +/** + * @brief Set value of hostBundleName_. + * @param hostBundleName Host bundle Name. + */ +void FormItemInfo::SetHostBundleName(const std::string &hostBundleName) +{ + hostBundleName_ = hostBundleName; +} +/** + * @brief Set value of moduleName_. + * @param moduleName Module Name. + */ +void FormItemInfo::SetModuleName(const std::string &moduleName) +{ + moduleName_ = moduleName; +} +/** + * @brief Set value of abilityName_. + * @param abilityName Ability name. + */ +void FormItemInfo::SetAbilityName(const std::string &abilityName) +{ + abilityName_ = abilityName; +} +/** + * @brief Set value of formName_. + * @param formName Form name. + */ +void FormItemInfo::SetFormName(const std::string &formName) +{ + formName_ = formName; +} +/** + * @brief Set value of jsComponentName_. + * @param jsComponentName Js component name. + */ +void FormItemInfo::SetJsComponentName(const std::string &jsComponentName) +{ + jsComponentName_ = jsComponentName; +} +/** + * @brief Set value of abilityModuleName_. + * @param abilityModuleName ability module name_. + */ +void FormItemInfo::SetAbilityModuleName(const std::string &abilityModuleName) +{ + abilityModuleName_ = abilityModuleName; +} +/** + * @brief Set value of specificationId_. + * @param specificationId Specification id. + */ +void FormItemInfo::SetSpecificationId(const int specificationId) +{ + specificationId_ = specificationId; +} +/** + * @brief Set value of updateFlag_. + * @param IsEnableUpdateFlag Enable update flag or not. + */ +void FormItemInfo::SetEnableUpdateFlag(bool IsEnableUpdateFlag) +{ + updateFlag_ = IsEnableUpdateFlag; +} +/** + * @brief Set value of updateDuration_. + * @param updateDuration Update duration. + */ +void FormItemInfo::SetUpdateDuration(int updateDuration) +{ + updateDuration_ = updateDuration; +} +/** + * @brief Set value of scheduledUpdateTime_. + * @param scheduledUpdateTime Scheduled update time. + */ +void FormItemInfo::SetScheduledUpdateTime(const std::string &scheduledUpdateTime) +{ + scheduledUpdateTime_ = scheduledUpdateTime; +} +/** + * @brief Add hap source dir. + * @param hapSourceDir Hap source dir. + */ +void FormItemInfo::AddHapSourceDirs(const std::string &hapSourceDir) +{ + hapSourceDirs_.emplace_back(hapSourceDir); +} +/** + * @brief Set value of temporaryFlag_. + * @param temporaryFlag Temporary flag. + */ +void FormItemInfo::SetTemporaryFlag(bool temporaryFlag) +{ + temporaryFlag_ = temporaryFlag; +} +/** + * @brief Add module info. + * @param moduleName Module name. + * @param moduleSourceDir Module source dir. + */ +void FormItemInfo::AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir) +{ + moduleInfoMap_.emplace(std::make_pair(moduleName, moduleSourceDir)); +} +/** + * @brief Set value of formVisibleNotify_. + * @param isFormVisibleNotify visible notify or not. + */ +void FormItemInfo::SetFormVisibleNotify(bool isFormVisibleNotify) +{ + formVisibleNotify_ = isFormVisibleNotify; +} +/** + * @brief Get formSrc_. + * @return formSrc_. + */ +std::string FormItemInfo::GetFormSrc() const +{ + return formSrc_; +} +/** + * @brief Set value of formSrc_. + * @param formSrc form src. + */ +void FormItemInfo::SetFormSrc(const std::string &formSrc) +{ + formSrc_ = formSrc; +} +/** + * @brief Get formWindow_. + * @return formWindow_. + */ +FormWindow FormItemInfo::GetFormWindow() const +{ + return formWindow_; +} +/** + * @brief Set value of formWindow_. + * @param formWindow form window. + */ +void FormItemInfo::SetFormWindow(const FormWindow &formWindow) +{ + formWindow_.autoDesignWidth = formWindow.autoDesignWidth; + formWindow_.designWidth = formWindow.designWidth; +} +/** + * @brief Get versionCode_. + * @return versionCode_. + */ +uint32_t FormItemInfo::GetVersionCode() const +{ + return versionCode_; +} +/** + * @brief Set value of versionCode_. + * @param versionCode bundle version code. + */ +void FormItemInfo::SetVersionCode(const uint32_t versionCode) +{ + versionCode_ = versionCode; +} +/** + * @brief Get versionName_. + * @return versionName_. + */ +std::string FormItemInfo::GetVersionName() const +{ + return versionName_; +} +/** + * @brief Set value of versionName_. + * @param versionName bundle version name. + */ +void FormItemInfo::SetVersionName(const std::string &versionName) +{ + versionName_ = versionName; +} +/** + * @brief Get compatibleVersion_. + * @return compatibleVersion_. + */ +uint32_t FormItemInfo::GetCompatibleVersion() const +{ + return compatibleVersion_; +} +/** + * @brief Set value of compatibleVersion_. + * @param compatibleVersion bundle version name. + */ +void FormItemInfo::SetCompatibleVersion(const uint32_t &compatibleVersion) +{ + compatibleVersion_ = compatibleVersion; +} +/** + * @brief Get icon_. + * @return icon_. + */ +std::string FormItemInfo::GetIcon() const +{ + return icon_; +} +/** + * @brief Set value of icon_. + * @param icon bundle version name. + */ +void FormItemInfo::SetIcon(const std::string &icon) +{ + icon_ = icon; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66abcf4432a6b089efa563c9a66821f7701eb468 --- /dev/null +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -0,0 +1,1720 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_acquire_connection.h" +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_cache_mgr.h" +#include "form_cast_temp_connection.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_db_info.h" +#include "form_delete_connection.h" +#include "form_dump_mgr.h" +#include "form_event_notify_connection.h" +#include "form_info_mgr.h" +#include "form_mgr_adapter.h" +#include "form_provider_info.h" +#include "form_provider_interface.h" +#include "form_provider_mgr.h" +#include "form_refresh_connection.h" +#include "form_supply_callback.h" +#include "form_timer_mgr.h" +#include "form_util.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "ohos_account_kits.h" +#include "power_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +const int HUNDRED = 100; +constexpr int32_t UID_CALLINGUID_TRANSFORM_DIVISOR = 200000; + +FormMgrAdapter::FormMgrAdapter() +{ +}; +FormMgrAdapter::~FormMgrAdapter() +{ +}; +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::AddForm(const int64_t formId, const Want &want, + const sptr &callerToken, FormJsInfo &formInfo) +{ + if (formId < 0 || callerToken == nullptr) { + APP_LOGE("%{public}s fail, callerToken can not be NULL", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // check form count limit + bool tempFormFlag = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + int callingUid = IPCSkeleton::GetCallingUid(); + int checkCode = 0; + if (tempFormFlag) { + if (formId > 0) { + APP_LOGE("%{public}s fail, temp form id is invalid, formId:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + checkCode = FormDataMgr::GetInstance().CheckTempEnoughForm(); + } else { + if (formId == 0) { + // get current userId + int32_t currentUserId = GetCurrentUserId(callingUid); + checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid, currentUserId); + } + } + if (checkCode != 0) { + APP_LOGE("%{public}s fail, too much forms in system", __func__); + return checkCode; + } + + // get from config info + FormItemInfo formItemInfo; + int32_t errCode = GetFormConfigInfo(want, formItemInfo); + formItemInfo.SetFormId(formId); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s fail, get form config info failed.", __func__); + return errCode; + } + if (!formItemInfo.IsValidItem()) { + APP_LOGE("%{public}s fail, input param itemInfo is invalid", __func__); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + if (!FormDataMgr::GetInstance().GenerateUdidHash()) { + APP_LOGE("%{public}s fail, generate udid hash failed", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + WantParams wantParams = want.GetParams(); + if (formId > 0) { + return AllotFormById(formItemInfo, callerToken, wantParams, formInfo); + } else { + return AllotFormByInfo(formItemInfo, callerToken, wantParams, formInfo); + } +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + if (formId <= 0 || callerToken == nullptr) { + APP_LOGE("%{public}s, deleteForm invalid param", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { + // delete temp form if receive delete form call + return HandleDeleteTempForm(matchedFormId, callerToken); + } + return HandleDeleteForm(matchedFormId, callerToken); +} + +/** + * @brief Release forms with formIds, send formIds to form Mgr service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0 || callerToken == nullptr) { + APP_LOGE("%{public}s, releaseForm invalid param", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { + // delete temp form if receive release form call + return HandleDeleteTempForm(matchedFormId, callerToken); + } + FormRecord dbRecord; + if (FormDbCache::GetInstance().GetDBRecord(matchedFormId, dbRecord) != ERR_OK) { + APP_LOGE("%{public}s, not exist such db form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = GetCurrentUserId(callingUid); + bool isSelfDbFormId = (userId == dbRecord.userId) && ((std::find(dbRecord.formUserUids.begin(), + dbRecord.formUserUids.end(), callingUid) != dbRecord.formUserUids.end()) ? true : false); + if (!isSelfDbFormId) { + APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + if (delCache) { + if (ErrCode result = HandleReleaseForm(matchedFormId, callerToken); result != ERR_OK) { + APP_LOGE("%{public}s, release form error.", __func__); + return result; + } + } + + if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, matchedFormId)) { + APP_LOGE("%{public}s, failed to remove host record", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if (!FormTimerMgr::GetInstance().RemoveFormTimer(matchedFormId)) { + APP_LOGE("%{public}s, remove timer error", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + return ERR_OK; +} + +/** + * @brief Handle release form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleReleaseForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + if (!FormDataMgr::GetInstance().ExistFormRecord(formId)) { + APP_LOGE("%{public}s, not exist such db or temp form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + FormHostRecord hostRecord; + bool hasHostRec = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, hostRecord); + bool isSelfId = hasHostRec && hostRecord.Contains(formId); + if (!isSelfId) { + APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + APP_LOGD("%{public}s, release formRecords, formId: %{public}" PRId64 "", __func__, formId); + FormDataMgr::GetInstance().DeleteFormUserUid(formId, IPCSkeleton::GetCallingUid()); + if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) { + FormDataMgr::GetInstance().DeleteFormRecord(formId); + if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) { + APP_LOGE("%{public}s, remove timer error", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + return ERR_OK; +} + +/** + * @brief Handle delete form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleDeleteForm(const int64_t formId, const sptr &callerToken) +{ + FormRecord dbRecord; + if (FormDbCache::GetInstance().GetDBRecord(formId, dbRecord) != ERR_OK) { + APP_LOGE("%{public}s, not exist such db form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = GetCurrentUserId(callingUid); + bool isSelfDbFormId = (userId == dbRecord.userId) && ((std::find(dbRecord.formUserUids.begin(), + dbRecord.formUserUids.end(), callingUid) != dbRecord.formUserUids.end()) ? true : false); + if (!isSelfDbFormId) { + APP_LOGE("%{public}s, not self form:%{public}" PRId64 ", callingUid:%{public}d", __func__, formId, callingUid); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + if (ErrCode result = HandleDeleteFormCache(dbRecord, callingUid, formId); result != ERR_OK) { + return result; + } + + if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) { + APP_LOGE("%{public}s, failed to remove host record", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + return ERR_OK; +} + +/** + * @brief Handle delete temp form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleDeleteTempForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + int uid = IPCSkeleton::GetCallingUid(); + FormRecord record; + bool isFormRecExist = FormDataMgr::GetInstance().GetFormRecord(formId, record); + bool isSelfTempFormId = false; + if (isFormRecExist && record.formTempFlg) { + int32_t userId = GetCurrentUserId(uid); + isSelfTempFormId = (userId == record.userId) && ((std::find(record.formUserUids.begin(), + record.formUserUids.end(), uid) != record.formUserUids.end()) ? true : false); + } + if (!isSelfTempFormId) { + APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid); + if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) { + int result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, record); + if (result != ERR_OK) { + APP_LOGE("%{public}s, failed!", __func__); + FormDataMgr::GetInstance().AddFormUserUid(formId, uid); + return result; + } + FormDataMgr::GetInstance().DeleteTempForm(formId); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + if (!FormCacheMgr::GetInstance().DeleteData(formId)) { + APP_LOGE("%{public}s, failed to remove cache data", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) { + APP_LOGE("%{public}s, failed to remove host record", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + APP_LOGD("%{public}s, record.formUserUids size: %{public}zu", __func__, record.formUserUids.size()); + return ERR_OK; +} + +/** + * @brief Handle delete form cache. + * @param dbRecord Form storage information. + * @param uid calling user id. + * @param formId The form id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleDeleteFormCache(FormRecord &dbRecord, const int uid, const int64_t formId) +{ + APP_LOGD("%{public}s, delete formDBRecords, formId: %{public}" PRId64 "", __func__, formId); + auto iter = std::find(dbRecord.formUserUids.begin(), dbRecord.formUserUids.end(), uid); + if (iter != dbRecord.formUserUids.end()) { + dbRecord.formUserUids.erase(iter); + } + + ErrCode result = ERR_OK; + if (dbRecord.formUserUids.empty()) { + result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, dbRecord); + if (result != ERR_OK) { + APP_LOGE("%{public}s, failed to notify provider form delete", __func__); + return result; + } + if (!FormDataMgr::GetInstance().DeleteFormRecord(formId)) { + APP_LOGE("%{public}s, failed to remove cache data", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if (result = FormDbCache::GetInstance().DeleteFormInfo(formId); result != ERR_OK) { + APP_LOGE("%{public}s, failed to remove db data", __func__); + return result; + } + + int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(dbRecord.bundleName, dbRecord.moduleName); + if (matchCount == 0) { + FormBmsHelper::GetInstance().NotifyModuleRemovable(dbRecord.bundleName, dbRecord.moduleName); + } + + if (!FormCacheMgr::GetInstance().DeleteData(formId)) { + APP_LOGE("%{public}s, failed to remove cache data", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) { + APP_LOGE("%{public}s, remove timer error", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + return ERR_OK; + } + + if (result = FormDbCache::GetInstance().UpdateDBRecord(formId, dbRecord); result != ERR_OK) { + return result; + } + + APP_LOGD("%{public}s, dbRecord.formUserUids size: %{public}zu", __func__, dbRecord.formUserUids.size()); + FormBmsHelper::GetInstance().NotifyModuleNotRemovable(dbRecord.bundleName, dbRecord.moduleName); + if (!FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid)) { + APP_LOGE("%{public}s, failed to remove form user uid", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + return result; +} + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formProviderData form provider data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::UpdateForm(const int64_t formId, + const std::string &bundleName, const FormProviderData &formProviderData) +{ + APP_LOGI("%{public}s start.", __func__); + + // check formId and bundleName + if (formId <= 0 || bundleName.empty()) { + APP_LOGE("%{public}s error, the passed in formId can't be negative or zero, bundleName is not empty.", + __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // get IBundleMgr + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + } + + // check bundle uid for permission + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = GetCurrentUserId(callingUid); + int32_t bundleUid = iBundleMgr->GetUidByBundleName(bundleName, userId); + if (bundleUid != callingUid) { + APP_LOGE("%{public}s error, permission denied, the updated form is not your own.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // find matched formId + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + + // check exist and get the formRecord + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGE("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + if (userId != formRecord.userId) { + APP_LOGE("%{public}s error, not under current user, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + // check bundleName match + if (formRecord.bundleName.compare(bundleName) != 0) { + APP_LOGE("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str()); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // update Form + return FormProviderMgr::GetInstance().UpdateForm(matchedFormId, formRecord, formProviderData); +} + +/** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0 || callerToken == nullptr) { + APP_LOGE("%{public}s fail, callerToken can not be NULL.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId)) { + APP_LOGE("%{public}s fail, not exist such formId:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + FormHostRecord formHostRecord; + bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); + if (!isHostExist) { + APP_LOGE("%{public}s fail, cannot find target client.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (!formHostRecord.Contains(matchedFormId)) { + APP_LOGE("%{public}s fail, form is not self-owned.", __func__); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + APP_LOGI("%{public}s, find target client.", __func__); + Want reqWant(want); + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = GetCurrentUserId(callingUid); + reqWant.SetParam(Constants::PARAM_FORM_USER_ID, userId); + return FormProviderMgr::GetInstance().RefreshForm(matchedFormId, reqWant); +} + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The vector of form Ids. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector &formIds, + const sptr &callerToken, const int32_t formVisibleType) +{ + APP_LOGI("%{public}s called.", __func__); + + if (callerToken == nullptr) { + APP_LOGE("%{public}s fail, callerToken can not be NULL.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s fail, failed to get IBundleMgr.", __func__); + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + } + + int64_t matchedFormId; + std::map> eventMaps; + for (int64_t formId : formIds) { + if (formId <= 0) { + APP_LOGW("%{public}s, formId %{public}" PRId64 " is less than 0", __func__, formId); + continue; + } + matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + FormRecord formRecord; + // Update provider info to host + if (!UpdateProviderInfoToHost(matchedFormId, callerToken, formVisibleType, formRecord)) { + continue; + } + + // Check if the form provider is system app + if (!CheckIsSystemAppByBundleName(iBundleMgr, formRecord.bundleName)) { + continue; + } + + // Create eventMaps + if (!CreateHandleEventMap(matchedFormId, formRecord, eventMaps)) { + continue; + } + } + + for (auto iter = eventMaps.begin(); iter != eventMaps.end(); iter++) { + if (HandleEventNotify(iter->first, iter->second, formVisibleType) != ERR_OK) { + APP_LOGW("%{public}s fail, HandleEventNotify error, key is %{public}s.", __func__, iter->first.c_str()); + } + } + + return ERR_OK; +} + +/** + * @brief Temp form to normal form. + * @param formId The Id of the form. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + if (formId <= 0 || callerToken == nullptr) { + APP_LOGE("%{public}s, invalid param", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) || + !FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { + APP_LOGE("%{public}s, not exist such temp form:%{public}" PRId64 "", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + FormHostRecord record; + bool hasHostRec = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, record); + if (!hasHostRec || !record.Contains(matchedFormId)) { + APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = GetCurrentUserId(callingUid); + int checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid, userId); + if (checkCode != 0) { + APP_LOGE("%{public}s, %{public}" PRId64 " failed,because if too mush forms", __func__, matchedFormId); + return checkCode; + } + + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + int bindSupplierCheckCode = HandleCastTempForm(matchedFormId, formRecord); + if (bindSupplierCheckCode != 0) { + APP_LOGE("%{public}s, cast temp form bindSupplier failed", __func__); + return bindSupplierCheckCode; + } + + if (!FormDataMgr::GetInstance().DeleteTempForm(matchedFormId)) { + APP_LOGE("%{public}s fail, delete temp form error, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + if (!FormDataMgr::GetInstance().ModifyFormTempFlg(matchedFormId, false)) { + APP_LOGE("%{public}s fail, modify form temp flag error, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + if (!FormDataMgr::GetInstance().AddFormUserUid(matchedFormId, callingUid)) { + APP_LOGE("%{public}s fail, add form user uid error, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + if (std::find(formRecord.formUserUids.begin(), formRecord.formUserUids.end(), + callingUid) == formRecord.formUserUids.end()) { + formRecord.formUserUids.emplace_back(callingUid); + } + if (ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(matchedFormId, formRecord); errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, update db record error, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return errorCode; + } + + // start timer + return AddFormTimer(formRecord); +} +/** + * @brief Handle cast temp form. + * @param formId The form id. + * @param record Form information. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleCastTempForm(const int64_t formId, const FormRecord &record) +{ + APP_LOGD("%{public}s, cast temp form to normal form, notify supplier, package:%{public}s, class:%{public}s", + __func__, record.bundleName.c_str(), record.abilityName.c_str()); + sptr castTempConnection = new FormCastTempConnection(formId, + record.bundleName, record.abilityName); + + Want want; + want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + want.SetElementName(record.bundleName, record.abilityName); + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const +{ + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + if (formDBInfos.size() > 0) { + std::sort(formDBInfos.begin(), formDBInfos.end(), + [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { + return formDBInfoA.formId < formDBInfoB.formId; + }); + FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos); + return ERR_OK; + } else { + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) const +{ + APP_LOGI("%{public}s called.", __func__); + std::vector formRecordInfos; + if (FormDataMgr::GetInstance().GetFormRecord(bundleName, formRecordInfos)) { + FormDumpMgr::GetInstance().DumpFormInfos(formRecordInfos, formInfos); + return ERR_OK; + } else { + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const +{ + APP_LOGI("%{public}s called.", __func__); + int reply = ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + + FormRecord formRecord; + if (FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { + FormDumpMgr::GetInstance().DumpFormInfo(formRecord, formInfo); + reply = ERR_OK; + } + + FormHostRecord formHostRecord; + if (FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecord)) { + FormDumpMgr::GetInstance().DumpFormHostInfo(formHostRecord, formInfo); + reply = ERR_OK; + } + + return reply; +} +/** + * @brief Dump form timer by form id. + * @param formId The id of the form. + * @param formInfo Form timer. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) const +{ + APP_LOGI("%{public}s called.", __func__); + FormTimer formTimer; + UpdateAtItem updateAtItem; + DynamicRefreshItem dynamicItem; + bool result_inter = FormTimerMgr::GetInstance().GetIntervalTimer(formId, formTimer); + bool result_update = FormTimerMgr::GetInstance().GetUpdateAtTimer(formId, updateAtItem); + bool result_dynamic = FormTimerMgr::GetInstance().GetDynamicItem(formId, dynamicItem); + APP_LOGI("%{public}s result_inter:%{public}d,result_update:%{public}d,result_dynamic:%{public}d", + __func__, result_inter, result_update, result_dynamic); + if (result_inter || result_update || result_dynamic) { + isTimingService = "true"; + } else { + isTimingService = "false"; + } + return ERR_OK; +} +/** + * @brief Get form configure info. + * @param want The want of the request. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetFormConfigInfo(const Want &want, FormItemInfo &formConfigInfo) +{ + APP_LOGD("GetFormConfigInfo start."); + BundleInfo bundleInfo; + std::string packageName; + + ErrCode errCode = GetBundleInfo(want, bundleInfo, packageName); + if (errCode != ERR_OK) { + APP_LOGE("addForm find bundle info failed"); + return errCode; + } + + FormInfo formInfo; + errCode = GetFormInfo(want, formInfo); + if (errCode != ERR_OK) { + APP_LOGE("addForm can not find target form info"); + return errCode; + } + + errCode = GetFormItemInfo(want, bundleInfo, formInfo, formConfigInfo); + if (errCode != ERR_OK) { + APP_LOGE("get form item info failed."); + return errCode; + } + formConfigInfo.SetPackageName(packageName); + + APP_LOGD("GetFormConfigInfo end."); + return ERR_OK; +} +/** + * @brief Allocate form by formId. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) +{ + int64_t formId = PaddingUDIDHash(info.GetFormId()); + FormRecord record; + bool hasRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record); + if (hasRecord && record.formTempFlg) { + APP_LOGE("%{public}s, addForm can not acquire temp form when select form id", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + // get current userId + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t currentUserId = GetCurrentUserId(callingUid); + if (hasRecord && (record.userId == currentUserId + || FormDataMgr::GetInstance().IsCallingUidValid(record.formUserUids))) { + if (!info.IsMatch(record)) { + APP_LOGE("%{public}s, formId and item info not match:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID; + } + return AddExistFormRecord(info, callerToken, record, formId, wantParams, formInfo); + } + + // find in db but not in cache + FormRecord dbRecord; + ErrCode getDbRet = FormDbCache::GetInstance().GetDBRecord(formId, dbRecord); + if (getDbRet == ERR_OK && (record.userId == currentUserId + || FormDataMgr::GetInstance().IsCallingUidValid(dbRecord.formUserUids))) { + return AddNewFormRecord(info, formId, callerToken, wantParams, formInfo); + } + + APP_LOGI("%{public}s, addForm no such form %{public}" PRId64 "", __func__, formId); + + // delete form data in provider + FormRecord delRecord; + delRecord.bundleName = info.GetProviderBundleName(); + delRecord.abilityName = info.GetAbilityName(); + FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, delRecord); + + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; +} +int64_t FormMgrAdapter::PaddingUDIDHash(const int64_t formId) const +{ + // Compatible with int form id. + uint64_t unsignedFormId = static_cast(formId); + if ((unsignedFormId & 0xffffffff00000000L) == 0) { + int64_t udidHash = FormDataMgr::GetInstance().GetUdidHash(); + uint64_t unsignUdidHash = static_cast(udidHash); + uint64_t unsignUdidHashFormId = unsignUdidHash | unsignedFormId; + int64_t udidHashFormId = static_cast(unsignUdidHashFormId); + return udidHashFormId; + } + return formId; +} +ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr &callerToken, + const FormRecord &record, const int64_t formId, const WantParams &wantParams, + FormJsInfo &formInfo) +{ + APP_LOGI("%{public}s call, formId:%{public}" PRId64 "", __func__, formId); + // allot form host record + int callingUid = IPCSkeleton::GetCallingUid(); + bool isCreated = FormDataMgr::GetInstance().AllotFormHostRecord(info, callerToken, formId, callingUid); + if (!isCreated) { + APP_LOGE("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + FormRecord newRecord(record); + + if (newRecord.needRefresh) { + newRecord.isInited = false; + FormDataMgr::GetInstance().SetFormCacheInited(formId, false); + // acquire formInfo from provider + ErrCode errorCode = AcquireProviderFormInfoAsync(formId, info, wantParams); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__); + return errorCode; + } + } + + // Add new form user uid. + FormDataMgr::GetInstance().AddFormUserUid(formId, callingUid); + if (std::find(newRecord.formUserUids.begin(), newRecord.formUserUids.end(), callingUid) == + newRecord.formUserUids.end()) { + newRecord.formUserUids.emplace_back(callingUid); + } + + // create form info for js + std::string cacheData; + if (FormCacheMgr::GetInstance().GetData(formId, cacheData)) { + formInfo.formData = cacheData; + } + FormDataMgr::GetInstance().CreateFormInfo(formId, record, formInfo); + + // start update timer + if (ErrCode errorCode = AddFormTimer(newRecord); errorCode != ERR_OK) { + return errorCode; + } + + if (!newRecord.formTempFlg) { + return FormDbCache::GetInstance().UpdateDBRecord(formId, newRecord); + } + return ERR_OK; +} +/** + * @brief Allocate form by form configure info. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) +{ + // generate formId + int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId(); + if (newFormId < 0) { + APP_LOGE("%{public}s fail, generateFormId no invalid formId", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + APP_LOGD("newFormId:%{public}" PRId64 "", newFormId); + + return AddNewFormRecord(info, newFormId, callerToken, wantParams, formInfo); +} + +/** + * @brief Add new form record. + * @param info Form configure info. + * @param formId The form id. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AddNewFormRecord(const FormItemInfo &info, const int64_t formId, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) +{ + APP_LOGI("%{public}s start", __func__); + FormItemInfo newInfo(info); + newInfo.SetFormId(formId); + // allot form host record + int callingUid = IPCSkeleton::GetCallingUid(); + if (!FormDataMgr::GetInstance().AllotFormHostRecord(newInfo, callerToken, formId, callingUid)) { + APP_LOGE("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + // get current userId + int32_t currentUserId = GetCurrentUserId(callingUid); + // allot form record + FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(newInfo, callingUid, currentUserId); + + // acquire formInfo from provider + if (ErrCode errorCode = AcquireProviderFormInfoAsync(formId, newInfo, wantParams); errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__); + return errorCode; + } + + // create form info for js + FormDataMgr::GetInstance().CreateFormInfo(formId, formRecord, formInfo); + + // storage info + if (!newInfo.IsTemporaryForm()) { + if (ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(formId, formRecord); errorCode != ERR_OK) { + return errorCode; + } + } + + // start update timer + return AddFormTimer(formRecord); +} + +/** + * @brief Add form timer. + * @param formRecord Form information. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AddFormTimer(const FormRecord &formRecord) +{ + APP_LOGI("%{public}s start", __func__); + if (formRecord.isEnableUpdate && !formRecord.formTempFlg) { + bool timerRet = false; + if (formRecord.updateDuration > 0) { + timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, + formRecord.updateDuration, formRecord.userId); + } else { + timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, formRecord.updateAtHour, + formRecord.updateAtMin, formRecord.userId); + } + if (!timerRet) { + APP_LOGE("%{public}s fail, add form timer failed", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + APP_LOGI("%{public}s end", __func__); + return ERR_OK; +} + +/** + * @brief Send event notify to form provider. The event notify type include FORM_VISIBLE and FORM_INVISIBLE. + * + * @param providerKey The provider key string which consists of the provider bundle name and ability name. + * @param formIdsByProvider The vector of form Ids which have the same provider. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const std::vector &formIdsByProvider, + const int32_t formVisibleType) +{ + APP_LOGI("%{public}s called.", __func__); + size_t position = providerKey.find(Constants::NAME_DELIMITER); + std::string bundleName = providerKey.substr(0, position); + std::string abilityName = providerKey.substr(position + Constants::NAME_DELIMITER.size()); + sptr formEventNotifyConnection = new FormEventNotifyConnection(formIdsByProvider, + formVisibleType, bundleName, abilityName); + Want connectWant; + connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + + connectWant.SetElementName(bundleName, abilityName); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formEventNotifyConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + + return ERR_OK; +} + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the form. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId, + const FormItemInfo &info, const WantParams &wantParams) +{ + if (formId <= 0) { + APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + sptr formAcquireConnection + = new FormAcquireConnection(formId, info, wantParams); + Want want; + want.SetElementName(info.GetProviderBundleName(), info.GetAbilityName()); + want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} + +/** + * @brief Get bundle info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param packageName Package name. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundleInfo, std::string &packageName) +{ + APP_LOGD("GetBundleMgr start."); + std::string bundleName = want.GetElement().GetBundleName(); + std::string abilityName = want.GetElement().GetAbilityName(); + std::string deviceId = want.GetElement().GetDeviceID(); + std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY); + if (bundleName.empty() || abilityName.empty() || moduleName.empty()) { + APP_LOGE("GetBundleInfo bundleName or abilityName or moduleName is invalid"); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("GetBundleMgr, failed to get IBundleMgr."); + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + } + + if (!iBundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, + bundleInfo, FormUtil::GetCurrentAccountId())) { + APP_LOGE("GetBundleInfo, failed to get bundle info."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + + bool moduleExist = false; + for (const auto &moduleInfo : bundleInfo.moduleNames) { + APP_LOGD("bundleInfo.moduleNames, module name:%{public}s", moduleInfo.c_str()); + if (moduleInfo.compare(moduleName) == 0) { + moduleExist = true; + break; + } + } + if (!moduleExist) { + APP_LOGE("GetBundleInfo no such module, name:%{public}s", moduleName.c_str()); + return ERR_APPEXECFWK_FORM_NO_SUCH_MODULE; + } + + packageName = bundleName + moduleName; + APP_LOGD("GetBundleMgr end."); + return ERR_OK; +} +/** + * @brief Get form info. + * @param want The want of the request. + * @param packageName Package name. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo) +{ + APP_LOGD("GetFormInfo start."); + std::string bundleName = want.GetElement().GetBundleName(); + std::string abilityName = want.GetElement().GetAbilityName(); + std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY); + if (bundleName.empty() || abilityName.empty() || moduleName.empty()) { + APP_LOGE("addForm bundleName or abilityName or moduleName is invalid"); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + std::vector formInfos {}; + ErrCode errCode = FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos); + if (errCode != ERR_OK) { + APP_LOGE("GetFormsInfoByModule, failed to get form config info."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + + std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY); + if (formName.empty()) { + for (const auto &form : formInfos) { + if (form.defaultFlag) { + formInfo = form; + formInfo.moduleName = moduleName; + APP_LOGD("GetFormInfo end."); + return ERR_OK; + } + } + } else { + for (const auto &form : formInfos) { + if (form.name == formName) { + formInfo = form; + formInfo.moduleName = moduleName; + APP_LOGD("GetFormInfo end."); + return ERR_OK; + } + } + } + APP_LOGE("failed to get form info failed."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; +} +/** + * @brief Get form configure info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetFormItemInfo(const AAFwk::Want &want, const BundleInfo &bundleInfo, + const FormInfo &formInfo, FormItemInfo &formItemInfo) +{ + APP_LOGD("GetFormItemInfo start."); + int32_t dimensionId = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, formInfo.defaultDimension); + if (!IsDimensionValid(formInfo, dimensionId)) { + APP_LOGE("addForm, dimension is not valid"); + return ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION; + } + + if (ErrCode ret = CreateFormItemInfo(bundleInfo, formInfo, formItemInfo); ret != ERR_OK) { + return ret; + } + formItemInfo.SetSpecificationId(dimensionId); + formItemInfo.SetTemporaryFlag(want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false)); + + APP_LOGD("GetFormItemInfo end."); + return ERR_OK; +} +/** + * @brief Dimension valid check. + * @param formInfo Form info. + * @param dimensionId Dimension id. + * @return Returns true on success, false on failure. + */ +bool FormMgrAdapter::IsDimensionValid(const FormInfo &formInfo, int dimensionId) const +{ + if (formInfo.supportDimensions.empty()) { + APP_LOGE("Js form, no support dimension."); + return false; + } + + for (size_t i = 0; i < formInfo.supportDimensions.size() && i < Constants::MAX_LAYOUT; i++) { + int supportDimensionId = formInfo.supportDimensions[i]; + if (supportDimensionId == dimensionId) { + return true; + } + } + + APP_LOGE("No matched dimension found."); + return false; +} +/** + * @brief Create form configure info. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param itemInfo Form configure info. + */ +ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, + const FormInfo &formInfo, FormItemInfo &itemInfo) +{ + itemInfo.SetProviderBundleName(bundleInfo.name); + itemInfo.SetVersionCode(bundleInfo.versionCode); + itemInfo.SetVersionName(bundleInfo.versionName); + itemInfo.SetCompatibleVersion(bundleInfo.compatibleVersion); + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("GetFormInfo, failed to get IBundleMgr."); + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + } + std::string hostBundleName {}; + if (!iBundleMgr->GetBundleNameForUid(IPCSkeleton::GetCallingUid(), hostBundleName)) { + APP_LOGE("GetFormsInfoByModule, failed to get form config info."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + itemInfo.SetHostBundleName(hostBundleName); + std::string icon = iBundleMgr->GetAbilityIcon(bundleInfo.name, formInfo.abilityName); + itemInfo.SetIcon(icon); + + itemInfo.SetAbilityName(formInfo.abilityName); + itemInfo.SetModuleName(formInfo.moduleName); // formInfo.moduleName: bundleMagr do not set + itemInfo.SetFormName(formInfo.name); + itemInfo.SetEnableUpdateFlag(formInfo.updateEnabled); + itemInfo.SetUpdateDuration(formInfo.updateDuration); + itemInfo.SetScheduledUpdateTime(formInfo.scheduledUpdateTime); + itemInfo.SetJsComponentName(formInfo.jsComponentName); + itemInfo.SetFormVisibleNotify(formInfo.formVisibleNotify); + itemInfo.SetFormSrc(formInfo.src); + itemInfo.SetFormWindow(formInfo.window); + + for (const auto &abilityInfo : bundleInfo.abilityInfos) { + if (abilityInfo.name == formInfo.abilityName) { + itemInfo.SetAbilityModuleName(abilityInfo.moduleName); + } + } + + APP_LOGI("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size()); + for (const auto &item : bundleInfo.applicationInfo.moduleInfos) { + APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, + item.moduleName.c_str(), item.moduleSourceDir.c_str()); + if (formInfo.moduleName == item.moduleName) { + itemInfo.AddHapSourceDirs(item.moduleSourceDir); + } + itemInfo.AddModuleInfo(item.moduleName, item.moduleSourceDir); + } + return ERR_OK; +} + +/** + * @brief set next refresh time. + * @param formId The id of the form. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + APP_LOGI("%{public}s begin here, formId:%{public}" PRId64 ",nextTime:%{public}" PRId64 "", __func__, formId, nextTime); + if (formId <= 0) { + APP_LOGE("%{public}s form formId or bundleName is invalid", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + + std::string bundleName; + if (!GetBundleName(bundleName)) { + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGE("%{public}s, not found in formrecord.", __func__); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = GetCurrentUserId(callingUid); + bool isSelfFormId = (userId == formRecord.userId) && ((std::find(formRecord.formUserUids.begin(), + formRecord.formUserUids.end(), callingUid) != formRecord.formUserUids.end()) ? true : false); + if (!isSelfFormId) { + APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + // check bundleName + if (bundleName != formRecord.bundleName) { + APP_LOGE("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str()); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + return SetNextRefreshtTimeLocked(matchedFormId, nextTime, userId); +} + +/** + * @brief get bundleName. + * @param bundleName for output. + * @return Returns true on success, others on failure. + */ +bool FormMgrAdapter::GetBundleName(std::string &bundleName) +{ + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s, failed to get IBundleMgr.", __func__); + return false; + } + + int uid = IPCSkeleton::GetCallingUid(); + if (!iBundleMgr->CheckIsSystemAppByUid(uid)) { + APP_LOGE("%{public}s fail, form is not system app. uid:%{public}d", __func__, uid); + return false; + } + + bool result = iBundleMgr->GetBundleNameForUid(uid, bundleName); + if (!result || bundleName.empty()) { + APP_LOGE("%{public}s failed, cannot get bundle name by uid:%{public}d", __func__, uid); + return false; + } + return true; +} + +/** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param nextTime next refresh time. + * @param userId User ID. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::SetNextRefreshtTimeLocked(const int64_t formId, const int64_t nextTime, const int32_t userId) +{ + APP_LOGE("SetNextRefreshtTimeLocked."); + int32_t timerRefreshedCount = FormTimerMgr::GetInstance().GetRefreshCount(formId); + if (timerRefreshedCount >= Constants::LIMIT_COUNT) { + APP_LOGE("%{public}s, already refresh times:%{public}d", __func__, timerRefreshedCount); + FormTimerMgr::GetInstance().MarkRemind(formId); + return ERR_APPEXECFWK_FORM_MAX_REFRESH; + } + + if (!FormTimerMgr::GetInstance().SetNextRefreshTime(formId, nextTime, userId)) { + APP_LOGE("%{public}s failed", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + return ERR_OK; +} + +/** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param bundleName Provider ability bundleName. + * @return Returns true or false. + */ +bool FormMgrAdapter::IsUpdateValid(const int64_t formId, const std::string &bundleName) +{ + if (formId <= 0 || bundleName.empty()) { + return false; + } + return true; +} + +/** + * @brief enable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::EnableUpdateForm(const std::vector formIDs, const sptr &callerToken) +{ + APP_LOGI("enableUpdateForm"); + return HandleUpdateFormFlag(formIDs, callerToken, true); +} + +/** + * @brief disable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DisableUpdateForm(const std::vector formIDs, const sptr &callerToken) +{ + APP_LOGI("disableUpdateForm"); + return HandleUpdateFormFlag(formIDs, callerToken, false); +} + +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgrAdapter::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + if (formId <= 0) { + APP_LOGE("%{public}s form formId or bundleName is invalid", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (callerToken == nullptr) { + APP_LOGE("%{public}s failed, callerToken can not be NULL", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (!want.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + APP_LOGE("%{public}s failed, message info is not exist", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + FormRecord record; + bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record); + if (!bGetRecord) { + APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + FormHostRecord formHostRecord; + bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); + if (!isHostExist) { + APP_LOGE("%{public}s failed, cannot find target client.", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + if (!formHostRecord.Contains(matchedFormId)) { + APP_LOGE("%{public}s failed, form is not self-owned.", __func__); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + APP_LOGI("%{public}s, find target client.", __func__); + return FormProviderMgr::GetInstance().MessageEvent(matchedFormId, record, want); +} + +int FormMgrAdapter::HandleUpdateFormFlag(std::vector formIds, + const sptr &callerToken, bool flag) +{ + APP_LOGI("%{public}s called.", __func__); + if (formIds.empty() || callerToken == nullptr) { + APP_LOGE("%{public}s, invalid param", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + std::vector refreshForms; + int errCode = FormDataMgr::GetInstance().UpdateHostFormFlag(formIds, callerToken, flag, refreshForms); + if (errCode == ERR_OK && refreshForms.size() > 0) { + for (const int64_t id : refreshForms) { + APP_LOGI("%{public}s, formRecord need refresh: %{public}" PRId64 "", __func__, id); + Want want; + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = GetCurrentUserId(callingUid); + want.SetParam(Constants::PARAM_FORM_USER_ID, userId); + FormProviderMgr::GetInstance().RefreshForm(id, want); + } + } + return errCode; +} + +/** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns true on success, false on failure. + */ +bool FormMgrAdapter::IsFormCached(const FormRecord record) +{ + if (record.versionUpgrade) { + return false; + } + return true; +} + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormMgrAdapter::AcquireProviderFormInfo(const int64_t formId, const Want &want, +const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->AcquireProviderFormInfo(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} + +/** + * @brief Notify form provider for delete form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormMgrAdapter::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} + +/** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns forms count to add. + */ +int FormMgrAdapter::BatchAddFormRecords(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + ElementName elementName = want.GetElement(); + std::string bundleName = elementName.GetBundleName(); + std::string abilityName = elementName.GetAbilityName(); + int formCount = want.GetIntParam(Constants::PARAM_FORM_ADD_COUNT, 0); + APP_LOGI("%{public}s, batch add form, bundleName: %{public}s, abilityName: %{public}s, count: %{public}d.", + __func__, + bundleName.c_str(), + abilityName.c_str(), + formCount); + + for (int count = 0; count < formCount; count++) { + // get from comfig info + FormItemInfo formItemInfo; + int32_t errCode = GetFormConfigInfo(want, formItemInfo); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s fail, get form config info failed.", __func__); + return errCode; + } + if (!formItemInfo.IsValidItem()) { + APP_LOGE("%{public}s fail, input param itemInfo is invalid", __func__); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + if (!FormDataMgr::GetInstance().GenerateUdidHash()) { + APP_LOGE("%{public}s fail, generate udid hash failed", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + // generate formId + int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId(); + if (newFormId < 0) { + APP_LOGE("%{public}s fail, generateFormId no invalid formId", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + formItemInfo.SetFormId(newFormId); + // allot form host record + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t currentUserId = GetCurrentUserId(callingUid); + // allot form record + FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid, currentUserId); + APP_LOGI("%{public}s, batch add form, formId:" "%{public}" PRId64 ".", __func__, formRecord.formId); + + APP_LOGI("%{public}s, count: %{public}d", __func__, count + 1); + } + APP_LOGI("%{public}s end.", __func__); + return ERR_OK; +} +/** + * @brief Clear form records for st limit value test. + * @return Returns forms count to delete. + */ +int FormMgrAdapter::ClearFormRecords() +{ + APP_LOGI("%{public}s called.", __func__); + FormDataMgr::GetInstance().ClearFormRecords(); + APP_LOGI("%{public}s end.", __func__); + return ERR_OK; +} +/** + * @brief Create eventMaps for event notify. + * + * @param matchedFormId The Id of the form + * @param formRecord Form storage information + * @param eventMaps eventMaps for event notify + * @return Returns true on success, false on failure. + */ +bool FormMgrAdapter::CreateHandleEventMap(const int64_t matchedFormId, const FormRecord &formRecord, + std::map> &eventMaps) +{ + if (!formRecord.formVisibleNotify) { + APP_LOGW("%{public}s fail, the config item 'formVisibleNotify' is false, formId:%{public}" PRId64 ".", + __func__, matchedFormId); + return false; + } + + std::string providerKey = formRecord.bundleName + Constants::NAME_DELIMITER + formRecord.abilityName; + auto iter = eventMaps.find(providerKey); + if (iter == eventMaps.end()) { + std::vector formEventsByProvider {matchedFormId}; + eventMaps.insert(std::make_pair(providerKey, formEventsByProvider)); + } else { + iter->second.emplace_back(matchedFormId); + } + return true; +} +/** + * @brief Update provider info to host + * + * @param matchedFormId The Id of the form + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param formRecord Form storage information + * @return Returns true on success, false on failure. + */ +bool FormMgrAdapter::UpdateProviderInfoToHost(const int64_t matchedFormId, const sptr &callerToken, + const int32_t formVisibleType, FormRecord &formRecord) +{ + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGW("%{public}s fail, not exist such form, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return false; + } + + FormHostRecord formHostRecord; + bool hasFormHostRecord = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); + if (!(hasFormHostRecord && formHostRecord.Contains(matchedFormId))) { + APP_LOGW("%{public}s fail, form is not belong to self, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return false; + } + + formRecord.formVisibleNotifyState = formVisibleType; + if (!FormDataMgr::GetInstance().UpdateFormRecord(matchedFormId, formRecord)) { + APP_LOGW("%{public}s fail, set formVisibleNotifyState error, formId:%{public}" PRId64 ".", + __func__, matchedFormId); + return false; + } + + // If the form need refrsh flag is true and form visibleType is FORM_VISIBLE, refresh the form host. + if (formRecord.needRefresh && formVisibleType == Constants::FORM_VISIBLE) { + std::string cacheData; + // If the form has business cache, refresh the form host. + if (FormCacheMgr::GetInstance().GetData(matchedFormId, cacheData)) { + formRecord.formProviderInfo.SetFormDataString(cacheData); + formHostRecord.OnUpdate(matchedFormId, formRecord); + } + } + return true; +} +/** + * @brief If the form provider is system app and the config item 'formVisibleNotify' is true, + * notify the form provider that the current form is visible. + * + * @param bundleName BundleName + * @return Returns true if the form provider is system app, false if not. + */ +bool FormMgrAdapter::CheckIsSystemAppByBundleName(const sptr &iBundleMgr, const std::string &bundleName) +{ + BundleInfo bundleInfo; + if (iBundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, + bundleInfo, FormUtil::GetCurrentAccountId())) { + APP_LOGD("%{public}s, get bundle uid success", __func__); + if (!iBundleMgr->CheckIsSystemAppByUid(bundleInfo.uid)) { + APP_LOGW("%{public}s fail, form provider is not system app, bundleName: %{public}s", + __func__, bundleName.c_str()); + return false; + } + } else { + APP_LOGW("%{public}s fail, can not get bundleInfo's uid", __func__); + return false; + } + + return true; +} + +/** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DistributedDataAddForm(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + FormDBInfo formDBInfo; + ElementName elementName = want.GetElement(); + formDBInfo.formId = want.GetIntParam(Constants::PARAM_FORM_ADD_COUNT, 0); + formDBInfo.formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY); + formDBInfo.bundleName = elementName.GetBundleName(); + formDBInfo.moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY); + formDBInfo.abilityName = elementName.GetAbilityName(); + formDBInfo.formUserUids.push_back(HUNDRED); + return FormDbCache::GetInstance().SaveFormInfo(formDBInfo); +} + +/** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DistributedDataDeleteForm(const std::string &formId) +{ + return FormDbCache::GetInstance().DeleteFormInfo(std::stoll(formId)); +} +/** + * @brief Get current user ID. + * @param callingUid calling Uid. + * @return Returns user ID. + */ +int32_t FormMgrAdapter::GetCurrentUserId(const int callingUid) +{ + // get current userId + int32_t userId = callingUid / UID_CALLINGUID_TRANSFORM_DIVISOR; + return userId; +} +/** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::GetAllFormsInfo(std::vector &formInfos) +{ + return FormInfoMgr::GetInstance().GetAllFormsInfo(formInfos); +} + +/** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) +{ + return FormInfoMgr::GetInstance().GetFormsInfoByBundle(bundleName, formInfos); +} + +/** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, + std::vector &formInfos) +{ + return FormInfoMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_mgr_service.cpp b/services/formmgr/src/form_mgr_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7eff4a62a66e85c7ae3767620e5c01cd9d6045fb --- /dev/null +++ b/services/formmgr/src/form_mgr_service.cpp @@ -0,0 +1,478 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_mgr_service.h" + +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_info_mgr.h" +#include "form_mgr_adapter.h" +#include "form_task_mgr.h" +#include "form_timer_mgr.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std::chrono; +using PermissionKit = OHOS::Security::Permission::PermissionKit; +using PermissionState = OHOS::Security::Permission::PermissionState; + +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +const std::string NAME_FORM_MGR_SERVICE = "FormMgrService"; + +FormMgrService::FormMgrService() + : SystemAbility(FORM_MGR_SERVICE_ID, true), + state_(ServiceRunningState::STATE_NOT_START), + runner_(nullptr), + handler_(nullptr) +{ +} + +FormMgrService::~FormMgrService() +{ + EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_); + formSysEventReceiver_ = nullptr; +} + +bool FormMgrService::IsReady() const +{ + if (state_ != ServiceRunningState::STATE_RUNNING) { + return false; + } + if (!handler_) { + APP_LOGE("%{public}s fail, handler is null", __func__); + return false; + } + + return true; +} + +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::AddForm(const int64_t formId, const Want &want, + const sptr &callerToken, FormJsInfo &formInfo) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, add form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + return FormMgrAdapter::GetInstance().AddForm(formId, want, callerToken, formInfo); +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, delete form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken); +} + +/** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, release form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return FormMgrAdapter::GetInstance().ReleaseForm(formId, callerToken, delCache); +} + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formBindingData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::UpdateForm(const int64_t formId, + const std::string &bundleName, const FormProviderData &formBindingData) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, update form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + return FormMgrAdapter::GetInstance().UpdateForm(formId, bundleName, formBindingData); +} + +/** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, request form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return FormMgrAdapter::GetInstance().RequestForm(formId, callerToken, want); +} + +/** + * @brief set next refresh time. + * @param formId The id of the form. + * @param bundleManager the bundle manager ipc object. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + APP_LOGI("%{public}s called.", __func__); + + return FormMgrAdapter::GetInstance().SetNextRefreshTime(formId, nextTime); +} + + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::NotifyWhetherVisibleForms(const std::vector &formIds, + const sptr &callerToken, const int32_t formVisibleType) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, event notify visible permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return FormMgrAdapter::GetInstance().NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); +} + +/** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, cast temp form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return FormMgrAdapter::GetInstance().CastTempForm(formId, callerToken); +} + +/** + * @brief lifecycle update. + * @param formIds formIds of hostclient. + * @param callerToken Caller ability token. + * @param updateType update type,enable or disable. + * @return Returns true on success, false on failure. + */ +int FormMgrService::LifecycleUpdate(const std::vector &formIds, + const sptr &callerToken, const int32_t updateType) +{ + APP_LOGI("lifecycleUpdate."); + + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, delete form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + if (updateType == ENABLE_FORM_UPDATE) { + return FormMgrAdapter::GetInstance().EnableUpdateForm(formIds, callerToken); + } else { + return FormMgrAdapter::GetInstance().DisableUpdateForm(formIds, callerToken); + } +} +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DumpStorageFormInfos(std::string &formInfos) +{ + return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) +{ + return FormMgrAdapter::GetInstance().DumpFormInfoByBundleName(bundleName, formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) +{ + return FormMgrAdapter::GetInstance().DumpFormInfoByFormId(formId, formInfo); +} +/** + * @brief Dump form timer by form id. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTimingService) +{ + return FormMgrAdapter::GetInstance().DumpFormTimerByFormId(formId, isTimingService); +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, request form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + return FormMgrAdapter::GetInstance().MessageEvent(formId, want, callerToken); +} + +/** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns forms count to add. + */ +int FormMgrService::BatchAddFormRecords(const Want &want) +{ + return FormMgrAdapter::GetInstance().BatchAddFormRecords(want); +} +/** + * @brief Clear form records for st limit value test. + * @return Returns forms count to delete. + */ +int FormMgrService::ClearFormRecords() +{ + return FormMgrAdapter::GetInstance().ClearFormRecords(); +} +/** + * @brief Start envent for the form manager service. + */ +void FormMgrService::OnStart() +{ + if (state_ == ServiceRunningState::STATE_RUNNING) { + APP_LOGW("%{public}s fail, Failed to start service since it's already running", __func__); + return; + } + + APP_LOGI("Form Mgr Service start..."); + ErrCode errCode = Init(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s fail, Failed to init, errCode: %{public}08x", __func__, errCode); + return; + } + + state_ = ServiceRunningState::STATE_RUNNING; + + APP_LOGI("Form Mgr Service start success."); +} +/** + * @brief Stop envent for the form manager service. + */ +void FormMgrService::OnStop() +{ + APP_LOGI("stop service"); + + state_ = ServiceRunningState::STATE_NOT_START; + + if (handler_) { + handler_.reset(); + } + + if (runner_) { + runner_.reset(); + } +} +/** + * @brief initialization of form manager service. + */ +ErrCode FormMgrService::Init() +{ + runner_ = EventRunner::Create(NAME_FORM_MGR_SERVICE); + if (!runner_) { + APP_LOGE("%{public}s fail, Failed to init due to create runner error", __func__); + return ERR_INVALID_OPERATION; + } + handler_ = std::make_shared(runner_); + if (!handler_) { + APP_LOGE("%{public}s fail, Failed to init due to create handler error", __func__); + return ERR_INVALID_OPERATION; + } + FormTaskMgr::GetInstance().SetEventHandler(handler_); + FormAmsHelper::GetInstance().SetEventHandler(handler_); + /* Publish service maybe failed, so we need call this function at the last, + * so it can't affect the TDD test program */ + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + APP_LOGE("%{public}s fail, FormMgrService::Init Publish failed!", __func__); + return ERR_INVALID_OPERATION; + } + + if (formSysEventReceiver_ == nullptr) { + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_UID_REMOVED); + // init TimerReceiver + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + formSysEventReceiver_ = std::make_shared(subscribeInfo); + EventFwk::CommonEventManager::SubscribeCommonEvent(formSysEventReceiver_); + } + FormDbCache::GetInstance().Start(); + FormInfoMgr::GetInstance().Start(); + + APP_LOGI("init success"); + return ERR_OK; +} +/** + * @brief Permission check by callingUid. + * @param formId the id of the form. + * @return Returns true on success, false on failure. + */ +bool FormMgrService::CheckFormPermission() +{ + return true; +} + +bool FormMgrService::CheckFormPermission(const std::string &bundleName) const +{ + if (bundleName.empty()) { + APP_LOGE("%{public}s fail, bundleName can not be empty", __func__); + return false; + } + int result = PermissionKit::VerifyPermission(bundleName, Constants::PERMISSION_REQUIRE_FORM, 0); + if (result != PermissionState::PERMISSION_GRANTED) { + APP_LOGW("permission = %{public}s, bundleName = %{public}s, result = %{public}d", + Constants::PERMISSION_REQUIRE_FORM.c_str(), bundleName.c_str(), result); + } + return result == PermissionState::PERMISSION_GRANTED; +} + +/** + * @brief Add forms to storage for st . + * @param Want The Want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DistributedDataAddForm(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + return FormMgrAdapter::GetInstance().DistributedDataAddForm(want); +} + +/** + * @brief Delete form form storage for st. + * @param formId The formId of the form to delete. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DistributedDataDeleteForm(const std::string &formId) +{ + APP_LOGI("%{public}s called.", __func__); + return FormMgrAdapter::GetInstance().DistributedDataDeleteForm(formId); +} + +/** + * @brief Get All FormsInfo. + * @param formInfos Return the forms' information of all forms provided. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::GetAllFormsInfo(std::vector &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + return FormMgrAdapter::GetInstance().GetAllFormsInfo(formInfos); +} + +/** + * @brief Get forms info by bundle name . + * @param bundleName Application name. + * @param formInfos Return the forms' information of the specify application name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + return FormMgrAdapter::GetInstance().GetFormsInfoByApp(bundleName, formInfos); +} + +/** + * @brief Get forms info by bundle name and module name. + * @param bundleName bundle name. + * @param moduleName Module name of hap. + * @param formInfos Return the forms' information of the specify bundle name and module name. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, + std::vector &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + return FormMgrAdapter::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_msg_event_connection.cpp b/services/formmgr/src/form_msg_event_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e975c26311ccdbff1035e3e4cd4a23dc313b03bf --- /dev/null +++ b/services/formmgr/src/form_msg_event_connection.cpp @@ -0,0 +1,67 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_msg_event_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormMsgEventConnection::FormMsgEventConnection(const int64_t formId, const Want& want, + const std::string &bundleName, const std::string &abilityName) + :formId_(formId), + want_(want) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormMsgEventConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + Want eventWant = Want(want_); + eventWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostFormEventTask(formId_, message, eventWant, remoteObject); + } else { + APP_LOGE("%{public}s error, message info is not exist", __func__); + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_provider_mgr.cpp b/services/formmgr/src/form_provider_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd5655852c6209e4dc0358d3c788e7345d8b2662 --- /dev/null +++ b/services/formmgr/src/form_provider_mgr.cpp @@ -0,0 +1,395 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ams_helper.h" +#include "form_batch_delete_connection.h" +#include "form_cache_mgr.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_delete_connection.h" +#include "form_msg_event_connection.h" +#include "form_provider_mgr.h" +#include "form_record.h" +#include "form_refresh_connection.h" +#include "form_timer_mgr.h" +#include "power_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +FormProviderMgr::FormProviderMgr(){} +FormProviderMgr::~FormProviderMgr(){} +/** + * @brief handle for acquire back from ams. + * @param formId The id of the form. + * @param formProviderInfo provider form info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::AcquireForm(const int64_t formId, const FormProviderInfo &formProviderInfo) +{ + APP_LOGD("%{public}s start, formId:%{public}" PRId64 "", __func__, formId); + + if (formId <= 0) { + APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + FormRecord formRecord; + bool isGetFormRecord = FormDataMgr::GetInstance().GetFormRecord(formId, formRecord); + if (!isGetFormRecord) { + APP_LOGE("%{public}s fail, not exist such form, formId:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + FormHostRecord clientHost; + bool isGetFormHostRecord = FormDataMgr::GetInstance().GetFormHostRecord(formId, clientHost); + if (!isGetFormHostRecord) { + APP_LOGE("%{public}s fail, clientHost is null", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + if (formRecord.isInited) { + if (IsFormCached(formRecord)) { + if (clientHost.Contains(formId)) { + formRecord.formProviderInfo = formProviderInfo; + clientHost.OnAcquire(formId, formRecord); + } + } else { + Want want; + RefreshForm(formId, want); + } + return ERR_OK; + } + formRecord.isInited = true; + formRecord.needRefresh = false; + FormDataMgr::GetInstance().SetFormCacheInited(formId, true); + + if (clientHost.Contains(formId)) { + formRecord.formProviderInfo = formProviderInfo; + clientHost.OnAcquire(formId, formRecord); + } + + // we do not cache when data size is over 1k + std::string jsonData = formProviderInfo.GetFormDataString(); // get json data + APP_LOGD("%{public}s , jsonData is %{public}s.", __func__, jsonData.c_str()); + if (jsonData.size() <= Constants::MAX_FORM_DATA_SIZE) { + APP_LOGW("%{public}s, acquire js card, cache the card", __func__); + FormCacheMgr::GetInstance().AddData(formId, formProviderInfo.GetFormDataString()); + } + return ERR_OK; +} + +/** + * @brief Refresh form. + * + * @param formId The form id. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::RefreshForm(const int64_t formId, const Want &want) +{ + APP_LOGI("%{public}s called, formId:%{public}" PRId64 ".", __func__, formId); + FormRecord record; + bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record); + if (!bGetRecord) { + APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + // get current userId + int32_t currentUserId = want.GetIntParam(Constants::PARAM_FORM_USER_ID, DEFAULT_USER_ID); + if (currentUserId != record.userId) { + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + APP_LOGE("%{public}s, not current user, just set refresh flag, userId:%{public}d", __func__, record.userId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + bool isTimerRefresh = want.GetBoolParam(Constants::KEY_IS_TIMER, false); + Want newWant(want); + newWant.RemoveParam(Constants::KEY_IS_TIMER); + + if (isTimerRefresh) { + FormDataMgr::GetInstance().SetCountTimerRefresh(formId, true); + } + + bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); + if (!screenOnFlag) { + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + APP_LOGE("%{public}s fail, screen off, set refresh flag, do not refresh now", __func__); + return ERR_OK; + } + + bool needRefresh = FormDataMgr::GetInstance().IsEnableRefresh(formId); + if (!needRefresh) { + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + APP_LOGE("%{public}s fail, no one needReresh, set refresh flag, do not refresh now", __func__); + return ERR_OK; + } + + FormRecord refreshRecord = GetFormAbilityInfo(record); + refreshRecord.isInited = record.isInited; + refreshRecord.versionUpgrade = record.versionUpgrade; + refreshRecord.isCountTimerRefresh = isTimerRefresh; + return ConnectAmsForRefresh(formId, refreshRecord, newWant, isTimerRefresh); +} + +/** + * @brief Connect ams for refresh form + * + * @param formId The form id. + * @param record Form data. + * @param want The want of the form. + * @param isTimerRefresh The flag of timer refresh. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::ConnectAmsForRefresh(const int64_t formId, + const FormRecord &record, const Want &want, const bool isTimerRefresh) +{ + APP_LOGD("%{public}s called, bundleName:%{public}s, abilityName:%{public}s.", + __func__, record.bundleName.c_str(), record.abilityName.c_str()); + + sptr formRefreshConnection = new FormRefreshConnection(formId, want, + record.bundleName, record.abilityName); + Want connectWant; + connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + connectWant.SetElementName(record.bundleName, record.abilityName); + + if (isTimerRefresh) { + if (!FormTimerMgr::GetInstance().IsLimiterEnableRefresh(formId)) { + APP_LOGE("%{public}s, timer refresh, already limit.", __func__); + return ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL; + } + } + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formRefreshConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + + if (record.isCountTimerRefresh) { + IncreaseTimerRefreshCount(formId); + } + + return ERR_OK; +} + +/** + * @brief Notify provider form delete. + * @param formId The form id. + * @param record Form information. + * @return Function result and has other host flag. + */ +ErrCode FormProviderMgr::NotifyProviderFormDelete(const int64_t formId, const FormRecord &formRecord) +{ + if (formRecord.abilityName.empty()) { + APP_LOGE("%{public}s, formRecord.abilityName is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (formRecord.bundleName.empty()) { + APP_LOGE("%{public}s, formRecord.bundleName is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + APP_LOGD("%{public}s, connectAbility,bundleName:%{public}s, abilityName:%{public}s", + __func__, formRecord.bundleName.c_str(), formRecord.abilityName.c_str()); + sptr formDeleteConnection = new FormDeleteConnection(formId, + formRecord.bundleName, formRecord.abilityName); + Want want; + want.SetElementName(formRecord.bundleName, formRecord.abilityName); + want.SetFlags(Want::FLAG_ABILITY_FORM_ENABLED); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} + +/** + * @brief Notify provider forms batch delete. + * @param bundleName BundleName. + * @param bundleName AbilityName. + * @param formIds form id list. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundleName, + const std::string &abilityName, const std::set &formIds) +{ + if (abilityName.empty()) { + APP_LOGE("%{public}s error, abilityName is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (bundleName.empty()) { + APP_LOGE("%{public}s error, bundleName is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + APP_LOGD("%{public}s, bundleName:%{public}s, abilityName:%{public}s", + __func__, bundleName.c_str(), abilityName.c_str()); + sptr batchDeleteConnection = new FormBatchDeleteConnection(formIds, bundleName, abilityName); + Want want; + want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + want.SetElementName(bundleName, abilityName); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, batchDeleteConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} +/** + * @brief Update form. + * @param formId The form's id. + + * @param formProviderData form provider data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::UpdateForm(const int64_t formId, const FormProviderInfo &formProviderInfo) +{ + // check exist and get the formRecord + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { + APP_LOGE("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + return UpdateForm(formId, formRecord, formProviderInfo.GetFormData()); +} +/** + * handle for update form event from provider. + * + * @param formId The id of the form. + * @param formRecord The form's record. + * @param formProviderData provider form info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::UpdateForm(const int64_t formId, + FormRecord &formRecord, const FormProviderData &formProviderData) +{ + APP_LOGI("%{public}s start", __func__); + + if (formRecord.versionUpgrade) { + formRecord.formProviderInfo.SetFormData(formProviderData); + formRecord.formProviderInfo.SetUpgradeFlg(true); + } else { + nlohmann::json addJsonData = formProviderData.GetData(); + formRecord.formProviderInfo.MergeData(addJsonData); + } + + // formRecord init + formRecord.isInited = true; + formRecord.needRefresh = false; + FormDataMgr::GetInstance().SetFormCacheInited(formId, true); + + // update form for host clients + FormDataMgr::GetInstance().UpdateHostNeedRefresh(formId, true); + + bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); + if (screenOnFlag) { + if (FormDataMgr::GetInstance().UpdateHostForm(formId, formRecord)) { + FormDataMgr::GetInstance().SetVersionUpgrade(formId, false); + formRecord.formProviderInfo.SetUpgradeFlg(false); + } + } + // update formProviderInfo to formRecord + FormDataMgr::GetInstance().UpdateFormProviderInfo(formId, formRecord.formProviderInfo); + // check if cache data size is less than 1k or not + std::string jsonData = formRecord.formProviderInfo.GetFormDataString(); // get json data + APP_LOGD("%{public}s screenOn:%{public}d jsonData:%{public}s.", __func__, screenOnFlag, jsonData.c_str()); + if (jsonData.size() <= Constants::MAX_FORM_DATA_SIZE) { + APP_LOGI("%{public}s, updateJsForm, data is less than 1k, cache data.", __func__); + FormCacheMgr::GetInstance().AddData(formId, jsonData); + } else { + FormCacheMgr::GetInstance().DeleteData(formId); + } + + // the update form is successfully + return ERR_OK; +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param record Form record. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ +int FormProviderMgr::MessageEvent(const int64_t formId, const FormRecord &record, const Want &want) +{ + APP_LOGI("%{public}s called, formId:%{public}" PRId64 ".", __func__, formId); + + bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); + if (!screenOnFlag) { + APP_LOGW("%{public}s fail, screen off now", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + sptr formMsgEventConnection = new FormMsgEventConnection(formId, want, + record.bundleName, record.abilityName); + Want connectWant; + connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + connectWant.SetElementName(record.bundleName, record.abilityName); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formMsgEventConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + + return ERR_OK; +} + +/** + * @brief Increase the timer refresh count. + * + * @param formId The form id. + */ +void FormProviderMgr::IncreaseTimerRefreshCount(const int64_t formId) +{ + FormRecord record; + if (FormDataMgr::GetInstance().GetFormRecord(formId, record)) { + APP_LOGE("%{public}s failed, not exist such form:%{public}" PRId64 ".", __func__, formId); + return; + } + + if (record.isCountTimerRefresh) { + FormDataMgr::GetInstance().SetCountTimerRefresh(formId, false); + FormTimerMgr::GetInstance().IncreaseRefreshCount(formId); + } +} +FormRecord FormProviderMgr::GetFormAbilityInfo(const FormRecord &record) const +{ + FormRecord newRecord; + newRecord.bundleName = record.bundleName; + newRecord.abilityName = record.abilityName; + + return newRecord; +} + +bool FormProviderMgr::IsFormCached(const FormRecord &record) +{ + if (record.versionUpgrade) { + return false; + } + return FormCacheMgr::GetInstance().IsExist(record.formId); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_refresh_connection.cpp b/services/formmgr/src/form_refresh_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..598857f3da2f86352ed631d351d865f57ce5fd6b --- /dev/null +++ b/services/formmgr/src/form_refresh_connection.cpp @@ -0,0 +1,75 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_refresh_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormRefreshConnection::FormRefreshConnection(const int64_t formId, const Want& want, + const std::string &bundleName, const std::string &abilityName) + :formId_(formId), + want_(want) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormRefreshConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + Want msgWant = Want(want_); + msgWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostFormEventTask(formId_, message, msgWant, remoteObject); + } else if (want_.HasParameter(Constants::RECREATE_FORM_KEY)) { + Want cloneWant = Want(want_); + cloneWant.RemoveParam(Constants::RECREATE_FORM_KEY); + cloneWant.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + cloneWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, cloneWant, remoteObject); + } else { + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostRefreshTask(formId_, want, remoteObject); + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_refresh_limiter.cpp b/services/formmgr/src/form_refresh_limiter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0cca52ee9e2bf1ee5395e10b8654654c127f1e0b --- /dev/null +++ b/services/formmgr/src/form_refresh_limiter.cpp @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "form_constants.h" +#include "form_refresh_limiter.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Add form limit info by formId. + * @param formId The id of the form. + * @return Returns true on success, false on failure. + */ +bool FormRefreshLimiter::AddItem(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info == limiterMap_.end()) { + LimitInfo limitInfo; + std::pair::iterator, bool> retVal = + limiterMap_.emplace(formId, limitInfo); + APP_LOGI("%{public}s end", __func__); + return retVal.second; + } else { + APP_LOGI("%{public}s end, already exist", __func__); + return true; + } +} +/** + * @brief Delete form limit info by formId. + * @param formId The form id. + */ +void FormRefreshLimiter::DeleteItem(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + limiterMap_.erase(formId); + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Reset limit info. + */ +void FormRefreshLimiter::ResetLimit() +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + for (auto &infoPair : limiterMap_) { + infoPair.second.refreshCount = 0; + infoPair.second.isReported = false; + infoPair.second.remindFlag = false; + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Refresh enable or not. + * @param formId The form id. + * @return Returns ERR_OK on success, others on failure. + */ +bool FormRefreshLimiter::IsEnableRefresh(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + bool isEnable = false; + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + if (info->second.refreshCount < Constants::LIMIT_COUNT) { + isEnable = true; + } + + if (info->second.refreshCount == Constants::LIMIT_COUNT && !info->second.isReported) { + info->second.isReported = true; + APP_LOGI("report refresh to 50 count,formId:%{public}" PRId64 "", formId); + } + } + APP_LOGI("%{public}s end", __func__); + return isEnable; +} +/** + * @brief Get refresh count. + * @param formId The form id. + * @return refresh count. + */ +int FormRefreshLimiter::GetRefreshCount(const int64_t formId) const +{ + APP_LOGI("%{public}s start", __func__); + // -1 means not added or already removed. + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + return info->second.refreshCount; + } + + APP_LOGI("%{public}s end", __func__); + return -1; +} +/** + * @brief Increase refresh count. + * @param formId The form id. + */ +void FormRefreshLimiter::Increase(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + info->second.refreshCount++; + APP_LOGI("increase,formId:%{public}" PRId64 ", count:%{public}d", formId, info->second.refreshCount); + if (info->second.refreshCount == Constants::LIMIT_COUNT && !info->second.isReported) { + info->second.isReported = true; + APP_LOGI("report refresh to 50 count,formId:%{public}" PRId64 "", formId); + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Mark remind flag. + * @param formId The form id. + */ +void FormRefreshLimiter::MarkRemind(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + if (info->second.refreshCount >= Constants::LIMIT_COUNT) { + info->second.remindFlag = true; + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Get remind list. + * @return remind list. + */ +std::vector FormRefreshLimiter::GetRemindList() const +{ + APP_LOGI("%{public}s start", __func__); + std::vector result; + std::lock_guard lock(limiterMutex_); + for (auto &infoPair : limiterMap_) { + if (infoPair.second.remindFlag) { + result.emplace_back(infoPair.first); + } + } + APP_LOGI("%{public}s end", __func__); + return result; +} +/** + * @brief Get remind list and reset limit. + * @return remind list. + */ +std::vector FormRefreshLimiter::GetRemindListAndResetLimit() +{ + APP_LOGI("%{public}s start", __func__); + std::vector result; + std::lock_guard lock(limiterMutex_); + for (auto &infoPair : limiterMap_) { + if (infoPair.second.remindFlag) { + result.emplace_back(infoPair.first); + } + + infoPair.second.refreshCount = 0; + infoPair.second.isReported = false; + infoPair.second.remindFlag = false; + } + APP_LOGI("%{public}s end", __func__); + return result; +} +/** + * @brief Get item count. + * @return Item count. + */ +int FormRefreshLimiter::GetItemCount() const +{ + return limiterMap_.size(); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_storage_mgr.cpp b/services/formmgr/src/form_storage_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b5441bc05632156f66776e692dfefb427a4ee99 --- /dev/null +++ b/services/formmgr/src/form_storage_mgr.cpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_storage_mgr.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "form_storage_mgr.h" +#include "kvstore_death_recipient_callback.h" +#include "securec.h" +#include "string_ex.h" +#include "types.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t MAX_TIMES = 600; // 1min +const int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms +} // namespace + +FormStorageMgr::FormStorageMgr() +{ + APP_LOGI("instance:%{private}p is created", this); + TryTwice([this] { return GetKvStore(); }); + RegisterKvStoreDeathListener(); +} + +FormStorageMgr::~FormStorageMgr() +{ + APP_LOGI("instance:%{private}p is destroyed", this); + dataManager_.CloseKvStore(appId_, kvStorePtr_); +} + +void FormStorageMgr::SaveEntries( + const std::vector &allEntries, std::vector &innerFormInfos) +{ + for (const auto &item : allEntries) { + std::string formId; + InnerFormInfo innerFormInfo; + + nlohmann::json jsonObject = nlohmann::json::parse(item.value.ToString(), nullptr, false); + if (jsonObject.is_discarded()) { + APP_LOGE("error key: %{private}s", item.key.ToString().c_str()); + // it's an bad json, delete it + { + std::lock_guard lock(kvStorePtrMutex_); + kvStorePtr_->Delete(item.key); + } + continue; + } + if (innerFormInfo.FromJson(jsonObject) != true) { + APP_LOGE("error key: %{private}s", item.key.ToString().c_str()); + // it's an error value, delete it + { + std::lock_guard lock(kvStorePtrMutex_); + kvStorePtr_->Delete(item.key); + } + continue; + } + + if (std::find(innerFormInfos.begin(), innerFormInfos.end(), innerFormInfo) == innerFormInfos.end()) { + APP_LOGD("emplace FormInfos: %{public}s", formId.c_str()); + std::map allDevicesInfos; + allDevicesInfos.emplace(formId, innerFormInfo); + innerFormInfos.emplace_back(innerFormInfo); + } + } + APP_LOGD("SaveEntries end"); +} + +/** + * @brief Load all form data from DB to innerFormInfos. + * @param innerFormInfos Storage all form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) +{ + APP_LOGI("%{public}s called.", __func__); + bool ret = ERR_OK; + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + DistributedKv::Status status; + std::vector allEntries; + TryTwice([this, &status, &allEntries] { + status = GetEntries(allEntries); + return status; + }); + + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("get entries error: %{public}d", status); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } else { + SaveEntries(allEntries, innerFormInfos); + } + + APP_LOGI("%{public}s, readdir over", __func__); + return ret; +} + +/** + * @brief Get form data from DB to innerFormInfo with formId. + * @param innerFormInfo Storage form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) +{ + ErrCode ret = ERR_OK; + APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + DistributedKv::Status status = DistributedKv::Status::ERROR; + std::vector allEntries; + DistributedKv::Key key(formId); + if (kvStorePtr_) { + // sync call GetEntries, the callback will be trigger at once + status = kvStorePtr_->GetEntries(key, allEntries); + } + + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("get entries error: %{public}d", status); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } else { + if (allEntries.empty()) { + APP_LOGE("%{public}s not match any FormInfo", formId.c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } else { + nlohmann::json jsonObject = nlohmann::json::parse(allEntries.front().value.ToString(), nullptr, false); + if (jsonObject.is_discarded()) { + APP_LOGE("error key: %{private}s", allEntries.front().key.ToString().c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if (innerFormInfo.FromJson(jsonObject) != true) { + APP_LOGE("error key: %{private}s", allEntries.front().key.ToString().c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + } + + return ret; +} + +/** + * @brief Save or update the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be save. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::SaveStorageFormInfo(const InnerFormInfo &innerFormInfo) +{ + APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); + ErrCode ret = ERR_OK; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + DistributedKv::Key key(formId); + DistributedKv::Value value(innerFormInfo.ToString()); + DistributedKv::Status status; + { + std::lock_guard lock(kvStorePtrMutex_); + status = kvStorePtr_->Put(key, value); + if (status == DistributedKv::Status::IPC_ERROR) { + status = kvStorePtr_->Put(key, value); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + } + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("put innerFormInfo to kvStore error: %{public}d", status); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + return ret; +} + +/** + * @brief Modify the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo) +{ + APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); + + ErrCode ret = ERR_OK; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + ret = DeleteStorageFormInfo(formId); + if (ret == ERR_OK) { + SaveStorageFormInfo(innerFormInfo); + } + + return ret; +} + +/** + * @brief Delete the form data in DB. + * @param formId The form data Id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::DeleteStorageFormInfo(const std::string &formId) +{ + APP_LOGI("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + DistributedKv::Key key(formId); + DistributedKv::Status status; + + { + std::lock_guard lock(kvStorePtrMutex_); + status = kvStorePtr_->Delete(key); + if (status == DistributedKv::Status::IPC_ERROR) { + status = kvStorePtr_->Delete(key); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + } + + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("delete key error: %{public}d", status); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } else { + APP_LOGE("delete value to kvStore success"); + } + + return ERR_OK; +} + +void FormStorageMgr::RegisterKvStoreDeathListener() +{ + APP_LOGI("register kvStore death listener"); + std::shared_ptr callback = + std::make_shared(); + dataManager_.RegisterKvStoreServiceDeathRecipient(callback); +} + +bool FormStorageMgr::CheckKvStore() +{ + if (kvStorePtr_ != nullptr) { + return true; + } + int32_t tryTimes = MAX_TIMES; + while (tryTimes > 0) { + DistributedKv::Status status = GetKvStore(); + if (status == DistributedKv::Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + APP_LOGD("CheckKvStore, Times: %{public}d", tryTimes); + usleep(SLEEP_INTERVAL); + tryTimes--; + } + return kvStorePtr_ != nullptr; +} + +DistributedKv::Status FormStorageMgr::GetKvStore() +{ + DistributedKv::Options options = { + .createIfMissing = true, + .encrypt = false, + .autoSync = true, + .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION + }; + + DistributedKv::Status status = dataManager_.GetSingleKvStore(options, appId_, storeId_, kvStorePtr_); + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("return error: %{public}d", status); + } else { + APP_LOGI("get kvStore success"); + } + return status; +} + +DistributedKv::Status FormStorageMgr::GetEntries(std::vector &allEntries) +{ + DistributedKv::Status status = DistributedKv::Status::ERROR; + // if prefix is empty, get all entries. + DistributedKv::Key key(""); + if (kvStorePtr_) { + // sync call GetEntries, the callback will be trigger at once + status = kvStorePtr_->GetEntries(key, allEntries); + } + APP_LOGI("get all entries status: %{public}d", status); + return status; +} + +void FormStorageMgr::TryTwice(const std::function &func) +{ + DistributedKv::Status status = func(); + if (status == DistributedKv::Status::IPC_ERROR) { + status = func(); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } +} + +bool FormStorageMgr::ResetKvStore() +{ + std::lock_guard lock(kvStorePtrMutex_); + kvStorePtr_ = nullptr; + DistributedKv::Status status = GetKvStore(); + if (status == DistributedKv::Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + APP_LOGW("failed"); + return false; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_supply_callback.cpp b/services/formmgr/src/form_supply_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a57025167cac79fbf5678791e94f7646153cf8db --- /dev/null +++ b/services/formmgr/src/form_supply_callback.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ams_helper.h" +#include "form_constants.h" +#include "form_provider_mgr.h" +#include "form_supply_callback.h" +#include "form_util.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +sptr FormSupplyCallback::instance_ = nullptr; +std::mutex FormSupplyCallback::mutex_; + +sptr FormSupplyCallback::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (instance_ == nullptr) { + instance_ = new FormSupplyCallback(); + } + } + return instance_; +} + +/** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnAcquire(const FormProviderInfo &formProviderInfo, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + int errCode = want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + RemoveConnection(connectId); + APP_LOGE("%{public}s error, errCode: %{public}d", __func__, errCode); + return errCode; + } + + std::string strFormId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + if (strFormId.empty()) { + APP_LOGE("%{public}s error, formId is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + int64_t formId = std::stoll(strFormId); + int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); + APP_LOGD("%{public}s come: %{public}" PRId64 ", %{public}ld, %{public}d", __func__, + formId, connectId, type); + RemoveConnection(connectId); + + switch (type) { + case Constants::ACQUIRE_TYPE_CREATE_FORM: + return FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo); + case Constants::ACQUIRE_TYPE_RECREATE_FORM: + return FormProviderMgr::GetInstance().UpdateForm(formId, formProviderInfo); + default: + APP_LOGW("%{public}s warning, onAcquired type: %{public}d", __func__, type); + } + APP_LOGI("%{public}s end.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; +} + +/** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnEventHandle(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + std::string supplyInfo = want.GetStringParam(Constants::FORM_SUPPLY_INFO); + APP_LOGD("%{public}s come: %{public}ld, %{public}s", __func__, connectId, supplyInfo.c_str()); + RemoveConnection(connectId); + APP_LOGI("%{public}s end.", __func__); + return ERR_OK; +} +/** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ +void FormSupplyCallback::AddConnection(sptr connection) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock_l(conMutex_); + long connectKey = FormUtil::GetCurrentMillisecond(); + while (connections_.find(connectKey) != connections_.end()) { + connectKey++; + } + connection->SetConnectId(connectKey); + connections_.emplace(connectKey, connection); + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ +void FormSupplyCallback::RemoveConnection(long connectId) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock_l(conMutex_); + auto conIterator = connections_.find(connectId); + if (conIterator != connections_.end()) { + sptr connection = conIterator->second; + if (connection != nullptr) { + if (CanDisConnect(connection)) { + FormAmsHelper::GetInstance().DisConnectServiceAbility(connection); + APP_LOGI("%{public}s end, disconnect service ability", __func__); + } else { + FormAmsHelper::GetInstance().DisConnectServiceAbilityDelay(connection); + APP_LOGI("%{public}s end, disconnect service ability delay", __func__); + } + } + connections_.erase(connectId); + } + APP_LOGI("%{public}s end.", __func__); +} +/** + * @brief check if disconnect ability or not. + * @param connection The ability connection. + */ +bool FormSupplyCallback::CanDisConnect(sptr &connection) +{ + APP_LOGI("%{public}s called.", __func__); + int count = 0; + for(auto &conn : connections_) { + if (connection->GetProviderKey() == conn.second->GetProviderKey()) { + APP_LOGI("%{public}s, key: %{public}s", __func__, conn.second->GetProviderKey().c_str()); + count++; + if (count > 1) { + APP_LOGI("%{public}s end, true.", __func__); + return true; + } + } + } + APP_LOGI("%{public}s end, false.", __func__); + return false; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_sys_event_receiver.cpp b/services/formmgr/src/form_sys_event_receiver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d70134defb085dce995be5ecb0d871ecc4ebafdb --- /dev/null +++ b/services/formmgr/src/form_sys_event_receiver.cpp @@ -0,0 +1,526 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bundle_info.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "form_bms_helper.h" +#include "form_cache_mgr.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_db_info.h" +#include "form_info_mgr.h" +#include "form_provider_mgr.h" +#include "form_sys_event_receiver.h" +#include "form_timer_mgr.h" +#include "form_util.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string KEY_UID = "uid"; +const std::string KEY_USER_ID = "userId"; +/** + * @brief Receiver Constructor. + * @param subscriberInfo Subscriber info. + */ +FormSysEventReceiver::FormSysEventReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo) + : EventFwk::CommonEventSubscriber(subscriberInfo) +{} +/** + * @brief Receive common event. + * @param eventData Common event data. + */ +void FormSysEventReceiver::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + const AAFwk::Want& want = eventData.GetWant(); + std::string action = want.GetAction(); + std::string bundleName = want.GetElement().GetBundleName(); + if (action.empty() || bundleName.empty()) { + APP_LOGE("%{public}s failed, invalid param, action: %{public}s, bundleName: %{public}s", + __func__, action.c_str(), bundleName.c_str()); + return; + } + APP_LOGI("%{public}s, action:%{public}s.", __func__, action.c_str()); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED || + action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) { + // install or update + APP_LOGI("%{public}s, bundle changed, bundleName: %{public}s", __func__, bundleName.c_str()); + HandleBundleFormInfoChanged(bundleName); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + APP_LOGI("%{public}s, bundle removed, bundleName: %{public}s", __func__, bundleName.c_str()); + HandleProviderRemoved(bundleName); + HandleBundleFormInfoRemoved(bundleName); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED) { + APP_LOGI("%{public}s, bundle updated, bundleName: %{public}s", __func__, bundleName.c_str()); + HandleProviderUpdated(bundleName); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { + int uid = want.GetIntParam(KEY_UID, 0); + HandleBundleDataCleared(bundleName, uid); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_UID_REMOVED) { + int32_t userId = want.GetIntParam(KEY_USER_ID, -1); + if (userId == -1) { + APP_LOGE("%{public}s, failed to get userId, bundleName: %{public}s", __func__, bundleName.c_str()); + return; + } + HandleUserIdRemoved(userId); + } else { + APP_LOGW("%{public}s warnning, invalid action.", __func__); + } +} +/** + * @brief Handle provider updated event. + * @param bundleName bundle name. + * @param uid uid. + */ +void FormSysEventReceiver::HandleProviderUpdated(const std::string &bundleName) +{ + std::vector formInfos; + bool bResult = FormDataMgr::GetInstance().GetFormRecord(bundleName, formInfos); + if (!bResult) { + APP_LOGI("%{public}s, no form info.", __func__); + return; + } + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + // GetBundleMgr() has error log + return; + } + + std::vector targetForms; + if (!iBundleMgr->GetFormsInfoByApp(bundleName, targetForms)) { + APP_LOGE("%{public}s error, failed to get forms info.", __func__); + return; + } + + if (targetForms.empty()) { + APP_LOGE("%{public}s error, targetForms is empty.", __func__); + return; + } + + std::vector removedForms; + std::vector updatedForms; + for (FormRecord& formRecord : formInfos) { + APP_LOGI("%{public}s, provider update, formName:%{public}s", __func__, formRecord.formName.c_str()); + int64_t formId = formRecord.formId; + if (ProviderFormUpdated(formId, formRecord, targetForms)) { + updatedForms.emplace_back(formId); + continue; + } + + APP_LOGI("%{public}s, no such form anymore, delete it:%{public}s", __func__, formRecord.formName.c_str()); + if (!formRecord.formTempFlg) { + FormDbCache::GetInstance().DeleteFormInfo(formId); + } else { + FormDataMgr::GetInstance().DeleteTempForm(formId); + } + removedForms.emplace_back(formId); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + } + + if (!removedForms.empty()) { + APP_LOGI("%{public}s, clean removed forms", __func__); + FormDataMgr::GetInstance().CleanHostRemovedForms(removedForms); + } + + APP_LOGI("%{public}s, remove form timer", __func__); + for (const int64_t id : removedForms) { + FormTimerMgr::GetInstance().RemoveFormTimer(id); + } + + APP_LOGI("%{public}s, refresh form", __func__); + Want want; + for (const int64_t id : updatedForms) { + FormProviderMgr::GetInstance().RefreshForm(id, want); + } +} + +void FormSysEventReceiver::HandleProviderRemoved(const std::string &bundleName) +{ + APP_LOGI("GET into HandleProviderRemoved with bundleName : %{public}s", bundleName.c_str()); + // clean removed form in DB + std::set removedForms; + { + std::vector removedDBForm; + FormDbCache::GetInstance().DeleteFormInfoByBundleName(bundleName, removedDBForm); + for (const auto &dbForm : removedDBForm) { + removedForms.emplace(dbForm.formId); + int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(dbForm.bundleName, dbForm.moduleName); + if (matchCount == 0) { + FormBmsHelper::GetInstance().NotifyModuleRemovable(dbForm.bundleName, dbForm.moduleName); + } + } + } + // clean removed form in FormRecords + FormDataMgr::GetInstance().CleanRemovedFormRecords(bundleName, removedForms); + // clean removed temp form in FormRecords + FormDataMgr::GetInstance().CleanRemovedTempFormRecords(bundleName, removedForms); + // clean removed forms in FormHostRecords + std::vector vRemovedForms; + vRemovedForms.assign(removedForms.begin(), removedForms.end()); + FormDataMgr::GetInstance().CleanHostRemovedForms(vRemovedForms); + + // clean removed form timers + for (auto &formId : removedForms) { + FormTimerMgr::GetInstance().RemoveFormTimer(formId); + } +} + +bool FormSysEventReceiver::ProviderFormUpdated(const int64_t formId, + const FormRecord &formRecord, const std::vector &targetForms) +{ + APP_LOGI("%{public}s start", __func__); + if (targetForms.empty()) { + APP_LOGE("%{public}s error, targetForms is empty", __func__); + return false; + } + + FormInfo updatedForm; + bool bGetForm = FormDataMgr::GetInstance().GetUpdatedForm(formRecord, targetForms, updatedForm); + if (bGetForm) { + APP_LOGI("%{public}s, form is still exist,form:%{public}s", __func__, formRecord.formName.c_str()); + // update resource + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + FormCacheMgr::GetInstance().DeleteData(formId); + + FormBmsHelper::GetInstance().NotifyModuleNotRemovable(formRecord.bundleName, formRecord.moduleName); + FormTimerCfg timerCfg; + GetTimerCfg(updatedForm.updateEnabled, updatedForm.updateDuration, + updatedForm.scheduledUpdateTime, timerCfg); + HandleTimerUpdate(formId, formRecord, timerCfg); + FormDataMgr::GetInstance().SetVersionUpgrade(formId, true); + return true; + } + APP_LOGI("%{public}s, no updated form.", __func__); + return false; +} + +void FormSysEventReceiver::HandleBundleFormInfoChanged(const std::string &bundleName) +{ + FormInfoMgr::GetInstance().Update(bundleName); +} + +void FormSysEventReceiver::HandleBundleFormInfoRemoved(const std::string &bundleName) +{ + FormInfoMgr::GetInstance().Remove(bundleName); +} + +void FormSysEventReceiver::HandleBundleDataCleared(const std::string &bundleName, const int uid) +{ + APP_LOGD("%{public}s, bundleName:%{public}s, uid:%{public}d", __func__, bundleName.c_str(), uid); + // as provider data is cleared + std::set reCreateForms; + FormDataMgr::GetInstance().GetReCreateFormRecordsByBundleName(bundleName, reCreateForms); + if (!reCreateForms.empty()) { + for (int64_t formId : reCreateForms) { + ReCreateForm(formId); + } + } + + // as form host data is cleared + HandleFormHostDataCleared(uid); +} +void FormSysEventReceiver::HandleFormHostDataCleared(const int uid) +{ + APP_LOGD("%{public}s, uid:%{public}d", __func__, uid); + std::map removedFormsMap; + // clear formDBRecord + ClearFormDBRecordData(uid, removedFormsMap); + + // clear temp form + ClearTempFormRecordData(uid, removedFormsMap); + + // clear host data + FormDataMgr::GetInstance().ClearHostDataByUId(uid); + + // delete forms timer + for (const auto &removedForm : removedFormsMap) { + if (removedForm.second) { + FormTimerMgr::GetInstance().RemoveFormTimer(removedForm.first); + } + } +} +void FormSysEventReceiver::ClearFormDBRecordData(const int uid, std::map &removedFormsMap) +{ + std::map foundFormsMap; + std::map> noHostFormDbMap; + FormDbCache::GetInstance().GetNoHostDBForms(uid, noHostFormDbMap, foundFormsMap); + if (foundFormsMap.size() > 0) { + for (const auto &element : foundFormsMap) { + FormDataMgr::GetInstance().DeleteFormUserUid(element.first, uid); + } + } + + APP_LOGD("%{public}s, noHostFormDbMap size:%{public}zu", __func__, noHostFormDbMap.size()); + if (noHostFormDbMap.size() > 0) { + BatchDeleteNoHostDBForms(uid, noHostFormDbMap, foundFormsMap); + } + + if (!foundFormsMap.empty()) { + removedFormsMap.insert(foundFormsMap.begin(), foundFormsMap.end()); + } +} +void FormSysEventReceiver::ClearTempFormRecordData(const int uid, std::map &removedFormsMap) +{ + std::map foundFormsMap; + std::map> noHostTempFormsMap; + FormDataMgr::GetInstance().GetNoHostTempForms(uid, noHostTempFormsMap, foundFormsMap); + APP_LOGD("%{public}s, noHostTempFormsMap size:%{public}zu", __func__, noHostTempFormsMap.size()); + if (noHostTempFormsMap.size() > 0) { + BatchDeleteNoHostTempForms(uid, noHostTempFormsMap, foundFormsMap); + } + if (!foundFormsMap.empty()) { + removedFormsMap.insert(foundFormsMap.begin(), foundFormsMap.end()); + } +} +void FormSysEventReceiver::BatchDeleteNoHostDBForms(const int uid, std::map> &noHostFormDbMap, std::map &removedFormsMap) +{ + std::set removableModuleSet; + for (const auto &element: noHostFormDbMap) { + std::set formIds = element.second; + FormIdKey formIdKey = element.first; + std::string bundleName = formIdKey.bundleName; + std::string abilityName = formIdKey.abilityName; + int result = FormProviderMgr::GetInstance().NotifyProviderFormsBatchDelete(bundleName, abilityName, formIds); + if (result != ERR_OK) { + APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s,\ + abilityName:%{public}s", + __func__, bundleName.c_str(), abilityName.c_str()); + for (int64_t formId : formIds) { + FormDBInfo dbInfo; + int errCode = FormDbCache::GetInstance().GetDBRecord(formId, dbInfo); + if (errCode == ERR_OK) { + dbInfo.formUserUids.emplace_back(uid); + FormDbCache::GetInstance().SaveFormInfo(dbInfo); + } + } + } else { + for (const int64_t formId : formIds) { + removedFormsMap.emplace(formId, true); + FormDBInfo dbInfo; + int errCode = FormDbCache::GetInstance().GetDBRecord(formId, dbInfo); + if (errCode == ERR_OK) { + FormIdKey removableModuleFormIdKey; + removableModuleFormIdKey.bundleName = dbInfo.bundleName; + removableModuleFormIdKey.moduleName = dbInfo.moduleName; + removableModuleSet.emplace(removableModuleFormIdKey); + FormDbCache::GetInstance().DeleteFormInfo(formId); + } + FormDataMgr::GetInstance().DeleteFormRecord(formId); + } + } + } + + for (const FormIdKey &item : removableModuleSet) { + int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(item.bundleName, item.moduleName); + if (matchCount == 0) { + FormBmsHelper::GetInstance().NotifyModuleRemovable(item.bundleName, item.moduleName); + } + } +} +/** + * @brief Delete no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ +void FormSysEventReceiver::BatchDeleteNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, std::map &foundFormsMap) +{ + for (const auto &element : noHostTempFormsMap) { + std::set formIds = element.second; + FormIdKey formIdKey = element.first; + std::string bundleName = formIdKey.bundleName; + std::string abilityName = formIdKey.abilityName; + int result = FormProviderMgr::GetInstance().NotifyProviderFormsBatchDelete(bundleName, abilityName, formIds); + if (result != ERR_OK) { + APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s,\ + abilityName:%{public}s", + __func__, bundleName.c_str(), abilityName.c_str()); + for (int64_t formId : formIds) { + FormDataMgr::GetInstance().AddFormUserUid(formId, uid); + } + } else { + for (int64_t formId : formIds) { + foundFormsMap.emplace(formId, true); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteTempForm(formId); + } + } + } +} +void FormSysEventReceiver::ReCreateForm(const int64_t formId) +{ + APP_LOGI("%{public}s start, formId:%{public}" PRId64 "", __func__, formId); + FormRecord reCreateRecord; + FormRecord record; + bool isGetForm = FormDataMgr::GetInstance().GetFormRecord(formId, record); + if (!isGetForm) { + APP_LOGE("%{public}s error, not exist such form:%{public}" PRId64 "", __func__, formId); + return; + } + FormCacheMgr::GetInstance().DeleteData(formId); + + reCreateRecord.bundleName = record.bundleName; + reCreateRecord.abilityName = record.abilityName; + reCreateRecord.formName = record.formName; + reCreateRecord.specification = record.specification; + reCreateRecord.formTempFlg = record.formTempFlg; + reCreateRecord.isInited = record.isInited; + reCreateRecord.versionUpgrade = record.versionUpgrade; + + Want want; + FormUtil::CreateFormWant(reCreateRecord.formName, reCreateRecord.specification, reCreateRecord.formTempFlg, want); + want.SetParam(Constants::RECREATE_FORM_KEY, true); + FormProviderMgr::GetInstance().ConnectAmsForRefresh(formId, reCreateRecord, want, false); +} +void FormSysEventReceiver::GetTimerCfg(const bool updateEnabled, + const int updateDuration, const std::string &configUpdateAt, FormTimerCfg& cfg) +{ + APP_LOGI("%{public}s start", __func__); + if (!updateEnabled) { + APP_LOGI("%{public}s, update disable", __func__); + return; + } + + if (updateDuration > 0) { + // interval timer + APP_LOGI("%{public}s,interval timer updateDuration:%{public}d", __func__, updateDuration); + if (updateDuration <= Constants::MIN_CONFIG_DURATION) { + cfg.updateDuration = Constants::MIN_PERIOD; + } else if (updateDuration >= Constants::MAX_CONFIG_DURATION) { + cfg.updateDuration = Constants::MAX_PERIOD; + } else { + cfg.updateDuration = updateDuration * Constants::TIME_CONVERSION; + } + cfg.enableUpdate = true; + return; + } else { + // updateAtTimer + if (configUpdateAt.empty()) { + APP_LOGI("%{public}s, configUpdateAt is empty", __func__); + return; + } + APP_LOGI("%{public}s,update at timer updateAt:%{public}s", __func__, configUpdateAt.c_str()); + + std::vector temp = FormUtil::StringSplit(configUpdateAt, Constants::TIME_DELIMETER); + if (temp.size() != Constants::UPDATE_AT_CONFIG_COUNT) { + APP_LOGE("%{public}s, invalid config", __func__); + return; + } + int hour = -1; + int min = -1; + hour = std::stoi(temp[0]); + min = std::stoi(temp[1]); + if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min > + Constants::MAX_MININUTE) { + APP_LOGE("%{public}s, time is invalid", __func__); + return; + } + + cfg.updateAtHour = hour; + cfg.updateAtMin = min; + cfg.enableUpdate = true; + return; + } +} + +void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, + const FormRecord &record, const FormTimerCfg &timerCfg) +{ + // both disable + if (!record.isEnableUpdate && !timerCfg.enableUpdate) { + return; + } + + // enable to disable + if (record.isEnableUpdate && !timerCfg.enableUpdate) { + FormDataMgr::GetInstance().SetEnableUpdate(formId, false); + FormTimerMgr::GetInstance().RemoveFormTimer(formId); + return; + } + + // disable to enable + if (!record.isEnableUpdate && timerCfg.enableUpdate) { + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, + timerCfg.updateDuration, timerCfg.updateAtHour, timerCfg.updateAtMin); + if (timerCfg.updateDuration > 0) { + APP_LOGI("%{public}s, add interval timer:%{public}" PRId64 "", __func__, timerCfg.updateDuration); + FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateDuration, record.userId); + } else { + APP_LOGI("%{public}s, add at timer:%{public}d, %{public}d", __func__, + timerCfg.updateAtHour, timerCfg.updateAtMin); + FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateAtHour, + timerCfg.updateAtMin, record.userId); + } + + return; + } + + // both enable + UpdateType type; + if (record.updateDuration > 0) { + if (timerCfg.updateDuration > 0) { + // no change + if (record.updateDuration == timerCfg.updateDuration) { + return; + } + // interval change + type = TYPE_INTERVAL_CHANGE; + } else { + // interval to updateat + type = TYPE_INTERVAL_TO_ATTIME; + } + } else { + if (timerCfg.updateDuration > 0) { + // updateat to interval + type = TYPE_ATTIME_TO_INTERVAL; + } else { + // no change; + if (record.updateAtHour == timerCfg.updateAtHour && record.updateAtMin == timerCfg.updateAtMin) { + return; + } + // updateat change + type = TYPE_ATTIME_CHANGE; + } + } + + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, + timerCfg.updateDuration, timerCfg.updateAtHour, timerCfg.updateAtMin); + FormTimerMgr::GetInstance().UpdateFormTimer(formId, type, timerCfg); +} + +// multiuser +void FormSysEventReceiver::HandleUserIdRemoved(const int32_t userId) +{ + std::vector removedFormIds; + FormDataMgr::GetInstance().DeleteFormsByUserId(userId, removedFormIds); + FormDbCache::GetInstance().DeleteDBFormsByUserId(userId); + + // delete form timer + std::vector::iterator itRemoved; + for (itRemoved = removedFormIds.begin();itRemoved != removedFormIds.end(); itRemoved++) { + FormTimerMgr::GetInstance().RemoveFormTimer(*itRemoved); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_task_mgr.cpp b/services/formmgr/src/form_task_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67ecbebc71e05fd6f5ffdbef7ca5decdd7a03688 --- /dev/null +++ b/services/formmgr/src/form_task_mgr.cpp @@ -0,0 +1,510 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_host_interface.h" +#include "form_item_info.h" +#include "form_mgr_adapter.h" +#include "form_provider_interface.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" + +namespace OHOS { +namespace AppExecFwk { +const int FORM_TASK_DELAY_TIME = 20; // ms +FormTaskMgr::FormTaskMgr() {} +FormTaskMgr::~FormTaskMgr() {} +/** + * @brief Acquire form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostAcquireTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function acquireProviderFormInfoFunc = std::bind(&FormTaskMgr::AcquireProviderFormInfo, + this, formId, want, remoteObject); + eventHandler_->PostTask(acquireProviderFormInfoFunc, FORM_TASK_DELAY_TIME); +} +/** + * @brief Delete form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostDeleteTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function notifyFormDeleteFunc = std::bind(&FormTaskMgr::NotifyFormDelete, + this, formId, want, remoteObject); + eventHandler_->PostTask(notifyFormDeleteFunc, FORM_TASK_DELAY_TIME); +} + +/** + * @brief Refresh form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::PostRefreshTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function notifyFormUpdateFunc = std::bind(&FormTaskMgr::NotifyFormUpdate, + this, formId, want, remoteObject); + eventHandler_->PostTask(notifyFormUpdateFunc, FORM_TASK_DELAY_TIME); +} + +/** + * @brief Cast temp form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::PostCastTempTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function notifyCastTempFunc = std::bind(&FormTaskMgr::NotifyCastTemp, + this, formId, want, remoteObject); + eventHandler_->PostTask(notifyCastTempFunc, FORM_TASK_DELAY_TIME); +} + +/** + * @brief Post form data to form host(task) when acquire form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::PostAcquireTaskToHost(const int64_t formId, const FormRecord &record, + const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function acquireTaskToHostFunc = std::bind(&FormTaskMgr::AcquireTaskToHost, + this, formId, record, remoteObject); + eventHandler_->PostTask(acquireTaskToHostFunc, FORM_TASK_DELAY_TIME); +} + +/** + * @brief Post form data to form host(task) when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::PostUpdateTaskToHost(const int64_t formId, const FormRecord &record, + const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + + APP_LOGD("%{public}s, post the task of updateTaskToHostFunc.", __func__); + std::function updateTaskToHostFunc = std::bind(&FormTaskMgr::UpdateTaskToHost, + this, formId, record, remoteObject); + eventHandler_->PostTask(updateTaskToHostFunc, FORM_TASK_DELAY_TIME); +} + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the form. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +/** + * @brief Handel form host died(task). + * @param remoteHost Form host proxy object. + */ +void FormTaskMgr::PostHostDiedTask(const sptr &remoteHost) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function postTaskFunc = std::bind(&FormTaskMgr::HostDied, + this, remoteHost); + eventHandler_->PostTask(postTaskFunc, FORM_TASK_DELAY_TIME); +} + +/** + * @brief Post event notify to form provider. + * + * @param formEvent The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ +void FormTaskMgr::PostEventNotifyTask(const std::vector &formEvent, const int32_t formVisibleType, + const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function eventNotifyFunc = std::bind(&FormTaskMgr::EventNotify, + this, formEvent, formVisibleType, want, remoteObject); + eventHandler_->PostTask(eventNotifyFunc, FORM_TASK_DELAY_TIME); +} +/** + * @brief Post provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostProviderBatchDeleteTask(std::set &formIds, const Want &want, + const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function batchDeleteFunc = std::bind(&FormTaskMgr::ProviderBatchDelete, + this, formIds, want, remoteObject); + eventHandler_->PostTask(batchDeleteFunc, FORM_TASK_DELAY_TIME); +} +/** + * @brief Post message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostFormEventTask(const int64_t formId, const std::string &message, + const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function formEventFunc = std::bind(&FormTaskMgr::FireFormEvent, + this, formId, message, want, remoteObject); + eventHandler_->PostTask(formEventFunc, FORM_TASK_DELAY_TIME); +} + +/** + * @brief Post uninstall message to form host(task). + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostUninstallTaskToHost(const std::vector &formIds, const sptr &remoteObject) +{ + APP_LOGI("%{public}s start", __func__); + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function uninstallFunc = std::bind(&FormTaskMgr::FormUninstall, + this, formIds, remoteObject); + eventHandler_->PostTask(uninstallFunc, FORM_TASK_DELAY_TIME); + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &remoteObject) +{ + FormMgrAdapter::GetInstance().AcquireProviderFormInfo(formId, want, remoteObject); +} + +/** + * @brief Notify form provider for delete form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + FormMgrAdapter::GetInstance().NotifyFormDelete(formId, want, remoteObject); +} + +/** + * @brief Notify form provider for updating form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); + return; + } + int error = formProviderProxy->NotifyFormUpdate(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to notify form update.", __func__); + } +} + +/** + * @brief Event notify to form provider. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ +void FormTaskMgr::EventNotify(const std::vector &formEvents, const int32_t formVisibleType, + const Want &want, const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->EventNotify(formEvents, formVisibleType, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to send event notify.", __func__); + } +} + +/** + * @brief Notify form provider for cast temp form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::NotifyCastTemp(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->NotifyFormCastTempForm(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} + +/** + * @brief Post form data to form host when acquire form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::AcquireTaskToHost(const int64_t formId, const FormRecord &record, + const sptr &remoteObject) +{ + APP_LOGI("FormTaskMgr AcquireTaskToHost, formId:%{public}" PRId64 "", formId); + + sptr remoteFormHost = iface_cast(remoteObject); + if (remoteFormHost == nullptr) { + APP_LOGE("%{public}s fail, Failed to get form host proxy", __func__); + return; + } + + APP_LOGD("FormTaskMgr remoteFormHost OnAcquired"); + remoteFormHost->OnAcquired(CreateFormJsInfo(formId, record)); +} + +/** + * @brief Post form data to form host when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::UpdateTaskToHost(const int64_t formId, const FormRecord &record, + const sptr &remoteObject) +{ + APP_LOGI("%{public}s start.", __func__); + + sptr remoteFormHost = iface_cast(remoteObject); + if (remoteFormHost == nullptr) { + APP_LOGE("%{public}s fail, Failed to get form host proxy.", __func__); + return; + } + + APP_LOGD("%{public}s, FormTaskMgr remoteFormHost OnUpdate.", __func__); + remoteFormHost->OnUpdate(CreateFormJsInfo(formId, record)); + + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ +void FormTaskMgr::HostDied(const sptr &remoteHost) +{ + APP_LOGI("%{public}s, remote client died event", __func__); + if (remoteHost == nullptr) { + APP_LOGI("%{public}s, remote client died, invalid param", __func__); + return; + } + FormDataMgr::GetInstance().HandleHostDied(remoteHost); +} +/** + * @brief Post provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::ProviderBatchDelete(std::set &formIds, const Want &want, + const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + std::vector vFormIds; + vFormIds.assign(formIds.begin(), formIds.end()); + int error = formProviderProxy->NotifyFormsDelete(vFormIds, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s failed", __func__); + } +} +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &remoteObject) +{ + APP_LOGI("%{public}s start", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s, Failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->FireFormEvent(formId, message, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s, Failed to fire message event to form provider", __func__); + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Handle uninstall message. + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::FormUninstall(const std::vector &formIds, + const sptr &remoteObject) +{ + APP_LOGI("%{public}s start", __func__); + sptr remoteFormHost = iface_cast(remoteObject); + if (remoteFormHost == nullptr) { + APP_LOGE("%{public}s fail, Failed to get form host proxy.", __func__); + return; + } + + remoteFormHost->OnUninstall(formIds); + + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Create form data for form host. + * @param formId The Id of the form. + * @param record Form record. + * @return Form data. + */ +FormJsInfo FormTaskMgr::CreateFormJsInfo(const int64_t formId, const FormRecord &record) +{ + APP_LOGI("%{public}s start", __func__); + FormJsInfo form; + form.formId = formId; + form.bundleName = record.bundleName; + form.abilityName = record.abilityName; + form.formName = record.formName; + form.formTempFlg = record.formTempFlg; + form.jsFormCodePath = record.jsFormCodePath; + form.formData = record.formProviderInfo.GetFormDataString(); + form.formProviderData = record.formProviderInfo.GetFormData(); + form.formSrc = record.formSrc; + form.formWindow = record.formWindow; + APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, + form.jsFormCodePath.c_str(), form.formData.c_str()); + return form; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_timer_mgr.cpp b/services/formmgr/src/form_timer_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87afae21727d63f52d70bc07d8f4703f514bd1d4 --- /dev/null +++ b/services/formmgr/src/form_timer_mgr.cpp @@ -0,0 +1,1299 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_timer_mgr.h" + +#include + +#include "ability_context.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "context/context.h" +#include "form_constants.h" +#include "form_provider_mgr.h" +#include "form_refresh_limiter.h" +#include "form_timer_option.h" +#include "form_util.h" +#include "os_account_manager.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int TIMER_TYPE_ELAPSED_REALTIME = 1; +const int TIMER_TYPE_ELAPSED_REALTIME_WAKEUP = 2; +const int TIMER_TYPE_RTC_WAKEUP = 3; + +const int REQUEST_UPDATE_AT_CODE = 1; +const int REQUEST_LIMITER_CODE = 2; +const int REQUEST_DYNAMIC_CODE = 3; + +FormTimerMgr::FormTimerMgr() +{ + Init(); +} +FormTimerMgr::~FormTimerMgr() +{ + ClearIntervalTimer(); +} +/** + * @brief Add form timer by timer task. + * @param task The form timer task. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddFormTimer(const FormTimer &task) +{ + APP_LOGI("%{public}s, formId: %{public}" PRId64 ", userId:%{public}d", __func__, task.formId, task.userId); + if (task.isUpdateAt) { + if (task.hour >= Constants::MIN_TIME && task.hour <= Constants::MAX_HOUR && task.min >= Constants::MIN_TIME && + task.min <= Constants::MAX_MININUTE) { + return AddUpdateAtTimer(task); + } else { + APP_LOGE("%{public}s failed, update at time is invalid", __func__); + return false; + } + } else { + if (task.period >= Constants::MIN_PERIOD && task.period <= Constants::MAX_PERIOD && + (task.period % Constants::MIN_PERIOD) == 0) { + return AddIntervalTimer(task); + } else { + APP_LOGE("%{public}s failed, interval time is invalid", __func__); + return false; + } + } +} +/** + * @brief Add duration form timer. + * @param formId The Id of the form. + * @param updateDuration Update duration + * @param userId User ID. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddFormTimer(const int64_t formId, const long updateDuration, const int32_t userId) +{ + FormTimer timerTask(formId, updateDuration, userId); + return AddFormTimer(timerTask); +} +/** + * @brief Add scheduled form timer. + * @param formId The Id of the form. + * @param updateAtHour Hour. + * @param updateAtMin Min. + * @param userId User ID. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddFormTimer(const int64_t formId, const long updateAtHour, + const long updateAtMin, const int32_t userId) +{ + FormTimer timerTask(formId, updateAtHour, updateAtMin, userId); + return AddFormTimer(timerTask); +} +/** + * @brief Remove form timer by form id. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::RemoveFormTimer(const int64_t formId) +{ + APP_LOGI("%{public}s, task: %{public}" PRId64 "", __func__, formId); + + if (!DeleteIntervalTimer(formId)) { + if (!DeleteUpdateAtTimer(formId)) { + APP_LOGE("%{public}s, failed to DeleteUpdateAtTimer", __func__); + return false; + } + } + + if (!DeleteDynamicItem(formId)) { + APP_LOGE("%{public}s, failed to DeleteDynamicItem", __func__); + return false; + } + refreshLimiter_.DeleteItem(formId); + + return true; +} +/** + * @brief Update form timer. + * @param formId The Id of the form. + * @param type Timer type. + * @param timerCfg Timer config. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateFormTimer(const int64_t formId, const UpdateType &type, const FormTimerCfg &timerCfg) +{ + if (!timerCfg.enableUpdate) { + APP_LOGW("%{public}s, enableUpdate is false", __func__); + return false; + } + + switch (type) { + case UpdateType::TYPE_INTERVAL_CHANGE: { + return UpdateIntervalValue(formId, timerCfg); + } + case UpdateType::TYPE_ATTIME_CHANGE: { + return UpdateAtTimerValue(formId, timerCfg); + } + case UpdateType::TYPE_INTERVAL_TO_ATTIME: { + return IntervalToAtTimer(formId, timerCfg); + } + case UpdateType::TYPE_ATTIME_TO_INTERVAL: { + return AtTimerToIntervalTimer(formId, timerCfg); + } + default: { + APP_LOGE("%{public}s failed, invalid UpdateType", __func__); + return false; + } + } +} +/** + * @brief Update Interval timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateIntervalValue(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateDuration < Constants::MIN_PERIOD || timerCfg.updateDuration > Constants::MAX_PERIOD + || (timerCfg.updateDuration % Constants::MIN_PERIOD) != 0) { + APP_LOGE("%{public}s failed, invalid param", __func__); + return false; + } + + std::lock_guard lock(intervalMutex_); + auto intervalTask = intervalTimerTasks_.find(formId); + if (intervalTask != intervalTimerTasks_.end()) { + intervalTask->second.period = timerCfg.updateDuration; + return true; + } else { + APP_LOGE("%{public}s failed, the interval timer is not exist", __func__); + return false; + } +} +/** + * @brief Update update at timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateAtTimerValue(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateAtHour < Constants::MIN_TIME || timerCfg.updateAtHour > Constants::MAX_HOUR + || timerCfg.updateAtMin < Constants::MIN_TIME || timerCfg.updateAtMin > Constants::MAX_MININUTE) { + APP_LOGE("%{public}s failed, time is invalid", __func__); + return false; + } + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + UpdateAtItem changedItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->refreshTask.formId == formId) { + changedItem = *itItem; + updateAtTimerTasks_.erase(itItem); + break; + } + } + + if (changedItem.refreshTask.formId == 0) { + APP_LOGE("%{public}s failed, the update at timer is not exist", __func__); + return false; + } + changedItem.refreshTask.hour = timerCfg.updateAtHour; + changedItem.refreshTask.min = timerCfg.updateAtMin; + changedItem.updateAtTime = changedItem.refreshTask.hour * Constants::MIN_PER_HOUR + changedItem.refreshTask.min; + AddUpdateAtItem(changedItem); + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + return true; +} +/** + * @brief Interval timer task to update at timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::IntervalToAtTimer(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateAtHour < Constants::MIN_TIME || timerCfg.updateAtHour > Constants::MAX_HOUR + || timerCfg.updateAtMin < Constants::MIN_TIME || timerCfg.updateAtMin > Constants::MAX_MININUTE) { + APP_LOGE("%{public}s failed, time is invalid", __func__); + return false; + } + + std::lock_guard lock(intervalMutex_); + FormTimer timerTask; + auto intervalTask = intervalTimerTasks_.find(formId); + if (intervalTask != intervalTimerTasks_.end()) { + timerTask = intervalTask->second; + intervalTimerTasks_.erase(intervalTask); + + timerTask.isUpdateAt = true; + timerTask.hour = timerCfg.updateAtHour; + timerTask.min = timerCfg.updateAtMin; + if (!AddUpdateAtTimer(timerTask)) { + APP_LOGE("%{public}s, failed to add update at timer", __func__); + return false; + } + return true; + } else { + APP_LOGE("%{public}s failed, the interval timer is not exist", __func__); + return false; + } +} +/** + * @brief Update at timer task to interval timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AtTimerToIntervalTimer(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateDuration < Constants::MIN_PERIOD || timerCfg.updateDuration > Constants::MAX_PERIOD + || (timerCfg.updateDuration % Constants::MIN_PERIOD) != 0) { + APP_LOGE("%{public}s failed, time is invalid", __func__); + return false; + } + + UpdateAtItem targetItem; + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->refreshTask.formId == formId) { + targetItem = *itItem; + updateAtTimerTasks_.erase(itItem); + break; + } + } + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + + if (targetItem.refreshTask.formId == 0) { + APP_LOGE("%{public}s failed, the update at timer is not exist", __func__); + return false; + } + targetItem.refreshTask.isUpdateAt = false; + targetItem.refreshTask.period = timerCfg.updateDuration; + targetItem.refreshTask.refreshTime = LONG_MAX; + if (!AddIntervalTimer(targetItem.refreshTask)) { + APP_LOGE("%{public}s, failed to add interval timer", __func__); + return false; + } + return true; +} +/** + * @brief Is limiter enable refresh. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::IsLimiterEnableRefresh(const int64_t formId) +{ + return refreshLimiter_.IsEnableRefresh(formId); +} +/** + * @brief Increase refresh count. + * @param formId The Id of the form. + */ +void FormTimerMgr::IncreaseRefreshCount(const int64_t formId) +{ + refreshLimiter_.Increase(formId); +} +/** + * @brief Set next refresh time. + * @param formId The Id of the form. + * @param nextGapTime Next gap time(ms). + * @param userId User ID. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::SetNextRefreshTime(const int64_t formId, const long nextGapTime, const int32_t userId) +{ + if (nextGapTime < Constants::MIN_NEXT_TIME) { + APP_LOGE("%{public}s failed, nextGapTime is invalid, nextGapTime:%{public}ld", __func__, nextGapTime); + return false; + } + auto timeSinceEpoch = std::chrono::steady_clock::now().time_since_epoch(); + auto timeInSec = std::chrono::duration_cast(timeSinceEpoch).count(); + int64_t refreshTime = timeInSec + nextGapTime; // * Constants::MS_PER_SECOND; + std::lock_guard lock(refreshMutex_); + bool isExist = false; + for (auto &refreshItem: dynamicRefreshTasks_) { + if ((refreshItem.formId == formId) && (refreshItem.userId == userId)) { + refreshItem.settedTime = refreshTime; + isExist = true; + break; + } + } + if (!isExist) { + DynamicRefreshItem theItem; + theItem.formId = formId; + theItem.settedTime = refreshTime; + theItem.userId = userId; + dynamicRefreshTasks_.emplace_back(theItem); + } + std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to UpdateDynamicAlarm", __func__); + return false; + } + refreshLimiter_.AddItem(formId); + SetEnableFlag(formId, false); + + return true; +} + +void FormTimerMgr::SetEnableFlag(int64_t formId, bool flag) +{ + // try interval list + auto iter = intervalTimerTasks_.find(formId); + if (iter != intervalTimerTasks_.end()) { + iter->second.isEnable = flag; + APP_LOGI("%{public}s, formId:%{public}" PRId64 ", isEnable:%{public}d", __func__, formId, flag ? 1 : 0); + return; + } +} + +/** + * @brief Get refresh count. + * @param formId The Id of the form. + * @return Returns refresh count. + */ +int FormTimerMgr::GetRefreshCount(const int64_t formId) const +{ + return refreshLimiter_.GetRefreshCount(formId); +} +/** + * @brief Mark remind. + * @param formId The Id of the form. + * @return true or false. + */ +void FormTimerMgr::MarkRemind(const int64_t formId) +{ + refreshLimiter_.MarkRemind(formId); +} +/** + * @brief Add update at timer. + * @param task Update time task. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddUpdateAtTimer(const FormTimer &task) +{ + APP_LOGI("%{public}s start", __func__); + { + std::lock_guard lock(updateAtMutex_); + for (auto &updateAtTimer : updateAtTimerTasks_) { + if (updateAtTimer.refreshTask.formId == task.formId) { + APP_LOGW("%{public}s, already exist formTimer, formId:%{public}" PRId64 " task", __func__, task.formId); + return true; + } + } + + UpdateAtItem atItem; + atItem.refreshTask = task; + atItem.updateAtTime = task.hour * Constants::MIN_PER_HOUR + task.min; + + AddUpdateAtItem(atItem); + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + + return refreshLimiter_.AddItem(task.formId); +} +/** + * @brief Add update interval timer task. + * @param task Update interval timer task. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddIntervalTimer(const FormTimer &task) +{ + APP_LOGI("%{public}s start", __func__); + { + std::lock_guard lock(intervalMutex_); + EnsureInitIntervalTimer(); + if (intervalTimerTasks_.find(task.formId) != intervalTimerTasks_.end()) { + APP_LOGW("%{public}s, already exist formTimer, formId:%{public}" PRId64 " task", __func__, task.formId); + return true; + } + intervalTimerTasks_.emplace(task.formId, task); + } + if (!UpdateLimiterAlarm()) { + APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); + return false; + } + return refreshLimiter_.AddItem(task.formId); +} +/** + * @brief Add update at timer item. + * @param task Update at timer item. + */ +void FormTimerMgr::AddUpdateAtItem(const UpdateAtItem &atItem) +{ + if (updateAtTimerTasks_.empty()) { + updateAtTimerTasks_.emplace_back(atItem); + return; + } + + UpdateAtItem firstItem = updateAtTimerTasks_.front(); + if (atItem.updateAtTime < firstItem.updateAtTime) { + updateAtTimerTasks_.emplace_front(atItem); + return; + } + + bool isInsert = false; + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (atItem.updateAtTime < itItem->updateAtTime) { + updateAtTimerTasks_.insert(itItem, atItem); + isInsert = true; + break; + } + } + + if (!isInsert) { + updateAtTimerTasks_.emplace_back(atItem); + } +} +/** + * @brief Handle system time changed. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::HandleSystemTimeChanged() +{ + APP_LOGI("%{public}s start", __func__); + if (!updateAtTimerTasks_.empty()) { + return UpdateAtTimerAlarm(); + } + + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Reset form limiter. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::HandleResetLimiter() +{ + APP_LOGI("%{public}s start", __func__); + + std::vector remindTasks; + bool bGetTasks = GetRemindTasks(remindTasks); + if (bGetTasks) { + APP_LOGI("%{public}s failed, remind when reset limiter", __func__); + for (auto &task : remindTasks) { + ExecTimerTask(task); + } + } + + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Update attime trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::OnUpdateAtTrigger(long updateTime) +{ + APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); + std::vector updateList; + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->updateAtTime == updateTime && itItem->refreshTask.isEnable) { + updateList.emplace_back(*itItem); + } + } + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + + if (!updateList.empty()) { + APP_LOGI("%{public}s, update at timer triggered, trigged time: %{public}ld", __func__, updateTime); + for (auto &item : updateList) { + ExecTimerTask(item.refreshTask); + } + } + + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Dynamic time trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::OnDynamicTimeTrigger(long updateTime) +{ + APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); + std::vector updateList; + { + std::lock_guard lock(dynamicMutex_); + auto timeSinceEpoch = std::chrono::steady_clock::now().time_since_epoch(); + auto timeInSec = std::chrono::duration_cast(timeSinceEpoch).count(); + long markedTime = timeInSec + Constants::ABS_REFRESH_MS; + std::vector::iterator itItem; + for (itItem = dynamicRefreshTasks_.begin(); itItem != dynamicRefreshTasks_.end();) { + if (itItem->settedTime <= updateTime || itItem->settedTime <= markedTime) { + if (refreshLimiter_.IsEnableRefresh(itItem->formId)) { + FormTimer timerTask(itItem->formId, true, itItem->userId); + updateList.emplace_back(timerTask); + } + itItem = dynamicRefreshTasks_.erase(itItem); + if (itItem != dynamicRefreshTasks_.end()) { + SetIntervalEnableFlag(itItem->formId, true); + } + } else { + itItem++; + } + } + std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); + } + + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to update dynamic alarm.", __func__); + return false; + } + + if (!updateList.empty()) { + APP_LOGI("%{public}s triggered, trigged time: %{public}ld", __func__, updateTime); + for (auto &task : updateList) { + ExecTimerTask(task); + } + } + + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Get remind tasks. + * @param remindTasks Remind tasks. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::GetRemindTasks(std::vector &remindTasks) +{ + APP_LOGI("%{public}s start", __func__); + std::vector remindList = refreshLimiter_.GetRemindListAndResetLimit(); + for (int64_t id : remindList) { + FormTimer formTimer(id, false); + remindTasks.emplace_back(formTimer); + } + + if (!UpdateLimiterAlarm()) { + APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); + return false; + } + + if (remindTasks.size() > 0) { + APP_LOGI("%{public}s end", __func__); + return true; + } else { + APP_LOGI("%{public}s end, remindTasks is empty", __func__); + return false; + } +} +/** + * @brief Set enableFlag for interval timer task. + * @param formId The Id of the form. + * @param flag Enable flag. + */ +void FormTimerMgr::SetIntervalEnableFlag(int64_t formId, bool flag) +{ + std::lock_guard lock(intervalMutex_); + // try interval list + auto refreshTask = intervalTimerTasks_.find(formId); + if (refreshTask != intervalTimerTasks_.end()) { + refreshTask->second.isEnable = flag; + APP_LOGI("%{public}s, formId:%{public}" PRId64 ", isEnable:%{public}d", __func__, formId, flag ? 1 : 0); + return; + } +} +/** + * @brief Get interval timer task. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::GetIntervalTimer(const int64_t formId, FormTimer &formTimer) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(intervalMutex_); + auto intervalTask = intervalTimerTasks_.find(formId); + if (intervalTask == intervalTimerTasks_.end()) { + APP_LOGI("%{public}s, interval timer not find", __func__); + return false; + } + formTimer = intervalTask->second; + APP_LOGI("%{public}s, get interval timer successfully", __func__); + return true; +} +/** + * @brief Get update at timer. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::GetUpdateAtTimer(const int64_t formId, UpdateAtItem &updateAtItem) +{ + APP_LOGI("%{public}s start", __func__); + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->refreshTask.formId == formId) { + updateAtItem.refreshTask = itItem->refreshTask; + updateAtItem.updateAtTime = itItem->updateAtTime; + APP_LOGI("%{public}s, get update at timer successfully", __func__); + return true; + } + } + } + APP_LOGI("%{public}s, update at timer not find", __func__); + return false; +} +/** + * @brief Get dynamic refresh item. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::GetDynamicItem(const int64_t formId, DynamicRefreshItem &dynamicItem) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(dynamicMutex_); + std::vector::iterator itItem; + for (itItem = dynamicRefreshTasks_.begin(); itItem != dynamicRefreshTasks_.end();) { + if (itItem->formId == formId) { + dynamicItem.formId = itItem->formId; + dynamicItem.settedTime = itItem->settedTime; + dynamicItem.userId = itItem->userId; + APP_LOGI("%{public}s, get dynamic item successfully", __func__); + return true; + } + } + APP_LOGI("%{public}s, dynamic item not find", __func__); + return false; +} +/** + * @brief Delete interval timer task. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::DeleteIntervalTimer(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + bool isExist = false; + std::lock_guard lock(intervalMutex_); + auto intervalTask = intervalTimerTasks_.find(formId); + if (intervalTask != intervalTimerTasks_.end()) { + intervalTimerTasks_.erase(intervalTask); + isExist = true; + } + + if (intervalTimerTasks_.empty()) { + ClearIntervalTimer(); + } + APP_LOGI("%{public}s end", __func__); + return isExist; +} +/** + * @brief Delete update at timer. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->refreshTask.formId == formId) { + updateAtTimerTasks_.erase(itItem); + break; + } + } + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + return true; + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Delete dynamic refresh item. + * @param formId The Id of the form. + */ +bool FormTimerMgr::DeleteDynamicItem(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(dynamicMutex_); + std::vector::iterator itItem; + for (itItem = dynamicRefreshTasks_.begin(); itItem != dynamicRefreshTasks_.end();) { + if (itItem->formId == formId) { + itItem = dynamicRefreshTasks_.erase(itItem); + if (itItem != dynamicRefreshTasks_.end()) { + SetIntervalEnableFlag(itItem->formId, true); + } + break; + } + } + std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); + + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to UpdateDynamicAlarm", __func__); + return false; + } + return true; + APP_LOGI("%{public}s end", __func__); +} +/** +* @brief interval timer task timeout. +*/ +void FormTimerMgr::OnIntervalTimeOut() +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(intervalMutex_); + std::vector updateList; + long currentTime = FormUtil::GetCurrentNanosecond() / Constants::TIME_1000000; + for (auto &intervalPair : intervalTimerTasks_) { + FormTimer &intervalTask = intervalPair.second; + if ((intervalTask.refreshTime == LONG_MAX || (currentTime - intervalTask.refreshTime) >= intervalTask.period || + std::abs((currentTime - intervalTask.refreshTime) - intervalTask.period) < Constants::ABS_TIME) && + intervalTask.isEnable && refreshLimiter_.IsEnableRefresh(intervalTask.formId)) { + intervalTask.refreshTime = currentTime; + updateList.emplace_back(intervalTask); + } + } + + if (!updateList.empty()) { + for (auto &task : updateList) { + ExecTimerTask(task); + } + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Update at timer task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateAtTimerAlarm() +{ + APP_LOGI("%{public}s start", __func__); + struct tm tmAtTime = {0}; + auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + struct tm* ptm = localtime_r(&tt, &tmAtTime); + if (ptm == nullptr) { + APP_LOGE("%{public}s failed, localtime error", __func__); + return false; + } + + int nowAtTime = tmAtTime.tm_hour * Constants::MIN_PER_HOUR + tmAtTime.tm_min; + long currentTime = FormUtil::GetCurrentMillisecond(); + UpdateAtItem findedItem; + bool bFinded = FindNextAtTimerItem(nowAtTime, findedItem); + if (!bFinded) { + if (!updateAtTimerTasks_.empty()) { + APP_LOGW("%{public}s, updateAtTimerTasks_ is not empty", __func__); + return true; + } + ClearUpdateAtTimerResource(); + atTimerWakeUpTime_ = LONG_MAX; + APP_LOGI("%{public}s, no update at task in system now.", __func__); + return true; + } + + int nextWakeUpTime = findedItem.updateAtTime; + tmAtTime.tm_sec = 0; + tmAtTime.tm_hour = findedItem.refreshTask.hour; + tmAtTime.tm_min = findedItem.refreshTask.min; + long selectTime = FormUtil::GetMillisecondFromTm(tmAtTime); + if (selectTime < currentTime) { + tmAtTime.tm_mday += 1; + nextWakeUpTime += (Constants::HOUR_PER_DAY * Constants::MIN_PER_HOUR); + } + + if (nextWakeUpTime == atTimerWakeUpTime_) { + APP_LOGW("%{public}s end, wakeUpTime not change, no need update alarm.", __func__); + return true; + } + + auto timerOption = std::make_shared(); + timerOption->SetType(TIMER_TYPE_RTC_WAKEUP); + timerOption->SetRepeat(false); + timerOption->SetInterval(0); + std::shared_ptr wantAgent = GetUpdateAtWantAgent(findedItem.updateAtTime); + if (wantAgent == nullptr) { + APP_LOGE("%{public}s, failed to create wantAgent.", __func__); + return false; + } + timerOption->SetWantAgent(wantAgent); + + atTimerWakeUpTime_ = nextWakeUpTime; + if (currentUpdateAtWantAgent != nullptr) { + ClearUpdateAtTimerResource(); + } + currentUpdateAtWantAgent = wantAgent; + + updateAtTimerId_ = MiscServices::TimeServiceClient::GetInstance()->CreateTimer(timerOption); + bool bRet = MiscServices::TimeServiceClient::GetInstance()->StartTimer(updateAtTimerId_, + static_cast(selectTime)); + if (!bRet) { + APP_LOGE("%{public}s failed, init update at timer task error", __func__); + return false; + } + + APP_LOGI("%{public}s end", __func__); + return true; +} + +/** + * @brief Get WantAgent. + * @param updateAtTime The next update time. + * @return Returns WantAgent. + */ +std::shared_ptr FormTimerMgr::GetUpdateAtWantAgent(long updateAtTime) +{ + std::shared_ptr want = std::make_shared(); + ElementName element("", "", ""); + want->SetElement(element); + want->SetAction(Constants::ACTION_UPDATEATTIMER); + want->SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_STATIC_UPDATE); + want->SetParam(Constants::KEY_WAKEUP_TIME, updateAtTime); + + std::vector> wants; + wants.emplace_back(want); + WantAgentInfo wantAgentInfo(REQUEST_UPDATE_AT_CODE, WantAgentConstant::OperationType::SEND_COMMON_EVENT, + WantAgentConstant::Flags::UPDATE_PRESENT_FLAG, wants, nullptr); + return WantAgentHelper::GetWantAgent(wantAgentInfo); +} + +/** + * @brief Clear update at timer resource. + */ +void FormTimerMgr::ClearUpdateAtTimerResource() +{ + APP_LOGI("%{public}s start", __func__); + if (updateAtTimerId_ != 0L) { + APP_LOGI("%{public}s clear update at timer start", __func__); + MiscServices::TimeServiceClient::GetInstance()->StopTimer(updateAtTimerId_); + MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(updateAtTimerId_); + APP_LOGI("%{public}s clear update at timer end", __func__); + updateAtTimerId_ = 0L; + } + if (currentUpdateAtWantAgent != nullptr) { + WantAgentHelper::Cancel(currentUpdateAtWantAgent); + currentUpdateAtWantAgent = nullptr; + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Update limiter task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateLimiterAlarm() +{ + APP_LOGI("%{public}s start", __func__); + if (limiterTimerId_ != 0L) { + APP_LOGI("%{public}s clear dynamic timer start", __func__); + MiscServices::TimeServiceClient::GetInstance()->StopTimer(limiterTimerId_); + MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(limiterTimerId_); + APP_LOGI("%{public}s clear dynamic timer end", __func__); + limiterTimerId_ = 0L; + } + + // make limiter wakeup time + struct tm tmAtTime = {0}; + auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + struct tm* ptm = localtime_r(&tt, &tmAtTime); + if (ptm == nullptr) { + APP_LOGE("%{public}s failed, localtime error", __func__); + return false; + } + tmAtTime.tm_sec = Constants::MAX_SECOND; // max value can be 61 + tmAtTime.tm_hour = Constants::MAX_HOUR; + tmAtTime.tm_min = Constants::MAX_MININUTE; + uint64_t limiterWakeUpTime = FormUtil::GetMillisecondFromTm(tmAtTime); + + auto timerOption = std::make_shared(); + timerOption->SetType(TIMER_TYPE_RTC_WAKEUP); + timerOption->SetRepeat(false); + timerOption->SetInterval(0); + std::shared_ptr wantAgent = GetLimiterWantAgent(); + if (wantAgent) { + APP_LOGE("%{public}s, failed to create wantAgent.", __func__); + return false; + } + timerOption->SetWantAgent(wantAgent); + + if (currentLimiterWantAgent != nullptr) { + ClearUpdateAtTimerResource(); + } + currentLimiterWantAgent = wantAgent; + + limiterTimerId_ = MiscServices::TimeServiceClient::GetInstance()->CreateTimer(timerOption); + bool bRet = MiscServices::TimeServiceClient::GetInstance()->StartTimer(limiterTimerId_, + static_cast(limiterWakeUpTime)); + if (!bRet) { + APP_LOGE("%{public}s failed, init limiter timer task error", __func__); + return false; + } + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Clear limiter timer resource. + */ +void FormTimerMgr::ClearLimiterTimerResource() +{ + APP_LOGI("%{public}s start", __func__); + if (limiterTimerId_ != 0L) { + APP_LOGI("%{public}s clear limiter timer start", __func__); + MiscServices::TimeServiceClient::GetInstance()->StopTimer(limiterTimerId_); + MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(limiterTimerId_); + APP_LOGI("%{public}s clear limiter timer end", __func__); + limiterTimerId_ = 0L; + } + if (currentLimiterWantAgent != nullptr) { + WantAgentHelper::Cancel(currentLimiterWantAgent); + currentLimiterWantAgent = nullptr; + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Get WantAgent. + * @return Returns WantAgent. + */ +std::shared_ptr FormTimerMgr::GetLimiterWantAgent() +{ + std::shared_ptr want = std::make_shared(); + ElementName element("", "", ""); + want->SetElement(element); + want->SetAction(Constants::ACTION_UPDATEATTIMER); + want->SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_RESET_LIMIT); + + std::vector> wants; + wants.emplace_back(want); + WantAgentInfo wantAgentInfo(REQUEST_LIMITER_CODE, WantAgentConstant::OperationType::SEND_COMMON_EVENT, + WantAgentConstant::Flags::UPDATE_PRESENT_FLAG, wants, nullptr); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + return WantAgentHelper::GetWantAgent(context, wantAgentInfo); +} + +/** + * @brief Update dynamic refresh task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateDynamicAlarm() +{ + APP_LOGI("%{public}s start", __func__); + if (dynamicRefreshTasks_.empty()) { + ClearDynamicResource(); + dynamicWakeUpTime_ = LONG_MAX; + return true; + } + + bool needUpdate = false; + DynamicRefreshItem firstTask = dynamicRefreshTasks_.at(0); + if (dynamicWakeUpTime_ != firstTask.settedTime) { + dynamicWakeUpTime_ = firstTask.settedTime; + needUpdate = true; + } + + if (!needUpdate) { + APP_LOGE("%{public}s failed, no need to UpdateDynamicAlarm.", __func__); + return true; + } + + auto timerOption = std::make_shared(); + timerOption->SetType(TIMER_TYPE_ELAPSED_REALTIME_WAKEUP); + timerOption->SetRepeat(false); + timerOption->SetInterval(0); + std::shared_ptr wantAgent = GetDynamicWantAgent(dynamicWakeUpTime_); + if (wantAgent) { + APP_LOGE("%{public}s, failed to create wantAgent.", __func__); + return false; + } + timerOption->SetWantAgent(wantAgent); + + if (currentDynamicWantAgent != nullptr) { + ClearDynamicResource(); + } + currentDynamicWantAgent = wantAgent; + + dynamicAlarmTimerId_ = MiscServices::TimeServiceClient::GetInstance()->CreateTimer(timerOption); + bool bRet = MiscServices::TimeServiceClient::GetInstance()->StartTimer(dynamicAlarmTimerId_, + static_cast(dynamicWakeUpTime_)); + if (!bRet) { + APP_LOGE("%{public}s failed, init dynamic timer task error", __func__); + } + + APP_LOGI("%{public}s end", __func__); + + return true; +} +/** + * @brief Get WantAgent. + * @param nextTime The next update time. + * @return Returns WantAgent. + */ +std::shared_ptr FormTimerMgr::GetDynamicWantAgent(long nextTime) +{ + std::shared_ptr want = std::make_shared(); + ElementName element("", "", ""); + want->SetElement(element); + want->SetAction(Constants::ACTION_UPDATEATTIMER); + want->SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_DYNAMIC_UPDATE); + want->SetParam(Constants::KEY_WAKEUP_TIME, nextTime); + std::vector> wants; + wants.emplace_back(want); + WantAgentInfo wantAgentInfo(REQUEST_DYNAMIC_CODE, WantAgentConstant::OperationType::SEND_COMMON_EVENT, + WantAgentConstant::Flags::UPDATE_PRESENT_FLAG, wants, nullptr); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + return WantAgentHelper::GetWantAgent(context, wantAgentInfo); +} + +/** + * @brief Clear dynamic refresh resource. + */ +void FormTimerMgr::ClearDynamicResource() +{ + APP_LOGI("%{public}s start", __func__); + if (dynamicAlarmTimerId_ != 0L) { + APP_LOGI("%{public}s clear dynamic timer start", __func__); + MiscServices::TimeServiceClient::GetInstance()->StopTimer(dynamicAlarmTimerId_); + MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(dynamicAlarmTimerId_); + APP_LOGI("%{public}s clear dynamic timer end", __func__); + dynamicAlarmTimerId_ = 0L; + } + + if (currentDynamicWantAgent != nullptr) { + WantAgentHelper::Cancel(currentDynamicWantAgent); + currentDynamicWantAgent = nullptr; + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Fint next at timer item. + * @param nowTime Update time. + * @param updateAtItem Next at timer item. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::FindNextAtTimerItem(const int nowTime, UpdateAtItem &updateAtItem) +{ + APP_LOGI("%{public}s start", __func__); + if (updateAtTimerTasks_.empty()) { + APP_LOGW("%{public}s, updateAtTimerTasks_ is empty", __func__); + return false; + } + + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->updateAtTime > nowTime) { + updateAtItem = *itItem; + break; + } + } + + if (itItem == updateAtTimerTasks_.end()) { + updateAtItem = updateAtTimerTasks_.front(); + } + APP_LOGI("%{public}s end", __func__); + return true; +} + +/** + * @brief Ensure init interval timer resource. + */ +void FormTimerMgr::EnsureInitIntervalTimer() +{ + if (intervalTimerId_ != 0L) { + return; + } + + APP_LOGI("%{public}s, init base timer task", __func__); + auto timerOption = std::make_shared(); + timerOption->SetType(TIMER_TYPE_ELAPSED_REALTIME); + timerOption->SetRepeat(false); + timerOption->SetInterval(0); + timerOption->SetWantAgent(nullptr); + timerOption->SetCallbackInfo([]() { FormTimerMgr::GetInstance().OnIntervalTimeOut(); }); + + intervalTimerId_ = MiscServices::TimeServiceClient::GetInstance()->CreateTimer(timerOption); + bool bRet = MiscServices::TimeServiceClient::GetInstance()->StartTimer(intervalTimerId_, + static_cast(Constants::MIN_PERIOD)); + if (!bRet) { + APP_LOGE("%{public}s failed, init base timer task error", __func__); + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Clear interval timer resource. + */ +void FormTimerMgr::ClearIntervalTimer() +{ + APP_LOGI("%{public}s start", __func__); + if (intervalTimerId_ != 0L) { + APP_LOGI("%{public}s clear interval timer start", __func__); + MiscServices::TimeServiceClient::GetInstance()->StopTimer(intervalTimerId_); + MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(intervalTimerId_); + intervalTimerId_ = 0L; + APP_LOGI("%{public}s clear interval timer end", __func__); + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Creat thread pool for timer task. + */ + +void FormTimerMgr::CreatTaskThreadExecutor() +{ + APP_LOGI("%{public}s start", __func__); + if (taskExecutor_ == nullptr) { + taskExecutor_ = std::make_unique("timer task thread"); + taskExecutor_->Start(Constants::WORK_POOL_SIZE); + } + APP_LOGI("%{public}s end", __func__); + return; +} + +/** + * @brief Execute Form timer task. + * @param timerTask Form timer task. + */ +void FormTimerMgr::ExecTimerTask(const FormTimer &timerTask) +{ + APP_LOGI("%{public}s start", __func__); + CreatTaskThreadExecutor(); + if (taskExecutor_ != nullptr) { + APP_LOGI("%{public}s run", __func__); + AAFwk::Want want; + if (timerTask.isCountTimer) { + want.SetParam(Constants::KEY_IS_TIMER, true); + } + // multi user + if (IsActiveUser(timerTask.userId)) { + want.SetParam(Constants::PARAM_FORM_USER_ID, timerTask.userId); + } + APP_LOGI("%{public}s, userId:%{public}d", __func__, timerTask.userId); + + auto task = std::bind(&FormProviderMgr::RefreshForm, &FormProviderMgr::GetInstance(), timerTask.formId, want); + taskExecutor_->AddTask(task); + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Init. + */ +void FormTimerMgr::Init() +{ + APP_LOGI("%{public}s start", __func__); + timerReceiver_ = nullptr; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(Constants::ACTION_UPDATEATTIMER); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); + + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + timerReceiver_ = std::make_shared(subscribeInfo); + EventFwk::CommonEventManager::SubscribeCommonEvent(timerReceiver_); + + intervalTimerId_ = 0L; + updateAtTimerId_ = 0L; + dynamicAlarmTimerId_ = 0L; + limiterTimerId_ = 0L; + taskExecutor_ = nullptr; + + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Receiver Constructor. + * @param subscriberInfo Subscriber info. + */ +FormTimerMgr::TimerReceiver::TimerReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo) + : EventFwk::CommonEventSubscriber(subscriberInfo) +{} +/** + * @brief Receive common event. + * @param eventData Common event data. + */ +void FormTimerMgr::TimerReceiver::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + AAFwk::Want want = eventData.GetWant(); + std::string action = want.GetAction(); + + APP_LOGI("%{public}s, action:%{public}s.", __func__, action.c_str()); + + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) { + FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + } else if (action == Constants::ACTION_UPDATEATTIMER) { + int type = want.GetIntParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_STATIC_UPDATE); + if (type == Constants::TYPE_RESET_LIMIT) { + FormTimerMgr::GetInstance().HandleResetLimiter(); + } else if (type == Constants::TYPE_STATIC_UPDATE) { + long updateTime = want.GetLongParam(Constants::KEY_WAKEUP_TIME, -1); + if (updateTime < 0) { + APP_LOGE("%{public}s failed, invalid updateTime:%{public}ld.", __func__, updateTime); + return; + } + FormTimerMgr::GetInstance().OnUpdateAtTrigger(updateTime); + } else if (type == Constants::TYPE_DYNAMIC_UPDATE) { + long updateTime = want.GetLongParam(Constants::KEY_WAKEUP_TIME, 0); + if (updateTime <= 0) { + APP_LOGE("%{public}s failed, invalid updateTime:%{public}ld.", __func__, updateTime); + return; + } + FormTimerMgr::GetInstance().OnDynamicTimeTrigger(updateTime); + } else { + APP_LOGE("%{public}s failed, invalid type when action is update at timer.", __func__); + } + } else { + APP_LOGE("%{public}s failed, invalid action.", __func__); + } +} +/** + * @brief check if user is active or not. + * + * @param userId User ID. + * @return true:active, false:inactive + */ +bool FormTimerMgr::IsActiveUser(const int32_t userId) +{ + bool isOsAccountActived = false; + AccountSA::OsAccountManager::IsOsAccountActived(userId, isOsAccountActived); + return isOsAccountActived; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_util.cpp b/services/formmgr/src/form_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3ae26a8152e4d996e55f44ccde7dcf3184aade6 --- /dev/null +++ b/services/formmgr/src/form_util.cpp @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_util.h" +#include "ohos_account_kits.h" +#include "os_account_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std; +using namespace std::chrono; + +constexpr int64_t SEC_TO_NANOSEC = 1000000000; +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +constexpr int64_t INVALID_UDID_HASH = 0; +/** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ +void FormUtil::CreateFormWant(const std::string &formName, + const int32_t specificationId, const bool isTemporaryForm, Want &want) +{ + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, specificationId); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, isTemporaryForm); +} + +/** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param connectId connect id. + */ +void FormUtil::CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t connectId) +{ + want.SetParam(Constants::FORM_CONNECT_ID, connectId); + want.SetParam(Constants::FORM_SUPPLY_INFO, uri); +} + +/** + * @brief create udid for form. + * @return udid. + */ +std::string FormUtil::GenerateUdid() +{ + char buf[256] = {0}; + return buf; +} + +/** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::GenerateFormId(int64_t udidHash) +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &t); + + int64_t elapsedTime { ((t.tv_sec) * SEC_TO_NANOSEC + t.tv_nsec) }; + size_t elapsedHash = std::hash()(std::to_string(elapsedTime)); + APP_LOGI("%{public}s, GenerateFormId generate elapsed hash %{public}zu", __func__, elapsedHash); + uint64_t unsignedudidHash = static_cast(udidHash); + uint64_t formId = unsignedudidHash | (int32_t)(elapsedHash & 0x000000007fffffffL); + int64_t ret = static_cast(formId); + APP_LOGI("%{public}s, GenerateFormId generate formId %{public}" PRId64 "", __func__, ret); + return ret; +} + +/** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::PaddingUDIDHash(uint64_t formId, uint64_t udidHash) +{ + // Compatible with int form id. + if ((formId & 0xffffffff00000000L) == 0) { + return udidHash | formId; + } + + return formId; +} +/** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ +bool FormUtil::GenerateUdidHash(int64_t &udidHash) +{ + APP_LOGI("%{public}s start, udidHash: %{public}" PRId64 "", __func__, udidHash); + if (udidHash != INVALID_UDID_HASH) { + return true; + } + + u_int64_t hashId = 0L; + const int32_t thirtyTwo = 32; + udidHash = (hashId & 0x0000000000ffffffL) << thirtyTwo; + if (udidHash < 0) { + udidHash = 0L; + } + APP_LOGI("%{public}s, FormAdapter generate hash %{public}" PRId64 "", __func__, udidHash); + + return true; +} +/** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ +long FormUtil::GetCurrentNanosecond() +{ + struct timespec ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_NANOSEC + ts.tv_nsec); +} +/** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ +long FormUtil::GetCurrentMillisecond() +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC); +} +/** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ +long FormUtil::GetMillisecondFromTm(struct tm &tmAtTime) +{ + time_t inputTime = mktime(&tmAtTime); + if (inputTime == -1) { + APP_LOGE("%{public}s fail, mktime failed.", __func__); + return -1; + } + system_clock::time_point pointTime = system_clock::from_time_t(inputTime); + auto timeMilliseconds = chrono::duration_cast(pointTime.time_since_epoch()); + return timeMilliseconds.count(); +} + +/** +* @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ +std::vector FormUtil::StringSplit(const std::string &in, const std::string &delim) +{ + std::regex reg { delim }; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), + std::sregex_token_iterator() + }; +} + +/** + * @brief get current active account id. + * @return int current active account id. + */ +int FormUtil::GetCurrentAccountId() +{ + std::vector osAccountInfos; + ErrCode ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + if (ret != ERR_OK) { + APP_LOGE("QueryAllCreatedOsAccounts failed."); + return 0; + } + + if (osAccountInfos.empty()) { + APP_LOGE("osAccountInfos is empty, no accounts."); + return 0; + } + + for (const auto& account : osAccountInfos) { + if (account.GetIsActived()) { + return account.GetLocalId(); + } + } + APP_LOGE("GetCurrentAccountId failed, no Actived now."); + return 0; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/kvstore_death_recipient_callback.cpp b/services/formmgr/src/kvstore_death_recipient_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ad22bb8ffaa0264703396f9b561ad77225b76f42 --- /dev/null +++ b/services/formmgr/src/kvstore_death_recipient_callback.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "kvstore_death_recipient_callback.h" + +#include +#include + +#include "app_log_wrapper.h" +#include "form_db_cache.h" + +using namespace OHOS::DistributedKv; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t CHECK_TIMES = 300; +const int32_t CHECK_INTERVAL = 100000; // 100ms +} // namespace +KvStoreDeathRecipientCallback::KvStoreDeathRecipientCallback() +{ + APP_LOGI("create kvstore death recipient callback instance %{public}p", this); +} + +KvStoreDeathRecipientCallback::~KvStoreDeathRecipientCallback() +{ + APP_LOGI("destroy kvstore death recipient callback instance %{public}p", this); +} + +void KvStoreDeathRecipientCallback::OnRemoteDied() +{ + APP_LOGI("OnRemoteDied, register data change listener begin"); + + auto dataStorage = FormDbCache::GetInstance().GetDataStorage(); + if (!dataStorage) { + APP_LOGE("dataStorage is nullptr"); + return; + } + + std::thread([dataStorage] { + int32_t times = 0; + while (times < CHECK_TIMES) { + times++; + // init kvStore. + if (dataStorage && dataStorage->ResetKvStore()) { + // register data change listener again. + APP_LOGI("current times is %{public}d", times); + break; + } + usleep(CHECK_INTERVAL); + } + }).detach(); + + APP_LOGI("OnRemoteDied, register data change listener end"); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/test/BUILD.gn b/services/formmgr/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8380a15c303f738836464a6c9a1057bf998bb817 --- /dev/null +++ b/services/formmgr/test/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//foundation/aafwk/standard/aafwk.gni") + +config("formmgr_test_config") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "mock/include", + ] + + configs = [ + "${services_path}/formmgr:formmgr_config", + "${appexecfwk_path}/common:appexecfwk_common_config", + ] +} + +public_configs = [ + ":formmgr_test_config", + "//utils/native/base:utils_config", +] + +public_deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", +] + +group("unittest") { + testonly = true + + deps = [ + "unittest/fms_form_cache_mgr_test:unittest", + "unittest/fms_form_data_mgr_test:unittest", + "unittest/fms_form_db_record_test:unittest", + "unittest/fms_form_host_record_test:unittest", + "unittest/fms_form_info_mgr_test:unittest", + "unittest/fms_form_mgr_add_form_test:unittest", + "unittest/fms_form_mgr_cast_temp_form_test:unittest", + "unittest/fms_form_mgr_death_callback_test:unittest", + "unittest/fms_form_mgr_delete_form_test:unittest", + "unittest/fms_form_mgr_lifecycle_update_test:unittest", + "unittest/fms_form_mgr_message_event_test:unittest", + "unittest/fms_form_mgr_notify_invisible_forms_test:unittest", + "unittest/fms_form_mgr_notify_visible_forms_test:unittest", + "unittest/fms_form_mgr_release_form_test:unittest", + "unittest/fms_form_mgr_request_form_test:unittest", + "unittest/fms_form_mgr_update_form_test:unittest", + "unittest/fms_form_provider_data_test:unittest", + "unittest/fms_form_provider_mgr_test:unittest", + "unittest/fms_form_set_next_refresh_test:unittest", + "unittest/fms_form_sys_event_receiver_test:unittest", + "unittest/fms_form_timer_mgr_test:unittest", + ] +} diff --git a/services/formmgr/test/mock/include/mock_ability_manager.h b/services/formmgr/test/mock/include/mock_ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4fe0fa5f41913f25a0915d618b05dd1813b3ef3f --- /dev/null +++ b/services/formmgr/test/mock/include/mock_ability_manager.h @@ -0,0 +1,865 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H + +#include +#include + +#include "ability_manager_interface.h" +#include "mock_form_provider_client.h" +#include "semaphore_ex.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAbilityMgrProxy : public IRemoteProxy { +public: + explicit MockAbilityMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~MockAbilityMgrProxy() = default; + virtual int UpdateConfiguration(const Configuration &config) override + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) + { + return 0; + } + int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int TerminateAbility( + const sptr &token, int resultCode, const AAFwk::Want *resultWant = nullptr) + { + return 0; + } + virtual int ConnectAbility(const AAFwk::Want &want, const sptr &connect, + const sptr &callerToken, int32_t userId = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int DisconnectAbility(const sptr &connect) + { + return 0; + } + virtual sptr AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) + { + return nullptr; + } + virtual int ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) + { + return 0; + } + virtual void AddWindowInfo(const sptr &token, int32_t windowToken) + { + return; + } + virtual int AttachAbilityThread(const sptr &scheduler, const sptr &token) + { + return 0; + } + virtual int AbilityTransitionDone(const sptr &token, int state, const PacMap &saveData) + { + return 0; + } + virtual int GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) override + { + return 0; + } + virtual int PowerOff() override + { + return 0; + } + virtual int PowerOn() override + { + return 0; + } + virtual int lockMission(int missionId) + { + return 0; + } + virtual int UnlockMission(int missionId) override + { + return 0; + } + virtual int SetMissionDescriptionInfo( + const sptr &token, const AAFwk::MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + virtual int GetMissionLockModeState() override + { + return 0; + } + virtual sptr GetWantSender( + const AAFwk::WantSenderInfo &wantSenderInfo, const sptr &callerToken) override + { + return nullptr; + } + virtual int SendWantSender(const sptr &target, const AAFwk::SenderInfo &senderInfo) override + { + return 0; + } + virtual void CancelWantSender(const sptr &sender) override + { + return; + } + virtual int GetPendingWantUid(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantUserId(const sptr &target) override + { + return 0; + } + virtual std::string GetPendingWantBundleName(const sptr &target) override + { + return ""; + } + virtual int GetPendingWantCode(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantType(const sptr &target) override + { + return 0; + } + virtual void RegisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual void UnregisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual int GetPendingRequestWant(const sptr &target, std::shared_ptr &want) override + { + return 0; + } + virtual int ScheduleConnectAbilityDone(const sptr &token, const sptr &remoteObject) + { + return 0; + } + virtual int ScheduleDisconnectAbilityDone(const sptr &token) + { + return 0; + } + virtual int ScheduleCommandAbilityDone(const sptr &token) + { + return 0; + } + virtual void DumpState(const std::string &args, std::vector &state) + { + return; + } + virtual int TerminateAbilityResult(const sptr &token, int startId) + { + return 0; + } + virtual int StopServiceAbility(const AAFwk::Want &want, int32_t userId = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int GetAllStackInfo(AAFwk::StackInfo &stackInfo) + { + return 0; + } + virtual int GetMissionSnapshot(const int32_t missionId, AAFwk::MissionPixelMap &missionPixelMap) + { + return 0; + } + virtual int MoveMissionToTop(int32_t missionId) + { + return 0; + } + /** + * Requires that tasks associated with a given capability token be moved to the background + * + * @param token ability token + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToEnd(const sptr &token, const bool nonFirst) + { + return 0; + } + virtual int RemoveMission(int id) + { + return 0; + } + virtual int RemoveStack(int id) + { + return 0; + } + virtual int KillProcess(const std::string &bundleName) + { + return 0; + } + virtual int UninstallApp(const std::string &bundleName) + { + return 0; + } + virtual int TerminateAbilityByRecordId(const int64_t recordId = -1) + { + return 0; + } + virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) + { + return 0; + } + /** Checks whether this ability is the first ability in a mission. + * @param lostToken, the token of ability + * @return Returns true is first in Mission. + */ + virtual bool IsFirstInMission(const sptr &token) + { + return 0; + } + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) + { + return 0; + } + + virtual int SetShowOnLockScreen(bool isAllow) override + { + return 0; + } + int StartContinuation(const Want &want, const sptr &abilityToken, int32_t status) override + { + return 0; + } + int NotifyContinuationResult(int32_t missionId, const int32_t result) override + { + return 0; + } + int ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, + int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams) override + { + return 0; + } + int ContinueAbility(const std::string &deviceId, int32_t missionId) override + { + return 0; + } + void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) override + {} + + virtual int LockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int UnlockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int RegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int UnRegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, + std::vector &missionInfos) override + { + return 0; + } + + virtual int GetMissionInfo(const std::string& deviceId, int32_t missionId, + MissionInfo &missionInfo) override + { + return 0; + } + + virtual int CleanMission(int32_t missionId) override + { + return 0; + } + + virtual int CleanAllMissions() override + { + return 0; + } + virtual int MoveMissionToFront(int32_t missionId) override + { + return 0; + } + + virtual int SetMissionLabel(const sptr &token, + const std::string &lable) override + { + return 0; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } +}; + +class MockAbilityMgrStub : public IRemoteStub { +public: + using Uri = OHOS::Uri; + MockAbilityMgrStub() = default; + virtual ~MockAbilityMgrStub() = default; + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override + { + return 0; + } +}; +class MockAbilityMgrService : public MockAbilityMgrStub { +public: + void Wait() + { + sem_.Wait(); + } + + int Post() + { + sem_.Post(); + return 0; + } + + void PostVoid() + { + sem_.Post(); + } + + virtual int UpdateConfiguration(const Configuration &config) override + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) + { + return 0; + } + int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int TerminateAbility( + const sptr &token, int resultCode, const AAFwk::Want *resultWant = nullptr) + { + return 0; + } + virtual int MinimizeAbility(const sptr &token) override + { + return 0; + } + virtual int ConnectAbility(const AAFwk::Want &want, const sptr &connect, + const sptr &callerToken, int32_t userId = DEFAULT_INVAL_VALUE) + { + connect->OnAbilityConnectDone(want.GetElement(), new (std::nothrow) MockFormProviderClient(), 0); + return 0; + } + virtual int DisconnectAbility(const sptr &connect) + { + return 0; + } + virtual sptr AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) + { + return nullptr; + } + virtual int ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) + { + return 0; + } + virtual void AddWindowInfo(const sptr &token, int32_t windowToken) + { + return; + } + virtual int AttachAbilityThread(const sptr &scheduler, const sptr &token) + { + return 0; + } + virtual int AbilityTransitionDone(const sptr &token, int state, const PacMap &saveData) + { + return 0; + } + virtual int ScheduleConnectAbilityDone(const sptr &token, const sptr &remoteObject) + { + return 0; + } + virtual int ScheduleDisconnectAbilityDone(const sptr &token) + { + return 0; + } + virtual int ScheduleCommandAbilityDone(const sptr &token) + { + return 0; + } + virtual void DumpState(const std::string &args, std::vector &state) + { + return; + } + + virtual void DumpSysState( + const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID) + { + return; + } + + virtual int TerminateAbilityResult(const sptr &token, int startId) + { + return 0; + } + virtual int StopServiceAbility(const AAFwk::Want &want, int32_t userId = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int GetAllStackInfo(AAFwk::StackInfo &stackInfo) + { + return 0; + } + virtual int GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) override + { + return 0; + } + virtual int PowerOff() override + { + return 0; + } + virtual int PowerOn() override + { + return 0; + } + virtual int LockMission(int missionId) override + { + return 0; + } + virtual int UnlockMission(int missionId) override + { + return 0; + } + virtual int SetMissionDescriptionInfo( + const sptr &token, const AAFwk::MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + virtual int GetMissionLockModeState() override + { + return 0; + } + virtual sptr GetWantSender( + const AAFwk::WantSenderInfo &wantSenderInfo, const sptr &callerToken) override + { + return nullptr; + } + virtual int SendWantSender(const sptr &target, const AAFwk::SenderInfo &senderInfo) override + { + return 0; + } + virtual void CancelWantSender(const sptr &sender) override + { + return; + } + virtual int GetPendingWantUid(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantUserId(const sptr &target) override + { + return 0; + } + virtual std::string GetPendingWantBundleName(const sptr &target) override + { + return ""; + } + virtual int GetPendingWantCode(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantType(const sptr &target) override + { + return 0; + } + virtual void RegisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual void UnregisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual int GetPendingRequestWant(const sptr &target, std::shared_ptr &want) override + { + return 0; + } + virtual int GetMissionSnapshot(const int32_t missionId, AAFwk::MissionPixelMap &missionPixelMap) + { + return 0; + } + virtual int MoveMissionToTop(int32_t missionId) + { + return 0; + } + /** + * Requires that tasks associated with a given capability token be moved to the background + * + * @param token ability token + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToEnd(const sptr &token, const bool nonFirst) + { + return 0; + } + virtual int RemoveMission(int id) + { + return 0; + } + virtual int RemoveStack(int id) + { + return 0; + } + virtual int KillProcess(const std::string &bundleName) + { + return 0; + } + virtual int UninstallApp(const std::string &bundleName) + { + return 0; + } + virtual int TerminateAbilityByRecordId(const int64_t recordId = -1) + { + return 0; + } + virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) + { + return 0; + } + virtual int SetShowOnLockScreen(bool isAllow) override + { + return 0; + } + int MoveMissionToFloatingStack(const MissionOption &missionOption) + { + return 0; + } + int MoveMissionToSplitScreenStack(const MissionOption &primary, const MissionOption &secondary) + { + return 0; + } + int MinimizeMultiWindow(int missionId) + { + return 0; + } + int MaximizeMultiWindow(int missionId) + { + return 0; + } + int GetFloatingMissions(std::vector &list) + { + return 0; + } + int CloseMultiWindow(int missionId) + { + return 0; + } + int SetMissionStackSetting(const StackSetting &stackSetting) + { + return 0; + } + int StartAbility( + const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) + { + return 0; + } + + /** Checks whether this ability is the first ability in a mission. + * @param lostToken, the token of ability + * @return Returns true is first in Mission. + */ + virtual bool IsFirstInMission(const sptr &token) + { + return 0; + } + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) + { + return 0; + } + + virtual void GetSystemMemoryAttr(AppExecFwk::SystemMemoryAttr &memoryInfo) + {} + + int GetWantSenderInfo(const sptr &target, std::shared_ptr &info) override + { + return 0; + } + int ClearUpApplicationData(const std::string &bundleName) override + { + return 0; + } + virtual int LockMissionForCleanup(int32_t missionId) override + { + return 0; + } + int StartContinuation(const Want &want, const sptr &abilityToken, int32_t status) override + { + return 0; + } + int NotifyContinuationResult(int32_t missionId, const int32_t result) override + { + return 0; + } + int ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, + int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams) override + { + return 0; + } + int ContinueAbility(const std::string &deviceId, int32_t missionId) override + { + return 0; + } + void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) override + {} + + virtual int UnlockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int RegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int UnRegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, + std::vector &missionInfos) override + { + return 0; + } + + virtual int GetMissionInfo(const std::string& deviceId, int32_t missionId, + MissionInfo &missionInfo) override + { + return 0; + } + + virtual int CleanMission(int32_t missionId) override + { + return 0; + } + + virtual int CleanAllMissions() override + { + return 0; + } + + virtual int SetMissionLabel(const sptr &token, + const std::string &lable) override + { + return 0; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } + + virtual int MoveMissionToFront(int32_t missionId) override + { + return 0; + } + virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override + { + return 0; + } + virtual int StopSyncRemoteMissions(const std::string& devId) override + { + return 0; + } + virtual int RegisterMissionListener(const std::string &deviceId, + const sptr &listener) override + { + return 0; + } + virtual int UnRegisterMissionListener(const std::string &deviceId, + const sptr &listener) override + { + return 0; + } + virtual int GetAbilityRunningInfos(std::vector &info) override + { + return 0; + } + virtual int GetExtensionRunningInfos(int upperLimit, std::vector &info) override + { + return 0; + } + virtual int GetProcessRunningInfos(std::vector &info) override + { + return 0; + } + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + virtual bool IsRunningInStabilityTest() override + { + return true; + } + virtual int StartUser(int userId) override + { + return 0; + } + virtual int StopUser(int userId, const sptr &callback) override + { + return 0; + } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) override + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) override + { + return 0; + } + virtual bool SendANRProcessID(int pid) + { + return true; + } + virtual int StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) override + { + return 0; + } + virtual int ReleaseAbility( + const sptr &connect, const AppExecFwk::ElementName &element) override + { + return 0; + } +private: + Semaphore sem_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H diff --git a/services/formmgr/test/mock/include/mock_bundle_manager.h b/services/formmgr/test/mock/include/mock_bundle_manager.h new file mode 100755 index 0000000000000000000000000000000000000000..a4db213117d6cb997f5197a357ebbe0b2cc52082 --- /dev/null +++ b/services/formmgr/test/mock/include/mock_bundle_manager.h @@ -0,0 +1,496 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H +#define OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H + +#include + +#include "ability_info.h" +#include "application_info.h" +#include "bundle_mgr_interface.h" +#include "gmock/gmock.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "ohos/aafwk/content/want.h" + +namespace OHOS { +namespace AppExecFwk { +class BundleMgrProxy : public IRemoteProxy { +public: + explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + virtual ~BundleMgrProxy() + {} + MOCK_METHOD3(CanRequestPermission, + bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + bool(const std::string &bundleName, const std::string &permission, const int userId)); + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override + { + return "AbilityIcon"; + } + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override + { + return true; + } + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override + { + return true; + } + + std::string GetAppType(const std::string &bundleName) override + { + return "system"; + } + + virtual bool GetApplicationInfo(const std::string &appName, const ApplicationFlag flag, const int userId, + ApplicationInfo &appInfo) override + { + return true; + } + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + } + + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override + { + return true; + } + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override + { + if (bundleName.compare("com.form.host.app600") == 0) { + return 600; + } + return 0; + } + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override + { + return ""; + } + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "com.form.provider.service"; + return true; + } + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override + { + return true; + } + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + } + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + } + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + } + + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + } + + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + } + + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + } + + virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override + { + return 0; + } + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + } + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + } + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + } + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + } + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + } + virtual bool IsSafeMode() override + { + return true; + } + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + } + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override + { + return true; + } + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + } + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override + { + return true; + } + virtual sptr GetBundleInstaller() override + { + return nullptr; + } + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } + + /** + * @brief Obtains information about the shortcuts of the application. + * @param bundleName Indicates the name of the bundle to shortcut. + * @param form Indicates the callback a list to shortcutinfo. + * @return Returns true if shortcutinfo get success + */ + virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcut) override + { + return true; + } + + /** + * @brief Obtains the CommonEventInfo objects provided by a event key on the device. + * @param eventKey Indicates the event of the subscribe. + * @param commonEventInfos List of CommonEventInfo objects if obtained. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetAllCommonEventInfo(const std::string &eventKey, + std::vector &commonEventInfos) override + { + return true; + } + + /** + * @brief Obtain the HAP module info of a specific ability. + * @param abilityInfo Indicates the ability. + * @param hapModuleInfo Indicates the obtained HapModuleInfo object. + * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + + virtual bool CheckIsSystemAppByUid(const int uid) override + { + if (uid == 600) { + return false; + } + return true; + } + virtual bool IsApplicationEnabled(const std::string &bundleName)override + { + return true; + } + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + } + + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; + virtual bool GetAllFormsInfo(std::vector &formInfo) override; + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) override; + virtual bool GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfo) override; +}; + +class BundleMgrStub : public IRemoteStub { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +}; + +class BundleMgrService : public BundleMgrStub { +public: + MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); + MOCK_METHOD2(CheckPermission, int(const std::string &bundleName, const std::string &permission)); + MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); + MOCK_METHOD3( + CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + bool(const std::string &bundleName, const std::string &permission, const int userId)); + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; + + std::string GetAppType(const std::string &bundleName) override; + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override; + virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override + { + return "AbilityIcon"; + } + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + }; + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override + { + return true; + }; + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "com.form.provider.service"; + return true; + }; + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override; + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + }; + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + }; + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + }; + // obtains information about an application bundle contained in a ohos Ability Package (HAP). + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + }; + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + // obtains the Want for starting the main ability of an application based on the given bundle name. + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + }; + // checks whether the publickeys of two bundles are the same. + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + }; + // checks whether a specified bundle has been granted a specific permission. + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + }; + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + }; + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + }; + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + }; + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + }; + virtual bool IsSafeMode() override + { + return true; + }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; + + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + }; + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override + { + return true; + }; + virtual sptr GetBundleInstaller() override + { + return nullptr; + }; + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } + virtual bool IsApplicationEnabled(const std::string &bundleName) override + { + return true; + }; + virtual bool CheckIsSystemAppByUid(const int uid) override + { + if (uid == 600) { + return false; + } + + return true; + }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + }; + virtual bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) override + { + return true; + } + virtual bool QueryAbilityInfosByUri(const std::string &abilityUri, std::vector &abilityInfos) override + { + return true; + } + virtual int CheckPermissionByUid( + const std::string &bundleName, const std::string &permission, const int userId) override + { + return true; + } + virtual bool RemoveClonedBundle(const std::string &bundleName, const int32_t uid) override + { + return true; + } + virtual bool BundleClone(const std::string &bundleName) override + { + return true; + } + virtual bool CheckBundleNameInAllowList(const std::string &bundleName) override + { + return true; + } + /** + * @brief Obtains information about the shortcuts of the application. + * @param bundleName Indicates the name of the bundle to shortcut. + * @param form Indicates the callback a list to shortcutinfo. + * @return Returns true if shortcutinfo get success + */ + virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcut) override + { + return true; + } + + /** + * @brief Obtains the CommonEventInfo objects provided by a event key on the device. + * @param eventKey Indicates the event of the subscribe. + * @param commonEventInfos List of CommonEventInfo objects if obtained. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetAllCommonEventInfo(const std::string &eventKey, + std::vector &commonEventInfos) override + { + return true; + } + + virtual bool GetDistributedBundleInfo(const std::string &networkId, int32_t userId, + const std::string &bundleName, DistributedBundleInfo &distributedBundleInfo) override + { + return true; + } + + virtual bool GetAllFormsInfo(std::vector &formInfo) override; + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) override; + virtual bool GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfo) override; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool QueryAbilityInfosForClone(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyAbilityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) override + { + return true; + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H diff --git a/services/formmgr/test/mock/include/mock_form_death_callback.h b/services/formmgr/test/mock/include/mock_form_death_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..55bc225a85dfd9c4938b22da6797fb077fcb84cd --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_death_callback.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_DEATH_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_DEATH_CALLBACK_H + +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "event_handler.h" +#include "form_constants.h" +#include "form_callback_interface.h" +#include "form_mgr_stub.h" +#include "form_js_info.h" +#include "form_provider_data.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class MockFormDeathCallback. + * The MockFormDeathCallback for form mgr test. + */ +class MockFormDeathCallback : public FormCallbackInterface { +public: + MockFormDeathCallback() = default; + virtual ~MockFormDeathCallback() = default; + + void OnDeathReceived() + { + APP_LOGI("%{public}s called.", __func__); + } + + /** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + void ProcessFormUpdate(const FormJsInfo &formJsInfo) + { + APP_LOGI("%{public}s called.", __func__); + } + + /** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ + void ProcessFormUninstall(const int64_t formId) + { + APP_LOGI("%{public}s called.", __func__); + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_DEATH_CALLBACK_H diff --git a/services/formmgr/test/mock/include/mock_form_host_client.h b/services/formmgr/test/mock/include/mock_form_host_client.h new file mode 100644 index 0000000000000000000000000000000000000000..b242c4080ac12d1d2dc01a9772d0c2dfcf34dc94 --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_host_client.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H + +#include +// #include "ability.h" +#include "form_host_stub.h" +#include "iremote_object.h" +#include "iremote_stub.h" +#include "semaphore_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class MockFormHostClient + * MockFormHostClient. + */ +class MockFormHostClient : public FormHostStub { +public: + MockFormHostClient() = default; + virtual ~MockFormHostClient() = default; + + void Wait() + { + sem_.Wait(); + } + + int Post() + { + sem_.Post(); + return 0; + } + + void PostVoid() + { + sem_.Post(); + } + + // void AddForm(const Ability& slice, int64_t formId); + + // void RemoveForm(const Ability& slice, int64_t formId); + + // bool ContainsForm(int64_t formId); + /** + * Request to give back a Form. + * + * @param formId, The Id of the forms to create. + * @param formInfo, Form info. + * @return none. + */ + virtual void OnAcquired(const FormJsInfo &formInfo) override; + + /** + * Form is updated. + * + * @param formId, The Id of the form to update. + * @param formInfo, Form info. + * @return none. + */ + virtual void OnUpdate(const FormJsInfo &formInfo) override; + + /** + * Form provider is uninstalled. + * + * @param formIds, The Id list of the forms. + * @return none. + */ + virtual void OnUninstall(const std::vector &formIds) override; + +private: + +private: + Semaphore sem_; + DISALLOW_COPY_AND_MOVE(MockFormHostClient); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H diff --git a/services/formmgr/test/mock/include/mock_form_provider_client.h b/services/formmgr/test/mock/include/mock_form_provider_client.h new file mode 100644 index 0000000000000000000000000000000000000000..8f8a6857d373b5b5d07ead573ec3f8c5126b905f --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_provider_client.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H + +#include +#include +#include +#include "form_provider_stub.h" + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderStub + * FormProviderStub. + */ +class MockFormProviderClient : public FormProviderStub { +public: + MockFormProviderClient() = default; + virtual ~MockFormProviderClient() = default; + +private: + /** + * Acquire to give back an ProviderFormInfo. This is sync API. + * + * @param want, Indicates the {@link Want} structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * Notify provider when the form was deleted. + * + * @param formId, The Id of the form. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int NotifyFormDelete(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * Notify provider when the form was deleted. + * + * @param formIds, The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + */ + virtual int NotifyFormUpdate(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Event notify when change the form visible. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) override; + + /** + * Notify provider when the temp form was cast to normal form. + * + * @param formId, The Id of the form to update. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) override; + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) override; +private: + DISALLOW_COPY_AND_MOVE(MockFormProviderClient); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H diff --git a/services/formmgr/test/mock/include/mock_form_token.h b/services/formmgr/test/mock/include/mock_form_token.h new file mode 100644 index 0000000000000000000000000000000000000000..ca655e5f44f2ac7e460c7b3cb87af05515551e3b --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_token.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_TOKEN_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_TOKEN_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +class IFormToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormToken"); +}; + +class MockFormToken : public IRemoteStub { +public: + MockFormToken() = default; + virtual ~MockFormToken() = default; + + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + return 0; + } + +private: + DISALLOW_COPY_AND_MOVE(MockFormToken); +}; + +class FormTokenProxy : public IRemoteProxy { +public: + explicit FormTokenProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormTokenProxy() = default; + +private: + DISALLOW_COPY_AND_MOVE(FormTokenProxy); +}; + +DECLARE_INTERFACE_DESCRIPTOR(u"IFormToken"); +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_TOKEN_H diff --git a/services/formmgr/test/mock/include/mock_form_user_manager.h b/services/formmgr/test/mock/include/mock_form_user_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f60c1ad8659f889d26aaf471eab897529c596bc1 --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_user_manager.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_USER_MANAGER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_USER_MANAGER_H + + +#include + +#include "form_info.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "form_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class IFormUserMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormUserMgr"); + /** + * Update form with formId, send formId to form manager service. + * + * @param formId, The Id of the form to update. + * @param bundleName, Provider ability bundleName. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const FmsFormInfo &formInfo) = 0; +}; + +class FormUserMgrProxy : public IRemoteProxy { +public: + explicit FormUserMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + virtual ~FormUserMgrProxy() + {} + /** + * Update form with formId, send formId to form manager service. + * + * @param formId, The Id of the form to update. + * @param bundleName, Provider ability bundleName. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const FmsFormInfo &formInfo) override + { + return ERR_OK; + } +}; + +class FormUserMgrStub : public IRemoteStub { +public: + FormUserMgrStub(); + virtual ~FormUserMgrStub(); + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +private: + int32_t HandleUpdateForm(MessageParcel &data, MessageParcel &reply); +}; + +class FormUserMgrService : public FormUserMgrStub { +public: + void OnStart() override; + void OnStop() override; + + /** + * Update form with formId, send formId to form manager service. + * + * @param formId, The Id of the form to update. + * @param bundleName, Provider ability bundleName. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const FmsFormInfo &formInfo) override + { + return ERR_OK; + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_USER_MANAGER_H diff --git a/services/formmgr/test/mock/src/mock_bundle_manager.cpp b/services/formmgr/test/mock/src/mock_bundle_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1c87bc1dcafffe9f5889ea7368cea890fd033db --- /dev/null +++ b/services/formmgr/test/mock/src/mock_bundle_manager.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "mock_bundle_manager.h" + +#include "ability_info.h" +#include "application_info.h" +#include "form_info.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; +const std::string DEVICE_ID = "ohos-phone1"; + +bool BundleMgrProxy::GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) +{ + return true; +} + +int BundleMgrService::GetUidByBundleName(const std::string &bundleName, const int userId) +{ + if (bundleName.compare("com.form.host.app600") == 0) { + return 600; + } + return 0; +} + +bool BundleMgrProxy::GetAllFormsInfo(std::vector &formInfo) +{ + return true; +} +bool BundleMgrProxy::GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) +{ + return true; +} +bool BundleMgrProxy::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfo) +{ + return true; +} + +int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + return 0; +} + +bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrService::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) +{ + return false; +} + +bool BundleMgrService::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + return true; +} + +std::string BundleMgrService::GetAppType(const std::string &bundleName) +{ + return "system"; +} + +bool BundleMgrService::GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) +{ + std::vector abilityInfos; + ApplicationInfo applicationInfo; + ModuleInfo moduleInfo; + + moduleInfo.moduleSourceDir = FORM_PROVIDER_MODULE_SOURCE_DIR; + moduleInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + bundleInfo.name = bundleName; + applicationInfo.bundleName = bundleName; + applicationInfo.moduleInfos.emplace_back(moduleInfo); + bundleInfo.applicationInfo = applicationInfo; + + bundleInfo.moduleNames.emplace_back(PARAM_PROVIDER_MODULE_NAME); + + AbilityInfo abilityInfo; + abilityInfo.name = FORM_PROVIDER_ABILITY_NAME; + abilityInfo.package = PARAM_PROVIDER_PACKAGE_NAME; + abilityInfo.bundleName = bundleName; + abilityInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + abilityInfo.deviceId = DEVICE_ID; + bundleInfo.abilityInfos.emplace_back(abilityInfo); + + return true; +} +bool BundleMgrService::GetBundleGids(const std::string &bundleName, std::vector &gids) +{ + return true; +} + +bool BundleMgrService::GetAllFormsInfo(std::vector &formInfo) +{ + return true; +} +bool BundleMgrService::GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) +{ + FormInfo form; + form.bundleName = bundleName; + form.abilityName = FORM_PROVIDER_ABILITY_NAME; + form.moduleName = PARAM_PROVIDER_MODULE_NAME; + form.name = PARAM_FORM_NAME; + form.updateEnabled = true; + form.updateDuration = 1; + form.scheduledUpdateTime = "06:06"; + form.jsComponentName = FORM_JS_COMPOMENT_NAME; + form.formVisibleNotify = true; + form.supportDimensions = {1, 2}; + form.defaultDimension = 1; + formInfo.emplace_back(form); + return true; +} +bool BundleMgrService::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfo) +{ + FormInfo form; + form.bundleName = bundleName; + form.abilityName = FORM_PROVIDER_ABILITY_NAME; + form.moduleName = PARAM_PROVIDER_MODULE_NAME; + form.name = PARAM_FORM_NAME; + form.updateEnabled = true; + form.updateDuration = 1; + form.scheduledUpdateTime = "06:06"; + form.jsComponentName = FORM_JS_COMPOMENT_NAME; + form.formVisibleNotify = true; + form.supportDimensions = {1, 2}; + form.defaultDimension = 1; + formInfo.emplace_back(form); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/mock/src/mock_form_host_client.cpp b/services/formmgr/test/mock/src/mock_form_host_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1186c1520670c16475eaddca6631786f8d7aff82 --- /dev/null +++ b/services/formmgr/test/mock/src/mock_form_host_client.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "errors.h" +#include "mock_form_host_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Request to give back a Form. + * + * @param formInfo, Form info. + * @return none. + */ +void MockFormHostClient::OnAcquired(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnAcquired"); + + int64_t formId = formInfo.formId; + ASSERT_FALSE(formId == 0); + PostVoid(); +} + +/** +* Form is updated. +* +* @param bundleName, Provider ability bundleName. +* @return none. +*/ +void MockFormHostClient::OnUpdate(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnUpdate"); + PostVoid(); +} + +/** + * Form provider is uninstalled + * + * @param formIds, The Id list of the forms. + * @return none. + */ +void MockFormHostClient::OnUninstall(const std::vector &formIds) +{ + APP_LOGD("MockFormHostClient OnUnInstall"); + PostVoid(); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/mock/src/mock_form_provider_client.cpp b/services/formmgr/test/mock/src/mock_form_provider_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0d545dedd3bf35983082ade9d309490ce774da4 --- /dev/null +++ b/services/formmgr/test/mock/src/mock_form_provider_client.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "errors.h" +#include "form_constants.h" +#include "form_supply_interface.h" +#include "mock_form_provider_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Acquire to give back an ProviderFormInfo. This is sync API. + * + * @param want, The want of the form to create. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + // avoid the user modify the number in onCreate + + APP_LOGD("Acquire provider form info"); + + sptr formSupply = iface_cast(callerToken); + if (formSupply == nullptr) { + APP_LOGE("failed to get formSupplyProxy"); + } + + FormProviderInfo formProviderInfo; + Want newWant(want); + newWant.SetParam(Constants::ACQUIRE_TYPE, want.GetIntParam(Constants::ACQUIRE_TYPE, 0)); + newWant.SetParam(Constants::FORM_CONNECT_ID, want.GetLongParam(Constants::FORM_CONNECT_ID, 0)); + newWant.SetParam(Constants::FORM_SUPPLY_INFO, want.GetStringParam(Constants::FORM_SUPPLY_INFO)); + newWant.SetParam(Constants::PROVIDER_FLAG, true); + newWant.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, std::to_string(formId)); + formSupply->OnAcquire(formProviderInfo, newWant); + return ERR_OK; +} + +/** + * Notify provider when the form was deleted. + * + * @param formId, The Id of the form. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormDelete(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify form delete"); + return ERR_OK; +} +/** + * Notify provider when the forms was deleted. + * + * @param formIds, The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify forms delete"); + return ERR_OK; +} + +/** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + */ +int MockFormProviderClient::NotifyFormUpdate(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify form update"); + return ERR_OK; +} + +/** + * @brief Event notify when change the form visible. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) +{ + APP_LOGD("Event notify"); + return ERR_OK; +} + +/** + * Notify provider when the temp form was cast to normal form. + * + * @param formId, The Id of the form to update. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify cast temp form"); + return ERR_OK; +} +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Fire form event"); + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/unittest/fms_form_cache_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_cache_mgr_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f0bbfe0cd99554fc1c72dc200d26744fa0a9214a --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_cache_mgr_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormCacheMgrTest") { + module_out_path = module_output_path + + sources = [ "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormCacheMgrTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ca06825e01967358cc3d1bd43ea8dc243f0df56 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#define private public +#include "form_cache_mgr.h" +#undef private + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +const int64_t PARAM_FORM_ID_FIRST = 1001; +const int64_t PARAM_FORM_ID_SECOND = 1002; + +namespace { +class FmsFormCacheMgrTest : public testing::Test { +public: + + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + FormCacheMgr formCacheMgr_; +}; + + +void FmsFormCacheMgrTest::SetUpTestCase() +{} + +void FmsFormCacheMgrTest::TearDownTestCase() +{} + +void FmsFormCacheMgrTest::SetUp() +{} + +void FmsFormCacheMgrTest::TearDown() +{} + +/* + * Feature: FormCacheMgr + * Function: GetData + * FunctionPoints: FormCacheMgr GetData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: invoke GetData works by input key. + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_001, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_001 start"); + + std::string dataResult = ""; + formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST]= "{'a':'1','b':'2'}"; + EXPECT_TRUE(formCacheMgr_.GetData(PARAM_FORM_ID_FIRST, dataResult)); + EXPECT_EQ("{'a':'1','b':'2'}", dataResult); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_001 end"; +} + +/* + * Feature: FormCacheMgr + * Function: GetData + * FunctionPoints: FormCacheMgr GetData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: can not get data by input key. + */ + +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_002, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_002 start"); + + std::string dataResult = ""; + formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST]= "{'a':'1','b':'2'}"; + EXPECT_FALSE(formCacheMgr_.GetData(PARAM_FORM_ID_SECOND, dataResult)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_002 end"; +} + +/* + * Feature: FormCacheMgr + * Function: AddData + * FunctionPoints: FormCacheMgr AddData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: add data by input param. + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_003, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_003 start"); + + std::string dataResult = "{'a':'1','b':'2'}"; + EXPECT_TRUE(formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST], dataResult); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_003 end"; +} + +/* + * Feature: FormCacheMgr + * Function: AddData + * FunctionPoints: FormCacheMgr AddData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: cache contains data and add the new data by input param. + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_004, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_004 start"); + + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + EXPECT_TRUE(formCacheMgr_.AddData(PARAM_FORM_ID_SECOND, dataResult2)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_SECOND], dataResult2); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_004 end"; +} + +/* + * Feature: FormCacheMgr + * Function: AddData + * FunctionPoints: FormCacheMgr AddData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: add data but key conflict + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_010, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_010 start"); + + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + EXPECT_FALSE(formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult2)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_010 end"; +} + +/* + * Feature: FormCacheMgr + * Function: DeleteData + * FunctionPoints: FormCacheMgr DeleteData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: delete data by input key + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_005, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_005 start"); + + std::string dataResult = ""; + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + formCacheMgr_.AddData(PARAM_FORM_ID_SECOND, dataResult2); + EXPECT_TRUE(formCacheMgr_.DeleteData(PARAM_FORM_ID_SECOND)); + EXPECT_FALSE(formCacheMgr_.GetData(PARAM_FORM_ID_SECOND, dataResult)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST], dataResult1); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_005 end"; +} + +/* + * Feature: FormCacheMgr + * Function: DeleteData + * FunctionPoints: FormCacheMgr DeleteData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: delete data but not exsit + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_006, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_006 start"); + + EXPECT_TRUE(formCacheMgr_.DeleteData(PARAM_FORM_ID_SECOND)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_006 end"; +} + +/* + * Feature: FormCacheMgr + * Function: UpdateData + * FunctionPoints: FormCacheMgr UpdateData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: update cache's data by input param + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_007, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_007 start"); + + std::string dataResult = ""; + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + EXPECT_TRUE(formCacheMgr_.UpdateData(PARAM_FORM_ID_FIRST, dataResult2)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST], dataResult2); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_007 end"; +} + +/* + * Feature: FormCacheMgr + * Function: UpdateData + * FunctionPoints: FormCacheMgr UpdateData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: update cache's data but not exsit key + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_008, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_008 start"); + + std::string dataResult1 = "{'a':'1','b':'2'}"; + EXPECT_FALSE(formCacheMgr_.UpdateData(PARAM_FORM_ID_FIRST, dataResult1)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_008 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_data_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_data_mgr_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..db8192f78f54f4e6d21cf90f7644f10ca3cc20af --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/BUILD.gn @@ -0,0 +1,81 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormDataMgrTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + + #"//foundation/appexecfwk/standard/services/bundlemgr/include", + #"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + + #"//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/services/formmgr/test/mock/include", + "//foundation/appexecfwk/appexecfwk_lite/interfaces/kits/bundle_lite", + ] + + configs = [ + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + + #"${libs_path}/libeventhandler:libeventhandler_target", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormDataMgrTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c1d2f67dda94e6d96fdfd83cd25891e414dfd32 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp @@ -0,0 +1,2153 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// #include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#define private public +#include "form_data_mgr.h" +#undef private +#include "form_constants.h" +#include "form_record.h" +#include "mock_form_host_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_NAME = "formName"; + +namespace { +class FmsFormDataMgrTest : public testing::Test { +public: + FmsFormDataMgrTest() + {} + ~FmsFormDataMgrTest() + {} + + void SetUp(); + void TearDown(); + void InitFormItemInfo(int64_t formId, FormItemInfo &form_item_info, bool istemp = true); + +protected: + FormDataMgr formDataMgr_; + sptr token_; +}; + +void FmsFormDataMgrTest::SetUp(void) +{ + // token + token_ = new (std::nothrow) OHOS::AppExecFwk::MockFormHostClient(); +} + +void FmsFormDataMgrTest::TearDown(void) +{ + while (!formDataMgr_.formRecords_.empty()) { + formDataMgr_.formRecords_.erase(formDataMgr_.formRecords_.begin()); + } + if (!formDataMgr_.clientRecords_.empty()) { + formDataMgr_.clientRecords_.erase(formDataMgr_.clientRecords_.begin(), formDataMgr_.clientRecords_.end()); + } + if (!formDataMgr_.tempForms_.empty()) { + formDataMgr_.tempForms_.erase(formDataMgr_.tempForms_.begin(), formDataMgr_.tempForms_.end()); + } + formDataMgr_.udidHash_ = 0; +} + +void FmsFormDataMgrTest::InitFormItemInfo(int64_t formId, FormItemInfo &form_item_info, bool istemp) +{ + // create hapSourceDirs + std::vector hapSourceDirs; + std::string hapSourceDir = "1/2/3"; + hapSourceDirs.emplace_back(hapSourceDir); + + // create form_item_info + form_item_info.SetFormId(formId); + form_item_info.SetTemporaryFlag(istemp); + form_item_info.SetEnableUpdateFlag(true); + form_item_info.SetUpdateDuration(Constants::MIN_CONFIG_DURATION); + form_item_info.SetScheduledUpdateTime("10:30"); + form_item_info.SetHapSourceDirs(hapSourceDirs); +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_001 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * temporaryFlag is true, and tempForms is empty, then create a tempForm. + * formRecords_ is empty, then create formRecords. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_001 start"; + + int64_t formId = 1; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_002 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is include this formId. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_002 start"; + + int64_t formId = 2; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + + // create formRecords + FormRecord record = formDataMgr_.CreateFormRecord(form_item_info, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_003 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not include this formId, then create formRecords. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_003 start"; + + int64_t formId = 3; + int64_t otherformId = 100; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + + // create other FormItemInfo + FormItemInfo otherFormItemInfo; + InitFormItemInfo(otherformId, otherFormItemInfo); + + // create formRecords + FormRecord record = formDataMgr_.CreateFormRecord(otherFormItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(otherformId, record); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_004 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * EnableUpdateFlag is true, + * SetUpdateDuration is not MAX_CONFIG_DURATION.(call ParseIntervalConfig) + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_004 start"; + + int64_t formId = 4; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_004 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_005 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * EnableUpdateFlag is true, + * SetUpdateDuration is between MIN_CONFIG_DURATION and MAX_CONFIG_DURATION.(call ParseIntervalConfig) + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_005 start"; + + int64_t formId = 5; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION-2); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_005 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_006 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为empty + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_006 start"; + + int64_t formId = 6; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + form_item_info.scheduledUpdateTime_.clear(); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_006 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_007 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为无效值 + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_007 start"; + + int64_t formId = 7; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + form_item_info.SetScheduledUpdateTime("10:30:10"); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_007 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_008 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为无效值 + * 不存在hapSourceDirs_ + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_008 start"; + + int64_t formId = 8; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + form_item_info.SetScheduledUpdateTime("10:70"); + form_item_info.hapSourceDirs_.clear(); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_008 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_009 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为有效值 + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_009, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_009 start"; + + int64_t formId = 9; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_009 end"; +} + + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormHostRecord_001 + * @tc.name: AllotFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is include token_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_001 start"; + + int64_t formId = 1; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.AllotFormHostRecord(formItemInfo, token_, formId, callingUid)); + EXPECT_EQ(true, formDataMgr_.clientRecords_.begin()->forms_[formId]); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormHostRecord_002 + * @tc.name: AllotFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not include token_. + * CreateHostRecord is OK. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_002 start"; + + int64_t formId = 2; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + + EXPECT_EQ(true, formDataMgr_.AllotFormHostRecord(formItemInfo, token_, formId, callingUid)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormHostRecord_003 + * @tc.name: AllotFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not include token_. + * CreateHostRecord is NG. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_003 start"; + + int64_t formId = 3; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + + // set callerToken nullptr + token_ = nullptr; + + EXPECT_EQ(false, formDataMgr_.AllotFormHostRecord(formItemInfo, token_, formId, callingUid)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CreateFormInfo_001 + * @tc.name: CreateFormInfo + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CreateFormInfo_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CreateFormInfo_001 start"; + + int64_t formId = 1; + + // create record + FormRecord record; + record.bundleName = FORM_HOST_BUNDLE_NAME; + record.abilityName = FORM_PROVIDER_ABILITY_NAME; + record.formName = FORM_NAME; + record.formTempFlg = true; + + FormJsInfo formInfo; + + formDataMgr_.CreateFormInfo(formId, record, formInfo); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CreateFormInfo_001 output=>bundleName:"< formInfos; + + EXPECT_EQ(false, formDataMgr_.GetFormRecord(bundleName, formInfos)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormRecord_2_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetFormRecord_2_002 + * @tc.name: GetFormRecord_2 + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetFormRecord_2_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormRecord_2_002 start"; + + std::string bundleName = "bundleName"; + std::vector formInfos; + + // create formRecords_ + int64_t formId = 2; + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(bundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(true, formDataMgr_.GetFormRecord(bundleName, formInfos)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormRecord_2_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HasFormUserUids_001 + * @tc.name: HasFormUserUids + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HasFormUserUids_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_001 start"; + + int64_t formId = 1; + + EXPECT_EQ(false, formDataMgr_.HasFormUserUids(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HasFormUserUids_002 + * @tc.name: HasFormUserUids + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HasFormUserUids_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_002 start"; + + int64_t formId = 2; + + // create formRecords_ + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(true, formDataMgr_.HasFormUserUids(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetFormHostRecord_001 + * @tc.name: GetFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetFormHostRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_001 start"; + + int64_t formId = 1; + FormHostRecord formHostRecord; + + EXPECT_EQ(false, formDataMgr_.GetFormHostRecord(formId, formHostRecord)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetFormHostRecord_002 + * @tc.name: GetFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetFormHostRecord_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_002 start"; + + int64_t formId = 2; + FormHostRecord formHostRecord; + + // create clientRecords_ + FormHostRecord form_host_record; + form_host_record.SetClientStub(token_); + form_host_record.AddForm(formId); + formDataMgr_.clientRecords_.push_back(form_host_record); + + EXPECT_EQ(true, formDataMgr_.GetFormHostRecord(formId, formHostRecord)); + EXPECT_EQ(true, formHostRecord.forms_[formId]); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_DeleteHostRecord_001 + * @tc.name: DeleteHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_DeleteHostRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_DeleteHostRecord_001 start"; + + int64_t formId = 1; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.DeleteHostRecord(token_, formId)); + EXPECT_EQ(true, formDataMgr_.clientRecords_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_DeleteHostRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanHostRemovedForms_001 + * @tc.name: CleanHostRemovedForms + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanHostRemovedForms_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanHostRemovedForms_001 start"; + + std::vector removedFormIds; + int64_t formId = 1; + removedFormIds.emplace_back(formId); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + formDataMgr_.CleanHostRemovedForms(removedFormIds); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanHostRemovedForms_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HandleHostDied_001 + * @tc.name: HandleHostDied + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ & tempForms_ & formRecords is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HandleHostDied_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_001 start"; + + int64_t formId = 1; + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(formId); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.HandleHostDied(token_); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HandleHostDied_002 + * @tc.name: HandleHostDied + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * tempForms_ is not match. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HandleHostDied_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_002 start"; + + int64_t formId = 2; + int64_t otherFormId = 3; + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(otherFormId); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.HandleHostDied(token_); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HandleHostDied_003 + * @tc.name: HandleHostDied + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * remoteHost is not match, formRecords is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HandleHostDied_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_003 start"; + + int64_t formId = 3; + + // create clientRecords_ + sptr token_2; + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_2); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.HandleHostDied(token_); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_IsEnableRefresh_001 + * @tc.name: IsEnableRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_IsEnableRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_001 start"; + + int64_t formId = 1; + EXPECT_EQ(false, formDataMgr_.IsEnableRefresh(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_IsEnableRefresh_002 + * @tc.name: IsEnableRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_IsEnableRefresh_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_002 start"; + + int64_t formId = 2; + + // create clientRecords_ + sptr token_; + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.IsEnableRefresh(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GenerateUdidHash_001 + * @tc.name: GenerateUdidHash + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * udidHash_ is not 0. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GenerateUdidHash_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_001 start"; + + formDataMgr_.udidHash_ = 1; + EXPECT_EQ(true, formDataMgr_.GenerateUdidHash()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GenerateUdidHash_002 + * @tc.name: GenerateUdidHash + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * udidHash_ is 0. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GenerateUdidHash_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_002 start"; + + formDataMgr_.udidHash_ = Constants::INVALID_UDID_HASH; + EXPECT_EQ(true, formDataMgr_.GenerateUdidHash()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetMatchedHostClient_001 + * @tc.name: GetMatchedHostClient + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetMatchedHostClient_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_001 start"; + + // create clientRecords_ + FormHostRecord formHostRecord; + + EXPECT_EQ(false, formDataMgr_.GetMatchedHostClient(token_, formHostRecord)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetMatchedHostClient_002 + * @tc.name: GetMatchedHostClient + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetMatchedHostClient_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_002 start"; + + int64_t formId = 2; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + FormHostRecord formHostRecordOutput; + + EXPECT_EQ(true, formDataMgr_.GetMatchedHostClient(token_, formHostRecordOutput)); + EXPECT_EQ(true, formHostRecordOutput.forms_[formId]); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetNeedRefresh_001 + * @tc.name: SetNeedRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetNeedRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_001 start"; + + int64_t formId = 1; + bool needRefresh = true; + + formDataMgr_.SetNeedRefresh(formId, needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetNeedRefresh_002 + * @tc.name: SetNeedRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetNeedRefresh_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_002 start"; + + int64_t formId = 2; + bool needRefresh = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetNeedRefresh(formId, needRefresh); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetCountTimerRefresh_001 + * @tc.name: SetCountTimerRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetCountTimerRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_001 start"; + + int64_t formId = 1; + bool countTimerRefresh = true; + + formDataMgr_.SetCountTimerRefresh(formId, countTimerRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetCountTimerRefresh_002 + * @tc.name: SetCountTimerRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetCountTimerRefresh_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_002 start"; + + int64_t formId = 2; + bool countTimerRefresh = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetCountTimerRefresh(formId, countTimerRefresh); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isCountTimerRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetUpdatedForm_001 + * @tc.name: GetUpdatedForm + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * targetForms is empty. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_001 start"; + + FormRecord record; + record.bundleName = ""; + record.moduleName = ""; + record.abilityName = ""; + record.formName = ""; + record.specification = 0; + + std::vector targetForms; + FormInfo updatedForm; + + EXPECT_EQ(false, formDataMgr_.GetUpdatedForm(record, targetForms, updatedForm)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetUpdatedForm_002 + * @tc.name: GetUpdatedForm + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * targetForms is not empty. record is same as formInfo. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_002 start"; + + int32_t specification = 2; + + FormRecord record; + record.bundleName = FORM_HOST_BUNDLE_NAME; + record.moduleName = PARAM_PROVIDER_MODULE_NAME; + record.abilityName = FORM_PROVIDER_ABILITY_NAME; + record.formName = FORM_NAME; + record.specification = specification; + + std::vector targetForms; + FormInfo formInfo; + formInfo.bundleName = FORM_HOST_BUNDLE_NAME; + formInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + formInfo.abilityName = FORM_PROVIDER_ABILITY_NAME; + formInfo.name = FORM_NAME; + formInfo.supportDimensions.emplace_back(specification); + targetForms.emplace_back(formInfo); + + FormInfo updatedForm; + + EXPECT_EQ(true, formDataMgr_.GetUpdatedForm(record, targetForms, updatedForm)); + EXPECT_EQ(FORM_HOST_BUNDLE_NAME, updatedForm.bundleName); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetUpdatedForm_003 + * @tc.name: GetUpdatedForm + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * targetForms is not empty. record is not same as formInfo. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_003 start"; + + int32_t specification = 3; + + FormRecord record; + record.bundleName = "bundleName"; + record.moduleName = PARAM_PROVIDER_MODULE_NAME; + record.abilityName = FORM_PROVIDER_ABILITY_NAME; + record.formName = FORM_NAME; + record.specification = specification; + + std::vector targetForms; + FormInfo formInfo; + formInfo.bundleName = FORM_HOST_BUNDLE_NAME; + formInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + formInfo.abilityName = FORM_PROVIDER_ABILITY_NAME; + formInfo.name = FORM_NAME; + formInfo.supportDimensions.emplace_back(specification); + targetForms.emplace_back(formInfo); + + FormInfo updatedForm; + + EXPECT_EQ(false, formDataMgr_.GetUpdatedForm(record, targetForms, updatedForm)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetEnableUpdate_001 + * @tc.name: SetEnableUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetEnableUpdate_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_001 start"; + + int64_t formId = 1; + bool enableUpdate = true; + + formDataMgr_.SetEnableUpdate(formId, enableUpdate); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetEnableUpdate_002 + * @tc.name: SetEnableUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetEnableUpdate_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_002 start"; + + int64_t formId = 2; + bool enableUpdate = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetEnableUpdate(formId, enableUpdate); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isEnableUpdate); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetUpdateInfo_001 + * @tc.name: SetUpdateInfo + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetUpdateInfo_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_001 start"; + + int64_t formId = 1; + bool enableUpdate = true; + long updateDuration = 100; + int updateAtHour = 24; + int updateAtMin = 59; + + formDataMgr_.SetUpdateInfo(formId, enableUpdate, updateDuration, updateAtHour, updateAtMin); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetUpdateInfo_002 + * @tc.name: SetUpdateInfo + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetUpdateInfo_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_002 start"; + + int64_t formId = 1; + bool enableUpdate = true; + long updateDuration = 100; + int updateAtHour = 24; + int updateAtMin = 59; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetUpdateInfo(formId, enableUpdate, updateDuration, updateAtHour, updateAtMin); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isEnableUpdate); + EXPECT_EQ(100, formDataMgr_.formRecords_.find(formId)->second.updateDuration); + EXPECT_EQ(24, formDataMgr_.formRecords_.find(formId)->second.updateAtHour); + EXPECT_EQ(59, formDataMgr_.formRecords_.find(formId)->second.updateAtMin); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedFormRecords_001 + * @tc.name: CleanRemovedFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * removedForm is matched with formRecords_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedFormRecords_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_001 start"; + + // create formRecords + int callingUid = 0; + int64_t formId = 1; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set removedForms; + int64_t removedForm = formId; + removedForms.emplace(removedForm); + + formDataMgr_.CleanRemovedFormRecords(bundleName, removedForms); + EXPECT_EQ(true, formDataMgr_.formRecords_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedFormRecords_002 + * @tc.name: CleanRemovedFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * removedForm is not matched with formRecords_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedFormRecords_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_002 start"; + + // create formRecords + int callingUid = 0; + int64_t formId = 2; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set removedForms; + int64_t removedForm = 100; + removedForms.emplace(removedForm); + + formDataMgr_.CleanRemovedFormRecords(bundleName, removedForms); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedTempFormRecords_001 + * @tc.name: CleanRemovedTempFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * bundleName is matched with formRecords_, and it is temp. + * erase formRecords_ and tempForms_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedTempFormRecords_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_001 start"; + + int64_t formId = 1; + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set removedForms; + int64_t removedForm = formId; + removedForms.emplace(removedForm); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(bundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(formId); + + formDataMgr_.CleanRemovedTempFormRecords(bundleName, removedForms); + EXPECT_EQ(true, formDataMgr_.formRecords_.empty()); + EXPECT_EQ(true, formDataMgr_.tempForms_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedTempFormRecords_002 + * @tc.name: CleanRemovedTempFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * bundleName is not matched with formRecords_. + * erase none. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedTempFormRecords_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_002 start"; + + int64_t formId = 2; + std::string bundleName = FORM_HOST_BUNDLE_NAME; + std::string otherBundleName = "bundleName"; + + std::set removedForms; + int64_t removedForm = formId; + removedForms.emplace(removedForm); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(otherBundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(formId); + + formDataMgr_.CleanRemovedTempFormRecords(bundleName, removedForms); + EXPECT_EQ(false, formDataMgr_.formRecords_.empty()); + EXPECT_EQ(false, formDataMgr_.tempForms_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001 + * @tc.name: GetReCreateFormRecordsByBundleName + + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001 start"; + + int64_t formId = 1; + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set reCreateForms; + int64_t reCreateForm = formId; + reCreateForms.emplace(reCreateForm); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(bundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.GetReCreateFormRecordsByBundleName(bundleName, reCreateForms); + EXPECT_EQ(true, reCreateForms.count(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetFormCacheInited_001 + * @tc.name: SetFormCacheInited + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetFormCacheInited_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_001 start"; + + int64_t formId = 1; + + formDataMgr_.SetFormCacheInited(formId, true); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetFormCacheInited_002 + * @tc.name: SetFormCacheInited + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetFormCacheInited_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_002 start"; + + int64_t formId = 2; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetFormCacheInited(formId, true); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isInited); + EXPECT_EQ(false, formDataMgr_.formRecords_.find(formId)->second.needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetVersionUpgrade_001 + * @tc.name: SetVersionUpgrade + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetVersionUpgrade_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_001 start"; + + int64_t formId = 1; + bool version = true; + + formDataMgr_.SetVersionUpgrade(formId, version); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetVersionUpgrade_002 + * @tc.name: SetFormCacheInited + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetVersionUpgrade_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_002 start"; + + int64_t formId = 2; + bool versionUpgrade = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetVersionUpgrade(formId, versionUpgrade); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.versionUpgrade); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostNeedRefresh_001 + * @tc.name: UpdateHostNeedRefresh + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostNeedRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostNeedRefresh_001 start"; + + int64_t formId = 1; + bool needRefresh = true; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + formDataMgr_.UpdateHostNeedRefresh(formId, needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostNeedRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostForm_001 + * @tc.name: UpdateHostForm + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostForm_001 start"; + + int64_t formId = 1; + FormRecord formRecord; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.UpdateHostForm(formId, formRecord)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostForm_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_001 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not exit. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_001 start"; + + std::vector formIds; + int64_t formId = 1; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_002 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords's VersionUpgrade is false. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_002 start"; + + std::vector formIds; + int64_t formId = 2; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // SetNeedRefresh:true + formHostRecord.SetNeedRefresh(formId, true); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + // versionUpgrade : false + formDataMgr_.SetVersionUpgrade(formId, false); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_003 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords's VersionUpgrade is true. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_003 start"; + + std::vector formIds; + int64_t formId = 3; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // SetNeedRefresh:true + formHostRecord.SetNeedRefresh(formId, true); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + // versionUpgrade : true + formDataMgr_.SetVersionUpgrade(formId, true); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_004 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_'s NeedRefresh is false. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_004 start"; + + std::vector formIds; + int64_t formId = 4; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // SetNeedRefresh:false + formHostRecord.SetNeedRefresh(formId, false); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_004 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_005 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not include formId. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_005 start"; + + std::vector formIds; + int64_t formId = 5; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + int64_t otherformId = 500; + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(otherformId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_005 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_006 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * flag is false. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_006 start"; + + std::vector formIds; + int64_t formId = 6; + formIds.emplace_back(formId); + + bool flag = false; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_006 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_007 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords's needRefresh is true. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_007 start"; + + std::vector formIds; + int64_t formId = 7; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + // needRefresh:true + record.needRefresh = true; + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_007 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_008 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is not include formId. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_008 start"; + + std::vector formIds; + int64_t formId = 8; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int64_t otherFormId = 800; + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(otherFormId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(otherFormId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_008 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_db_record_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_db_record_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e42ba7196e320ffe39ed1034c971645e8d0f67b4 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_db_record_test/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormDbRecordTest") { + module_out_path = module_output_path + + sources = [ "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp" ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + + #"//foundation/appexecfwk/standard/services/bundlemgr/include", + #"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + + #"//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + + #"${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormDbRecordTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09f6455fd8ce5bea917faa610da328cec2b152c1 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// #include +#include +#include +#include +#include "app_log_wrapper.h" +#define private public +#include "form_db_cache.h" +#include "form_mgr_adapter.h" +#include "form_storage_mgr.h" +#undef private +#include "form_record.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +class FmsFormDbRecordTest : public testing::Test { +public: + void InitFormRecord(); + FormRecord formRecord_; + FormMgrAdapter formMgrAdapter_; +}; + +void FmsFormDbRecordTest::InitFormRecord() +{ + formRecord_.isInited = false; + formRecord_.needFreeInstall = false; + formRecord_.versionUpgrade = false; + formRecord_.needRefresh = false; + formRecord_.packageName = "TestPackageName"; + formRecord_.bundleName = "TestBundleName"; + formRecord_.moduleName = "TestModuleName"; + formRecord_.abilityName = "TestAbilityName"; + formRecord_.formName = "TestFormName"; + formRecord_.specification = 0; + formRecord_.isEnableUpdate = false; + formRecord_.updateDuration = 0; + formRecord_.updateAtHour = 0; + formRecord_.updateAtMin = 0; + formRecord_.hapSourceDirs.emplace_back("hapSourceDirs1"); + formRecord_.formName = "formNameTest"; + formRecord_.formTempFlg = false; + formRecord_.formUserUids.emplace_back(1); + formRecord_.formVisibleNotify = false; + formRecord_.formVisibleNotifyState = 0; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_001, TestSize.Level0) // create +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_001 start"; + FormDbCache::GetInstance().Start(); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_001 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_002, TestSize.Level0) // save formId 0, callIds[1] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_002 start"; + InitFormRecord(); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(0, formRecord_)); + FormDbCache::GetInstance().DeleteFormInfo(0); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_002 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_003, TestSize.Level0) // save formId 1, callIds[1, 0] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_003 start"; + InitFormRecord(); + formRecord_.formUserUids.emplace_back(0); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(1, formRecord_)); + FormDbCache::GetInstance().DeleteFormInfo(1); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_003 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_004, TestSize.Level0) // modify formId 1, callIds[1,2] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_004 start"; + InitFormRecord(); + formRecord_.formUserUids.emplace_back(2); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(1, formRecord_)); + FormDbCache::GetInstance().DeleteFormInfo(1); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_004 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_005, TestSize.Level0) // modify formId 0, callIds[1,2] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_005 start"; + InitFormRecord(); + formRecord_.formUserUids.emplace_back(2); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(0, formRecord_)); + FormDbCache::GetInstance().DeleteFormInfo(0); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_005 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_006, TestSize.Level0) // GetAllDBRecord +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 start"; + InitFormRecord(); + formRecord_.formUserUids.emplace_back(2); + FormDbCache::GetInstance().UpdateDBRecord(1, formRecord_); + FormDbCache::GetInstance().UpdateDBRecord(0, formRecord_); + + FormRecord record; + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(0, record)); + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formUserUids:" << record.formUserUids[j]; + } + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 -------------------"; + + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(1, record)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formUserUids:" << record.formUserUids[j]; + } + FormDbCache::GetInstance().DeleteFormInfo(0); + FormDbCache::GetInstance().DeleteFormInfo(1); + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_007, TestSize.Level0) // GetAllDBRecord +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 start"; + + InitFormRecord(); + FormDbCache::GetInstance().UpdateDBRecord(0, formRecord_); + formRecord_.formUserUids.emplace_back(0); + FormDbCache::GetInstance().UpdateDBRecord(1, formRecord_); + + FormRecord record; + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(0, record)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 formUserUids:" << record.formUserUids[j]; + } + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 -------------------"; + + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(1, record)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 formUserUids:" << record.formUserUids[j]; + } + FormDbCache::GetInstance().DeleteFormInfo(0); + FormDbCache::GetInstance().DeleteFormInfo(1); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_008, TestSize.Level0) // DeleteDbRecord(1) +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_008 start"; + InitFormRecord(); + FormDbCache::GetInstance().UpdateDBRecord(2, formRecord_); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().DeleteFormInfo(2)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_008 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_host_record_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e1fb2b0f64b5cea2d44785ef57ebe80d89ec8d02 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_host_record_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormHostRecordTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_host_record_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormHostRecordTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b29e51a9f858eec7b2c2ec176467de61ad1a13b --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormHostRecordTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormHostRecordTest::SetUpTestCase() +{} + +void FmsFormHostRecordTest::TearDownTestCase() +{} + +void FmsFormHostRecordTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormHostRecordTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormHostRecord + * SubFunction: OnRemoteDied Function + * FunctionPoints: FormMgr OnRemoteDied interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is not 0 after remote died. + */ +HWTEST_F(FmsFormHostRecordTest, OnRemoteDied_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_host_record_test_001 start"; + + int64_t formId1 {12001}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId1); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + int64_t formId2 {12002}; + FormItemInfo record2; + record2.SetFormId(formId2); + record2.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record2.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(record2, callingUid); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId1, callingUid); + + FormHostRecord hostRecord; + FormDataMgr::GetInstance().GetFormHostRecord(formId1, hostRecord); + hostRecord.GetDeathRecipient()->OnRemoteDied(token_); + + FormDataMgr::GetInstance().DeleteFormRecord(formId1); + FormDataMgr::GetInstance().DeleteFormRecord(formId2); + FormDataMgr::GetInstance().ClearHostDataByUId(callingUid); + + GTEST_LOG_(INFO) << "fms_form_host_record_test_001 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_info_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_info_mgr_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..09711d62e828079eb107dc1a95198aa23f5b70b5 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_info_mgr_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormInfoMgrTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_info_mgr_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormInfoMgrTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_info_mgr_test/fms_form_info_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_info_mgr_test/fms_form_info_mgr_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d28488cb5236917b15b3c631906e47516d427bf --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_info_mgr_test/fms_form_info_mgr_test.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "extension_form_profile.h" +#include "nlohmann/json.hpp" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string JSON_NONE; +const std::string JSON_EMPTY = "{}"; +const nlohmann::json JSON_BAD_FORMS = R"({"forms":""})"_json; +const nlohmann::json JSON_EMPTY_FORMS = R"({"forms":[]})"_json; +const nlohmann::json JSON_FORMS = R"( +{ + "forms": [ + { + "name": "Form_001", + "description": "$string:form_description", + "src": "./js/pages/card/index", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "formConfigAbility": "ability://form_ability_001", + "formVisibleNotify": false, + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 1, + "defaultDimension": "2*2", + "supportDimensions": ["2*2"], + "metadata": [ + { + "name": "string", + "value": "string" + } + ] + }, { + "name": "Form_002", + "formConfigAbility": "ability://form_ability_002", + "isDefault": true, + "updateEnabled": true, + "defaultDimension": "2*2", + "supportDimensions": ["2*2"] + } + ] +})"_json; +const int32_t JSON_FORMS_NUM = 2; + +std::string JsonToString(const nlohmann::json &json) +{ + std::ostringstream stream; + stream << json.dump(); + return stream.str(); +} + +HWTEST(ExtensionFormProfileTest, TransformTo_0100, TestSize.Level0) +{ + std::vector extensionFormInfos {}; + // none profile + EXPECT_EQ(ERR_APPEXECFWK_PARSE_BAD_PROFILE, ExtensionFormProfile::TransformTo(JSON_NONE, extensionFormInfos)); + EXPECT_EQ(0, extensionFormInfos.size()); + // empty profile + EXPECT_EQ(ERR_OK, ExtensionFormProfile::TransformTo(JSON_EMPTY, extensionFormInfos)); + EXPECT_EQ(0, extensionFormInfos.size()); + // bad forms profile + EXPECT_EQ(ERR_APPEXECFWK_PARSE_PROFILE_PROP_TYPE_ERROR, + ExtensionFormProfile::TransformTo(JsonToString(JSON_BAD_FORMS), extensionFormInfos)); + EXPECT_EQ(0, extensionFormInfos.size()); + // empty forms profile + EXPECT_EQ(ERR_OK, ExtensionFormProfile::TransformTo(JsonToString(JSON_EMPTY_FORMS), extensionFormInfos)); + EXPECT_EQ(0, extensionFormInfos.size()); + // forms ok profile + EXPECT_EQ(ERR_OK, ExtensionFormProfile::TransformTo(JsonToString(JSON_FORMS), extensionFormInfos)); + EXPECT_EQ(JSON_FORMS_NUM, extensionFormInfos.size()); +} + +HWTEST(ExtensionFormProfileTest, TransformTo_0101, TestSize.Level0) +{ + std::vector extensionFormInfos {}; + int32_t numForms = 0; + + std::vector notMustPropKeys = { + ExtensionFormProfileReader::DESCRIPTION, + ExtensionFormProfileReader::SRC, + ExtensionFormProfileReader::WINDOW, + ExtensionFormProfileReader::COLOR_MODE, + ExtensionFormProfileReader::FORM_VISIBLE_NOTIFY, + ExtensionFormProfileReader::SCHEDULED_UPDATE_TIME, + ExtensionFormProfileReader::UPDATE_DURATION, + ExtensionFormProfileReader::METADATA + }; + for (const auto &prop: notMustPropKeys) { + nlohmann::json formsJson = JSON_FORMS; + formsJson[ExtensionFormProfileReader::FORMS][0].erase(prop); + numForms += JSON_FORMS_NUM; + EXPECT_EQ(ERR_OK, ExtensionFormProfile::TransformTo(JsonToString(formsJson), extensionFormInfos)); + EXPECT_EQ(numForms, extensionFormInfos.size()); + } + + std::vector mustPropKeys = { + ExtensionFormProfileReader::NAME, + ExtensionFormProfileReader::FORM_CONFIG_ABILITY, + ExtensionFormProfileReader::IS_DEFAULT, + ExtensionFormProfileReader::UPDATE_ENABLED, + ExtensionFormProfileReader::DEFAULT_DIMENSION, + ExtensionFormProfileReader::SUPPORT_DIMENSIONS + }; + for (const auto &prop: mustPropKeys) { + nlohmann::json errorJson = JSON_FORMS; + errorJson[ExtensionFormProfileReader::FORMS][0].erase(prop); + EXPECT_EQ(ERR_APPEXECFWK_PARSE_PROFILE_MISSING_PROP, + ExtensionFormProfile::TransformTo(JsonToString(errorJson), extensionFormInfos)); + EXPECT_EQ(numForms, extensionFormInfos.size()); + } +} + +HWTEST(ExtensionFormProfileTest, TransformTo_0102, TestSize.Level0) +{ + std::vector extensionFormInfos {}; + int32_t numForms = 0; + + // name + nlohmann::json errorJson = JSON_FORMS; + errorJson[ExtensionFormProfileReader::FORMS][0][ExtensionFormProfileReader::NAME] = ""; + EXPECT_EQ(ERR_APPEXECFWK_PARSE_PROFILE_PROP_CHECK_ERROR, + ExtensionFormProfile::TransformTo(JsonToString(errorJson), extensionFormInfos)); + EXPECT_EQ(numForms, extensionFormInfos.size()); + // max name size + const int32_t maxFormName = 128; + std::string maxName(maxFormName, 'a'); + errorJson[ExtensionFormProfileReader::FORMS][0][ExtensionFormProfileReader::NAME] = maxName; + EXPECT_EQ(ERR_APPEXECFWK_PARSE_PROFILE_PROP_CHECK_ERROR, + ExtensionFormProfile::TransformTo(JsonToString(errorJson), extensionFormInfos)); + EXPECT_EQ(numForms, extensionFormInfos.size()); +} + +HWTEST(ExtensionFormProfileTest, TransformTo_0103, TestSize.Level0) +{ + std::vector extensionFormInfos {}; + int32_t numForms = 0; + + // dimension + nlohmann::json errorJson = JSON_FORMS; + const std::string invalidDimension = "1*4"; + errorJson[ExtensionFormProfileReader::FORMS][0][ExtensionFormProfileReader::DEFAULT_DIMENSION] = invalidDimension; + errorJson[ExtensionFormProfileReader::FORMS][0][ExtensionFormProfileReader::SUPPORT_DIMENSIONS].push_back( + invalidDimension); + EXPECT_EQ(ERR_APPEXECFWK_PARSE_PROFILE_PROP_CHECK_ERROR, + ExtensionFormProfile::TransformTo(JsonToString(errorJson), extensionFormInfos)); + EXPECT_EQ(numForms, extensionFormInfos.size()); + + // not in support + errorJson = JSON_FORMS; + const std::string validDimension = "1*2"; + errorJson[ExtensionFormProfileReader::FORMS][0][ExtensionFormProfileReader::DEFAULT_DIMENSION] = validDimension; + EXPECT_EQ(ERR_APPEXECFWK_PARSE_PROFILE_PROP_CHECK_ERROR, + ExtensionFormProfile::TransformTo(JsonToString(errorJson), extensionFormInfos)); +} +} // namespace diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..87389585e973c9100502d8e0c774bb0ec456b0c8 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn @@ -0,0 +1,89 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrAddFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_add_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "//foundation/appexecfwk/standard/services/bundlemgr/test:bundlemgr_test_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${appexecfwk_path}/services/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrAddFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6cad4e0edc7752ef33a9b13b06a592dae3d3e5f --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp @@ -0,0 +1,557 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#define private public +#include "form_data_mgr.h" +#undef private +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrAddFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrAddFormTest::SetUpTestCase() +{} + +void FmsFormMgrAddFormTest::TearDownTestCase() +{} + +void FmsFormMgrAddFormTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrAddFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke AddForm works. + */ + +HWTEST_F(FmsFormMgrAddFormTest, AddForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_001 start"; + // No cache + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + // clear old data + FormDataMgr::GetInstance().ClearFormRecords(); + std::vector oldFormDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(oldFormDBInfos); + FormDbCache::GetInstance().DeleteFormInfoByBundleName(FORM_PROVIDER_BUNDLE_NAME, oldFormDBInfos); + + // add form + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); + token_->Wait(); + + size_t dataCnt{1}; + int64_t formId = formJsInfo.formId; + // Form record alloted. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database info alloted. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // Form host record alloted. + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Add form with cache info. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_002 start"; + + int64_t formId = 0x0ffabcff00000000; + int callingUid {0}; + // Set cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetModuleName(PARAM_PROVIDER_MODULE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + retFormRec.updateAtHour = 1; + retFormRec.updateAtMin = 1; + FormDataMgr::GetInstance().UpdateFormRecord(formId, retFormRec); + // Set database info + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormDataMgr::GetInstance().AllotFormHostRecord(record1, token_, formId, callingUid); + + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + GTEST_LOG_(INFO) << "formId :"<Wait(); + + size_t dataCnt{1}; + size_t formUserUidCnt{1}; + // Cache params updated. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(formUserUidCnt, formInfo.formUserUids.size()); + // database info updated. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(formUserUidCnt, dbInfo.formUserUids.size()); + // Form host record not changed. + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_002 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Add form with database info but without cache. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_003 start"; + + int64_t formId = 0x0ffabcdf00000000; + int callingUid {0}; + // Set database info + FormRecord record1; + record1.formId = formId; + record1.bundleName = FORM_PROVIDER_BUNDLE_NAME; + record1.moduleName = PARAM_FORM_NAME; + record1.abilityName = FORM_PROVIDER_ABILITY_NAME; + record1.formName = PARAM_FORM_NAME; + record1.specification = PARAM_FORM_DIMENSION_VALUE; + record1.formUserUids.emplace_back(callingUid); + record1.formTempFlg = false; + FormDBInfo formDBInfo(formId, record1); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + GTEST_LOG_(INFO) << "formId :"<Wait(); + + size_t dataCnt{1}; + size_t formUserUidCnt{1}; + // Cache params updated. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(formUserUidCnt, formInfo.formUserUids.size()); + // databse info updated. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(formUserUidCnt, dbInfo.formUserUids.size()); + // Form host record not changed. + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Invalid case when callertoken is nullptr. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_004 start"; + + int64_t formId = 0x0ffabcde00000000; + + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: BundleName,AbilityName,moduleName in Want is null separately. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_005 start"; + + int64_t formId = 0x0ffabcdd00000000; + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, "", FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, ""); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + std::string tmp = ""; + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, tmp); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_005 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case when cache info is not matched with form. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_006 start"; + + int64_t formId = 0x0ababcff00000000; + int callingUid {0}; + // Set cache info . + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_ABILITY_NAME); + record1.SetModuleName(PARAM_FORM_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record. + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, 111L, callingUid); + + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + GTEST_LOG_(INFO) << "formId :"<Wait(); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_006 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case when temp form is out of limit. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_007 start"; + + int64_t formId = 0x0ababc5f00000000; + int callingUid {0}, tempCount = 0; + // Set cache info . + FormItemInfo record1[OHOS::AppExecFwk::Constants::MAX_TEMP_FORMS]; + for (; tempCountWait(); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + for (tempCount = 0; tempCount oldFormDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(oldFormDBInfos); + FormDbCache::GetInstance().DeleteFormInfoByBundleName(FORM_PROVIDER_BUNDLE_NAME, oldFormDBInfos); + + int64_t formId = 0x0ab5bc5f00000000; + int callingUid {0}, tempCount = 0; + // Set cache info . + FormItemInfo record1[Constants::MAX_FORMS+7]; + for (; tempCountWait(); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + for (tempCount = 0; tempCount + +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrCastTempFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrCastTempFormTest::SetUpTestCase() +{} + +void FmsFormMgrCastTempFormTest::TearDownTestCase() +{} + +void FmsFormMgrCastTempFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrCastTempFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke CastTempForm works. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_001 start"; + + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + int callingUid {1}; + // cache info + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetModuleName(PARAM_FORM_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(true); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // host object + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + ASSERT_EQ(ERR_OK, FormMgr::GetInstance().CastTempForm(formId, token_)); + token_->Wait(); + + size_t dataCnt {1}; + // form record is updated + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t userUidCnt {2}; + EXPECT_EQ(userUidCnt, formInfo.formUserUids.size()); + // db data is added + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(userUidCnt, dbInfo.formUserUids.size()); + // host is added + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: form id <= 0 or Caller ability token is nullptr. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 start"; + // form id <= 0 + ASSERT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(0L, token_)); + // Caller ability token is nullptr + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + ASSERT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(formId, nullptr)); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Temp form is not in form cache. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 start"; + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + // form is not exist in cache + ASSERT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().CastTempForm(formId, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Temp form is not in host. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_004 start"; + + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + int callingUid {1}; + // cache data + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetModuleName(PARAM_FORM_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(true); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + + ASSERT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().CastTempForm(formId, token_)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_004 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c6195f2cf8768704d30177aa8d99c9cca0d7402f --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn @@ -0,0 +1,90 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrDeathCallbackTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + + # "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_death_callback.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_death_callback_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${appexecfwk_path}/services/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrDeathCallbackTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9b45712fd4874fd9d63f026fffb4bbe1efa2395 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#define private public +#include "form_data_mgr.h" +#undef private +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_death_callback.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrDeathCallbackTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrDeathCallbackTest::SetUpTestCase() +{} + +void FmsFormMgrDeathCallbackTest::TearDownTestCase() +{} + +void FmsFormMgrDeathCallbackTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrDeathCallbackTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr::FormMgrDeathRecipient + * SubFunction: OnRemoteDied Function + * FunctionPoints: FormMgr::FormMgrDeathRecipient OnRemoteDied interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr::FormMgrDeathRecipient invoke OnRemoteDied works. + */ +HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_001 start"; + // No cache + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME) + .SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME) + .SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE) + .SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false) + .SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); + token_->Wait(); + + std::shared_ptr deathCallback = std::make_shared(); + FormMgr::GetInstance().RegisterDeathCallback(deathCallback); + EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); + FormMgr::GetInstance().GetDeathRecipient()->OnRemoteDied(formyMgrServ_->AsObject()); + + int64_t formId = formJsInfo.formId; + + FormHostRecord hostRecord; + EXPECT_EQ(true, FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + EXPECT_EQ(true, token_->AsObject() == hostRecord.clientStub_); + EXPECT_EQ(true, FormMgr::GetRecoverStatus() == Constants::NOT_IN_RECOVERY); + + FormMgr::GetInstance().UnRegisterDeathCallback(deathCallback); + EXPECT_EQ(false, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr::FormMgrDeathRecipient + * SubFunction: OnRemoteDied Function + * FunctionPoints: FormMgr::FormMgrDeathRecipient OnRemoteDied interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr::FormMgrDeathRecipient invoke OnRemoteDied works when remote is nullptr. + */ +HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_002 start"; + // No cache + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME) + .SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME) + .SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE) + .SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false) + .SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); + token_->Wait(); + + std::shared_ptr deathCallback = std::make_shared(); + FormMgr::GetInstance().RegisterDeathCallback(deathCallback); + EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); + + int beforeRecoverStatus = FormMgr::GetRecoverStatus(); + FormMgr::GetInstance().GetDeathRecipient()->OnRemoteDied(nullptr); + EXPECT_EQ(true, FormMgr::GetRecoverStatus() == beforeRecoverStatus); + + int64_t formId = formJsInfo.formId; + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_002 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..01a898436aad4812169fc556d80a5f1367bca258 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/BUILD.gn @@ -0,0 +1,89 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrDeleteFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_delete_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "//foundation/appexecfwk/standard/services/bundlemgr/test:bundlemgr_test_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${appexecfwk_path}/services/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrDeleteFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0ec63205f1c316a60b86966b7a773454f64bf51 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrDeleteFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrDeleteFormTest::SetUpTestCase() +{} + +void FmsFormMgrDeleteFormTest::TearDownTestCase() +{} + +void FmsFormMgrDeleteFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrDeleteFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is not 0 after delete form. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_001 start"; + + // clear old data + FormDataMgr::GetInstance().ClearFormRecords(); + std::vector oldFormDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(oldFormDBInfos); + FormDbCache::GetInstance().DeleteFormInfoByBundleName(FORM_HOST_BUNDLE_NAME, oldFormDBInfos); + + int64_t formId {12001}; + int callingUid = IPCSkeleton::GetCallingUid(); + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + int formUserUid {1}; + FormDataMgr::GetInstance().AddFormUserUid(formId, formUserUid); + // Set form host record + retFormRec.formUserUids.emplace_back(formUserUid); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().DeleteForm(formId, token_)); + token_->Wait(); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t dataCnt{1}; + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // Form host record is deleted. + FormHostRecord hostRecord; + EXPECT_FALSE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is 0 after delete form. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_002 start"; + + int64_t formId {12002}; + int callingUid = IPCSkeleton::GetCallingUid(); + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().DeleteForm(formId, token_)); + token_->Wait(); + + // Cache uid is deleted. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_FALSE(ret); + // Database is deleted. + size_t dataCnt{0}; + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + // Form host record is deleted. + FormHostRecord hostRecord; + EXPECT_FALSE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Test cases when some paraments are invalid + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 start"; + // case when formId<=0 + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(0, token_)); + // case when token is nullptr + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(123L, nullptr)); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case with no database info and form is not temporary. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_006 start"; + + int64_t formId {12006}; + int callingUid = IPCSkeleton::GetCallingUid(); + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().DeleteForm(formId, token_)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_006 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case when form with database info, not temporary form, without host record. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_007 start"; + + int64_t formId {12007}; + int callingUid = IPCSkeleton::GetCallingUid(); + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + retFormRec.formUserUids.clear(); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + ASSERT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().DeleteForm(formId, token_)); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t dataCnt{1}; + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + dataCnt = 0; + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // Form host record is not deleted. + FormHostRecord hostRecord; + EXPECT_TRUE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_007 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Persistent data,abilityName or bundleName is empty. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_008 start"; + + int64_t formId {12008}; + int callingUid = IPCSkeleton::GetCallingUid(); + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(""); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + ASSERT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(formId, token_)); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t dataCnt{1}; + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // form host record is not deleted yet. + FormHostRecord hostRecord; + EXPECT_TRUE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + // Database info. + FormDbCache::GetInstance().DeleteFormInfo(formId); + retFormRec.bundleName = ""; + retFormRec.abilityName = FORM_PROVIDER_ABILITY_NAME; + FormDBInfo formDBInfo1(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo1); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(formId, token_)); + + // Cache uid is not deleted yet. + ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + formDBInfos.clear(); + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + dbInfo = formDBInfos[0]; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // form host record is not deleted yet. + EXPECT_TRUE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_008 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4ff09d1b3a99aacdc7eaaa93e058a6b61d1bf5b7 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/BUILD.gn @@ -0,0 +1,91 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrLifecycleUpdateTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/aafwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", + ] + + configs = [ + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + + #"${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + #"//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrLifecycleUpdateTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..045433d88f0cb1d388eb92f59bd8a9e875694873 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_bms_helper.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_data_mgr.h" +#include "form_mgr.h" +#include "form_mgr_service.h" +#undef private +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test"; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; + +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrLifecycleUpdateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + void InitFormItemInfo(int64_t formId, FormItemInfo &formItemInfo) const; + +protected: + sptr mockBundleMgr_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + sptr token_; +}; + +void FmsFormMgrLifecycleUpdateTest::SetUpTestCase() +{} + +void FmsFormMgrLifecycleUpdateTest::TearDownTestCase() +{} + +void FmsFormMgrLifecycleUpdateTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_enable_update_test_001 setup"); + formyMgrServ_->OnStart(); + + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + // token + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrLifecycleUpdateTest::TearDown() +{} + +void FmsFormMgrLifecycleUpdateTest::InitFormItemInfo(int64_t formId, FormItemInfo &formItemInfo) const +{ + // create hapSourceDirs + std::vector hapSourceDirs; + std::string hapSourceDir = "1/2/3"; + hapSourceDirs.emplace_back(hapSourceDir); + + // create formItemInfo + formItemInfo.SetFormId(formId); + formItemInfo.SetTemporaryFlag(true); + formItemInfo.SetEnableUpdateFlag(true); + formItemInfo.SetUpdateDuration(Constants::MIN_CONFIG_DURATION); + formItemInfo.SetScheduledUpdateTime("10:30"); + formItemInfo.SetHapSourceDirs(hapSourceDirs); +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: formIds is empty. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 start"; + + std::vector formIds; + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 end"; +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: clientRecords_ is empty. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 start"; + + std::vector formIds; + formIds.push_back(3); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 end"; +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: + * clientRecords_ is exist, but no formRecords. + * set EnableRefresh, and not pull up Provider. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004 start"; + + std::vector formIds; + int64_t formId = 4; + formIds.push_back(formId); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formHostRecord.SetNeedRefresh(formId, true); + FormDataMgr::GetInstance().clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004 end"; +} + + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: + * clientRecords and formRecords(needRefresh:true) is exist. + * set EnableRefresh, and pull up Provider and update. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005 start"; + + std::vector formIds; + int64_t formId = 5; + formIds.push_back(formId); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formHostRecord.SetNeedRefresh(formId, true); + FormDataMgr::GetInstance().clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = FormDataMgr::GetInstance().CreateFormRecord(formItemInfo, callingUid); + // needRefresh:true + record.needRefresh = true; + FormDataMgr::GetInstance().formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005 end"; +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * + * @tc.info: + * clientRecords(needRefresh:true) and formRecords(needRefresh & versionUpgrade:false) is exist. + * set EnableRefresh, and update hostRecord. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006 start"; + + std::vector formIds; + int64_t formId = 6; + formIds.push_back(formId); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // needRefresh:true + formHostRecord.SetNeedRefresh(formId, true); + FormDataMgr::GetInstance().clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = FormDataMgr::GetInstance().CreateFormRecord(formItemInfo, callingUid); + // needRefresh:false + record.needRefresh = false; + // versionUpgrade:false + record.versionUpgrade = false; + FormDataMgr::GetInstance().formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + // judge hostrecord's needRefresh_ is false. + EXPECT_EQ(false, FormDataMgr::GetInstance().clientRecords_.at(0).IsNeedRefresh(formId)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..090152cd7bed0d895e5a9a2dfd5061ab2a22b747 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/BUILD.gn @@ -0,0 +1,88 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrMessageEventTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_message_event_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${appexecfwk_path}/services/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrMessageEventTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efa7bc176640925699a4dbb43db945464055118c --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +const std::string FORM_MESSAGE_EVENT_VALUE_1 = "event message1"; + +class FmsFormMgrMessageEventTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrMessageEventTest::SetUpTestCase() +{} + +void FmsFormMgrMessageEventTest::TearDownTestCase() +{} + +void FmsFormMgrMessageEventTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrMessageEventTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke MessageEvent works. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_001 start"; + + int64_t formId {10000001}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + int formUserUid {1}; + FormDataMgr::GetInstance().AddFormUserUid(formId, formUserUid); + // Set form host record + retFormRec.formUserUids.emplace_back(formUserUid); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if formId == 0. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_003 start"; + int64_t formId = 0; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_003 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if callerToken == nullptr. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_004 start"; + int64_t formId {10000001}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().MessageEvent(formId, want, nullptr)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_004 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if message info is not exist. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_005 start"; + int64_t formId {10000001}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_005 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if not exist such form. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_006 start"; + int64_t formId {11100002}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_006 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if cannot find target client. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_007 start"; + int64_t formId {10000001}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().MessageEvent(formId, want, + new (std::nothrow) MockFormHostClient())); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_007 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if form is not self-owned. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_008 start"; + int64_t formId2 {10000001}; + int64_t formId {10000002}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + int formUserUid {1}; + FormDataMgr::GetInstance().AddFormUserUid(formId, formUserUid); + // Set form host record + retFormRec.formUserUids.emplace_back(formUserUid); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId2); + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().MessageEvent(formId2, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_008 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c1bd251ae4da40a3dcc79970f4885aa6b6a3a0fa --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/BUILD.gn @@ -0,0 +1,90 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrNotifyInvisibleFormsTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/aafwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + + #"${libs_path}/libeventhandler:libeventhandler_target", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrNotifyInvisibleFormsTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f5adb323644a65f7abc2b66fd7eccaee70487dc --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#define private public +#include "form_bms_helper.h" +#include "form_mgr_service.h" +#include "form_mgr_adapter.h" +#include "form_data_mgr.h" +#include "form_mgr.h" +#undef private +#include "form_constants.h" +#include "mock_form_host_client.h" +#include "mock_bundle_manager.h" +#include "permission/permission_def.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string FORM_HOST_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrNotifyInvisibleFormsTest : public testing::Test { +public: + FmsFormMgrNotifyInvisibleFormsTest() : formMgrService_(nullptr) + {} + ~FmsFormMgrNotifyInvisibleFormsTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +protected: + sptr token_; + sptr mockBundleMgr_; + std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); +}; +void FmsFormMgrNotifyInvisibleFormsTest::SetUpTestCase(void) +{} + +void FmsFormMgrNotifyInvisibleFormsTest::TearDownTestCase(void) +{} + +void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) +{ + formMgrService_ = std::make_shared(); + + formMgrService_->OnStart(); + + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + // token + token_ = new (std::nothrow) OHOS::AppExecFwk::MockFormHostClient(); + + // Permission install + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_HOST_BUNDLE_NAME; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + std::vector permnameList; + permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, + permnameList, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_HOST_BUNDLE_NAME, + PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrNotifyInvisibleFormsTest::TearDown(void) +{} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_APPEXECFWK_FORM_INVALID_PARAM. + * @tc.info: callerToken is nullptr. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 start"; + + int64_t formId = 2; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // clear callerToken + token_ = nullptr; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, + token_, Constants::FORM_INVISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: form record is not found. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 start"; + + int64_t formId = 3; + std::vector formIds; + formIds.push_back(formId); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: host form record is not found. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 start"; + + int64_t formId = 4; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: host form record is found, but formVisibleNotify is false. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 start"; + + int64_t formId = 5; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.formVisibleNotify_ = false; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // creat clientRecords_ + FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: host form record is found, formVisibleNotify is true, it is a SystemApp. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 start"; + + int64_t formId = 6; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.formVisibleNotify_ = true; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // creat clientRecords_ + FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: it is not a SystemApp. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 start"; + + int64_t formId = 7; + std::string mockBundleName = "com.form.host.app600"; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = mockBundleName; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.formVisibleNotify_ = true; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // creat clientRecords_ + FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); + + // Permission install (mockBundleName) + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = mockBundleName; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(mockBundleName, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(mockBundleName, + PERMISSION_NAME_REQUIRE_FORM, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9c945385ae85e53f600915c104ab432d8bb38a2e --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/BUILD.gn @@ -0,0 +1,90 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrNotifyVisibleFormsTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/aafwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + + #"${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrNotifyVisibleFormsTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..843686dbc7cd3893bd5961fd19b5246e3031f542 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#define private public +#include "form_bms_helper.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_mgr.h" +#include "form_mgr_service.h" +#include "form_mgr_adapter.h" +#undef private +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_def.h" +#include "permission/permission_kit.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string NON_SYSTEM_APP_BUNDLE_NAME = "com.form.host.app600"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrNotifyVisibleFormsTest : public testing::Test { +public: + FmsFormMgrNotifyVisibleFormsTest() : formMgrService_(nullptr) + {} + ~FmsFormMgrNotifyVisibleFormsTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +protected: + sptr token_; + sptr mockBundleMgr_; + std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); +}; +void FmsFormMgrNotifyVisibleFormsTest::SetUpTestCase(void) +{} + +void FmsFormMgrNotifyVisibleFormsTest::TearDownTestCase(void) +{} + +void FmsFormMgrNotifyVisibleFormsTest::SetUp(void) +{ + formMgrService_ = std::make_shared(); + formMgrService_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + std::vector permnameList; + permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + permnameList, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, + PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrNotifyVisibleFormsTest::TearDown(void) +{} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return code is ERR_APPEXECFWK_FORM_INVALID_PARAM. + * @tc.info: The callerToken is nullptr. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002 start"; + + // set the callerToken to nullptr. + token_ = nullptr; + + // create formIds + int64_t formId1 = 301; + int64_t formId2 = 302; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + + FormItemInfo formiteminfo2; + formiteminfo2.SetFormId(formId2); + formiteminfo2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo2, 0); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, + Constants::FORM_VISIBLE)); + + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: Create two formId and push formIds, but only create one form record. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003 start"; + + // create formIds + int64_t formId1 = 401; + int64_t formId2 = 402; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId1, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId1, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: Create two formId and push formIds, but only create one form host record. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004 start"; + + // create formIds + int64_t formId1 = 501; + int64_t formId2 = 502; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId1, true); + + FormItemInfo formiteminfo2; + formiteminfo2.SetFormId(formId2); + formiteminfo2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo2.SetFormVisibleNotify(true); + formiteminfo2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo2, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId2, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId1, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: Create two formId and push formIds, two form records and two form host records. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005 start"; + + // create formIds + int64_t formId1 = 601; + int64_t formId2 = 602; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId1, true); + + FormItemInfo formiteminfo2; + formiteminfo2.SetFormId(formId2); + formiteminfo2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo2.SetFormVisibleNotify(true); + formiteminfo2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo2, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId2, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId1, 0); + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo2, token_, formId2, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: The NeedRefresh is false. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006 start"; + + // create formIds + int64_t formId = 700; + std::vector formIds; + formIds.push_back(formId); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId, false); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: The FormVisibleNotify is false. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007 start"; + + // create formIds + int64_t formId = 800; + std::vector formIds; + formIds.push_back(formId); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(false); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: The form provider is not a system app. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008 start"; + + // create formIds + int64_t formId = 900; + std::vector formIds; + formIds.push_back(formId); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId); + formiteminfo1.SetProviderBundleName(NON_SYSTEM_APP_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId, 0); + + // Permission install + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = NON_SYSTEM_APP_BUNDLE_NAME; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(NON_SYSTEM_APP_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(NON_SYSTEM_APP_BUNDLE_NAME, + PERMISSION_NAME_REQUIRE_FORM, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6638bfc119953fe748e3d5513d7dce823157607d --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrReleaseFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_release_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "//foundation/appexecfwk/standard/services/bundlemgr/test:bundlemgr_test_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrReleaseFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca8bdd6c2a42ae9d79bf821fd2790dd5aaed9b13 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "form_bms_helper.h" +#include "form_cache_mgr.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_db_info.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "mock_form_token.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test"; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; + +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; +constexpr int32_t UID_CALLINGUID_TRANSFORM_DIVISOR = 200000; + +class FmsFormMgrReleaseFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + sptr mockBundleMgr_; +}; + +void FmsFormMgrReleaseFormTest::SetUpTestCase() +{} + +void FmsFormMgrReleaseFormTest::TearDownTestCase() +{} + +void FmsFormMgrReleaseFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrReleaseFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is not 0 after release form. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_001 start"; + + int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = callingUid/UID_CALLINGUID_TRANSFORM_DIVISOR; + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid, userId); + // Set database info. + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + + int64_t formId2 = FormDataMgr::GetInstance().GenerateFormId(); + FormItemInfo record2; + record2.SetFormId(formId2); + record2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record2, 1, userId); + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_FALSE(ret); + ret = FormDataMgr::GetInstance().GetFormRecord(formId2, formInfo); + EXPECT_TRUE(ret); + // Form host record is deleted. + FormHostRecord hostRecord; + EXPECT_FALSE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteFormRecord(formId2); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId2); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId2); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is 0 after delete form. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_002 start"; + + int64_t formId1 = FormDataMgr::GetInstance().GenerateFormId(); + int64_t formId2 = FormDataMgr::GetInstance().GenerateFormId(); + FormItemInfo record1; + record1.SetFormId(formId1); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, 0); + // Set database info. + FormDBInfo formDBInfo(formId1, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + + FormItemInfo record2; + record2.SetFormId(formId2); + record2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record2, 0); + + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId1, 0); + + FormCacheMgr::GetInstance().AddData(formId1, "test data 1"); + FormCacheMgr::GetInstance().AddData(formId2, "test data 2"); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().ReleaseForm(formId1, token_, true)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId1); + FormDataMgr::GetInstance().DeleteFormRecord(formId2); + FormDbCache::GetInstance().DeleteFormInfo(formId1); + FormDbCache::GetInstance().DeleteFormInfo(formId2); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId1); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if formId is not exist in cache. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 start"; + int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if formId is not exist in host. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_005 start"; + int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record, 0); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_005 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..00713a1a04784791fed607ff601c12ccb1b2a9eb --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrRequestFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_request_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "//foundation/appexecfwk/standard/services/bundlemgr/test:bundlemgr_test_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrRequestFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..feaecd160542faf7eb4113b37f862ba5294ad14a --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "form_data_mgr.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "mock_bundle_manager.h" +#include "mock_ability_manager.h" +#include "system_ability_definition.h" +#include "../../mock/include/mock_form_token.h" +#include "../../mock/include/mock_form_host_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test"; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; + +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrRequestFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr mockAbilityMgrServ_; + sptr mockBundleMgr_; + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); +}; + +void FmsFormMgrRequestFormTest::SetUpTestCase() +{} + +void FmsFormMgrRequestFormTest::TearDownTestCase() +{} + +void FmsFormMgrRequestFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + + token_ = new (std::nothrow) MockFormHostClient(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrRequestFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgrClient + * SubFunction: RequestForm Function + * FunctionPoints: FormMgrClient RequestForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Nomal case: Verify if FormMgrClient invoke RequestForm works. + */ +HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_001, TestSize.Level0) +{ + APP_LOGI("fms_form_mgr_request_test_001 start"); + + int64_t formId {0X0000FFFF00000000}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + retFormRec.formUserUids.clear(); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + Want want; + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().RequestForm(formId, token_, want)); + + token_->Wait(); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + APP_LOGI("fms_form_mgr_request_test_001 end"); +} + +/* + * Feature: FormMgrService + * Function: FormMgrClient + * SubFunction: RequestForm Function + * FunctionPoints: FormMgrClient RequestForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Abnomal case: Verify invalid parameter. + */ +HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_003, TestSize.Level0) +{ + APP_LOGI("fms_form_mgr_request_test_003 start"); + + int64_t formId {0X00AAAAFF00000000}; + FormItemInfo record; + int callingUid {0}; + record.SetFormId(formId); + record.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + + Want want; + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().RequestForm(formId, token_, want)); + + token_->Wait(); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + APP_LOGI("fms_form_mgr_request_test_003 end"); +} + +/* + * Feature: FormMgrService + * Function: FormMgrClient + * SubFunction: RequestForm Function + * FunctionPoints: FormMgrClient RequestForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Abnomal case: Verify form not self. + */ +HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_004, TestSize.Level0) +{ + APP_LOGI("fms_form_mgr_request_test_004 start"); + int64_t formId {0X000ABCFF00000000}; + int64_t fakeFormId {0X0ABCDEFF00000000}; + FormItemInfo record; + int callingUid {0}; + record.SetFormId(formId); + record.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, fakeFormId, 0); + + Want want; + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().RequestForm(formId, token_, want)); + + token_->Wait(); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + APP_LOGI("fms_form_mgr_request_test_004 end"); +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4a7dbe9ef3ddbc3e30b2a12100691543c5455d48 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/BUILD.gn @@ -0,0 +1,88 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormMgrUpdateFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_update_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${appexecfwk_path}/services/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrUpdateFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..559958c4f72d4edba4e72370eaa70fceb3052a70 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp @@ -0,0 +1,355 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrUpdateFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrUpdateFormTest::SetUpTestCase() +{} + +void FmsFormMgrUpdateFormTest::TearDownTestCase() +{} + +void FmsFormMgrUpdateFormTest::SetUp() +{ + APP_LOGI("fms_form_mgr_client_updateForm_test_001 setup"); + + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrUpdateFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_001 start"; + + // param editor + int64_t formId {100L}; + int32_t callingUid {0}; + std::string bandleName = FORM_HOST_BUNDLE_NAME; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing001\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + FormItemInfo formItemInfo1; + formItemInfo1.SetFormId(1000L); + formItemInfo1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo1.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo1, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + token_->Wait(); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when passing bandleName is empty. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_003 start"; + + // param editor + int64_t formId {300L}; + int32_t callingUid {0}; + std::string bandleName = ""; + FormProviderData formProviderData; + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when bandleName not match. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_004 start"; + + // param editor + int64_t formId {400L}; + int32_t callingUid {0}; + std::string bandleName = FORM_PROVIDER_BUNDLE_NAME; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing004\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when not under current user. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_005 start"; + + // param editor + int64_t formId {500L}; + int32_t callingUid {1}; + std::string bandleName = FORM_HOST_BUNDLE_NAME; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing005\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_005 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when the updated form is not your own. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_006 start"; + + // param editor + int64_t formId {600L}; + int32_t callingUid {0}; + std::string bandleName = "com.form.host.app600"; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing006\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_006 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_007 start"; + + // param editor + int64_t formId {700L}; + int32_t callingUid {0}; + std::string bandleName = FORM_HOST_BUNDLE_NAME; + std::string jsonData = std::string("{"); + for (int i = 0; i < 1024; i = i + 1) { + jsonData = jsonData + std::string("\"city" + std::to_string(i) + "\"" + ":" + "\"beijing007\""); + if (i != 1023) { + jsonData = jsonData + std::string(", "); + } + } + jsonData = jsonData + std::string("}"); + FormProviderData formProviderData = FormProviderData(jsonData); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + formRecord.versionUpgrade = true; + + FormItemInfo formItemInfo1; + formItemInfo1.SetFormId(7000L); + formItemInfo1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo1.SetTemporaryFlag(true); + FormRecord formRecord1 = FormDataMgr::GetInstance().AllotFormRecord(formItemInfo1, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + token_->Wait(); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_007 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_provider_data_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_provider_data_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..967facddeafe3fe3044dd5988815a9bb74aa36ec --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormProviderDataTest") { + module_out_path = module_output_path + + sources = [ "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp" ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + + #"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + ] + + configs = [] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormProviderDataTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69244b5b00359580f54d315173fa1aea1b9b664a --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#define private public +#include "form_provider_data.h" +#undef private +#include "nlohmann/json.hpp" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; +const int32_t four = 4; +const int32_t ten = 10; +const int32_t eleven = 11; + +class FmsFormProviderDataTest : public testing::Test { +public: + void SetUp(); + void Test(); + bool InitJsonData(); + bool InitJsonData2(); + bool CreateJsonFileByJsonData1(const nlohmann::json &jsonData); + bool CreateJsonFileByJsonData2(const nlohmann::json &jsonData); + bool CreateMergeJsonFileByJsonData3(const nlohmann::json &jsonData); + + nlohmann::json jsonData_; +}; +void FmsFormProviderDataTest::SetUp() +{ + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR.c_str()); + if (dirptr == nullptr) { + APP_LOGW("%{public}s, opendir is fail", __func__); + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR.c_str(), S_IRWXU)) { + APP_LOGE("%{public}s, dir create fail", __func__); + return; + } + } else { + closedir(dirptr); + } +} + +bool FmsFormProviderDataTest::InitJsonData() +{ + nlohmann::json tmpJson; + tmpJson["name"] = "li"; + tmpJson["age"] = ten; + jsonData_["0"] = tmpJson; + return true; +} + +bool FmsFormProviderDataTest::InitJsonData2() +{ + nlohmann::json tmpJson; + tmpJson["name"] = "wang"; + tmpJson["age"] = eleven; + jsonData_["1"] = tmpJson; + return true; +} + +bool FmsFormProviderDataTest::CreateJsonFileByJsonData1(const nlohmann::json &jsonData) +{ + std::ofstream o("/data/formmgr/ByJsonFile1.json"); + o.close(); + + std::fstream f("/data/formmgr/ByJsonFile1.json"); + if (f.good() == false) { + return false; + } + + f << std::setw(four) << jsonData << std::endl; + + f.close(); + return true; +} + +bool FmsFormProviderDataTest::CreateJsonFileByJsonData2(const nlohmann::json &jsonData) +{ + std::ofstream o("/data/formmgr/ByJsonFile2.json"); + o.close(); + + std::fstream f("/data/formmgr/ByJsonFile2.json"); + if (f.good() == false) { + return false; + } + + f << std::setw(four) << jsonData << std::endl; + + f.close(); + return true; +} + +bool FmsFormProviderDataTest::CreateMergeJsonFileByJsonData3(const nlohmann::json &jsonData) +{ + std::ofstream o("/data/formmgr/ByJsonFile3.json"); + o.close(); + + std::fstream f("/data/formmgr/ByJsonFile3.json"); + if (f.good() == false) { + return false; + } + + f << std::setw(four) << jsonData << std::endl; + + f.close(); + return true; +} + +HWTEST_F(FmsFormProviderDataTest, FmsFormProviderDataTest_001, TestSize.Level0) // create +{ + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_001 start"; + EXPECT_EQ(true, InitJsonData()); + FormProviderData formProviderData(jsonData_); + EXPECT_EQ(true, CreateJsonFileByJsonData1(formProviderData.jsonFormProviderData_)); + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_001 end"; +} + +HWTEST_F(FmsFormProviderDataTest, FmsFormProviderDataTest_002, TestSize.Level0) // test constructor with string +{ + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_002 start"; + EXPECT_EQ(true, InitJsonData()); + FormProviderData formProviderData(jsonData_.dump()); + EXPECT_EQ(true, CreateJsonFileByJsonData2(formProviderData.jsonFormProviderData_)); + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_002 end"; +} + +HWTEST_F(FmsFormProviderDataTest, FmsFormProviderDataTest_003, TestSize.Level0) // test GetDataString +{ + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_003 start"; + EXPECT_EQ(true, InitJsonData()); + FormProviderData formProviderData(jsonData_); + GTEST_LOG_(INFO) << "print:" < +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#define private public +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_refresh_limiter.h" +#include "form_host_interface.h" +#undef private +#include "form_mgr_service.h" +#include "form_provider_mgr.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormProviderMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormProviderMgrTest::SetUpTestCase() +{} + +void FmsFormProviderMgrTest::TearDownTestCase() +{} + +void FmsFormProviderMgrTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormProviderMgrTest::TearDown() +{} + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: AcquireForm Function + * FunctionPoints: FormMgr AcquireForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AcquireForm works with invalid formid. + */ + +HWTEST_F(FmsFormProviderMgrTest, AcquireForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 start"; + int64_t formId = 0x114514aa00000000; + FormProviderInfo formProviderInfo; + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormProviderMgr::GetInstance().AcquireForm(-114514L, formProviderInfo)); + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 end"; +} + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: AcquireForm Function + * FunctionPoints: FormMgr AcquireForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AcquireForm works without formrecord. + */ + +HWTEST_F(FmsFormProviderMgrTest, AcquireForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 start"; + int64_t formId = 0x11451aaa00000000; + FormProviderInfo formProviderInfo; + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo)); + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 end"; +} + + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: AcquireForm Function + * FunctionPoints: FormMgr AcquireForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AcquireForm works without form host record. + */ + +HWTEST_F(FmsFormProviderMgrTest, AcquireForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 start"; + int64_t formId = 0x1145aaaa00000000; + FormProviderInfo formProviderInfo; + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, + FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo)); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 end"; +} + + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: RefreshForm Function + * FunctionPoints: FormMgr RefreshForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if RefreshForm works without form host record. + */ + +HWTEST_F(FmsFormProviderMgrTest, RefreshForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_004 start"; + int64_t formId = 0x1145aaaa00001200; + Want want; + int callingUid {0}; + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + FormItemInfo record; + record.SetFormId(formId); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_004 end"; +} + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: RefreshForm Function + * FunctionPoints: FormMgr RefreshForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if RefreshForm works without form host record. + */ + +HWTEST_F(FmsFormProviderMgrTest, RefreshForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 start"; + int64_t formId = 0x114514aa00000000; + Want want; + want.SetParam(Constants::KEY_IS_TIMER, true); + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4c5aa8506d649f3309c82609f124c0975dc1877e --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn @@ -0,0 +1,95 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormSetNextRefreshTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/aafwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "${appexecfwk_path}/services/bundlemgr/test:bundlemgr_test_config", + + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + + #"${libs_path}/libeventhandler:libeventhandler_target", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormSetNextRefreshTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c363f16e3a2b47b72c509f68f05106fe8876a3d3 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#define private public +#include "form_bms_helper.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_mgr_adapter.h" +#include "form_mgr_service.h" +#include "form_timer_mgr.h" +#undef private +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "mock_bundle_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string FORM_HOST_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; +constexpr int32_t UID_CALLINGUID_TRANSFORM_DIVISOR = 200000; + +class FmsFormSetNextRefreshTest : public testing::Test { +public: + FmsFormSetNextRefreshTest() : formSetNextRefresh_(nullptr) + {} + ~FmsFormSetNextRefreshTest() + {} + std::shared_ptr formSetNextRefresh_ = DelayedSingleton::GetInstance(); + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +protected: + sptr mockBundleMgr_; +}; +void FmsFormSetNextRefreshTest::SetUpTestCase(void) +{} + +void FmsFormSetNextRefreshTest::TearDownTestCase(void) +{} + +void FmsFormSetNextRefreshTest::SetUp(void) +{ + formSetNextRefresh_ = std::make_shared(); + + formSetNextRefresh_->OnStart(); + + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); +} + +void FmsFormSetNextRefreshTest::TearDown(void) +{} + + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_001 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(formId is invalid) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_001 start"; + int64_t formId = 0; // invalid formId + int64_t nextTime = Constants::MIN_NEXT_TIME; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_001 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_002 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(not found in form record) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_002 start"; + int64_t formId = 2; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_002 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_003 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(BundleName is found in form record, but no dynamicRefreshTask) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_003 start"; + int64_t formId = 3; + int64_t nextTime = Constants::MIN_NEXT_TIME; + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = callingUid/UID_CALLINGUID_TRANSFORM_DIVISOR; + GTEST_LOG_(INFO) << "callingUid:" << callingUid << " userId:" << userId; + // check dynamicRefreshTasks_ + EXPECT_EQ(true, FormTimerMgr::GetInstance().dynamicRefreshTasks_.empty()); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; + + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, callingUid, userId); + EXPECT_EQ(ERR_OK, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + + // check dynamicRefreshTasks_ + EXPECT_EQ(false, FormTimerMgr::GetInstance().dynamicRefreshTasks_.empty()); + + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_003 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_004 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(BundleName is not found in form record) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_004 start"; + int64_t formId = 4; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = "other_bundleName"; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_004 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_005 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(have dynamicRefreshTask , have IntervalTimerTasks) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_005 start"; + int64_t formId = 5; + int64_t nextTime = Constants::MIN_NEXT_TIME; + int callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = callingUid/UID_CALLINGUID_TRANSFORM_DIVISOR; + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; + + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, callingUid, userId); + + // Creat dynamicRefreshTasks_ + DynamicRefreshItem theItem; + theItem.formId = formId; + theItem.userId = userId; + theItem.settedTime = 1; + FormTimerMgr::GetInstance().dynamicRefreshTasks_.clear(); + FormTimerMgr::GetInstance().dynamicRefreshTasks_.emplace_back(theItem); + // check dynamicRefreshTasks_ + EXPECT_EQ(1, FormTimerMgr::GetInstance().dynamicRefreshTasks_.at(0).settedTime); + + // Create IntervalTimerTasks_ + FormTimer task(formId, 3 * Constants::MIN_PERIOD, userId); + + task.isEnable = true; + FormTimerMgr::GetInstance().AddFormTimer(task); + + EXPECT_EQ(ERR_OK, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + // check dynamicRefreshTasks_ + EXPECT_EQ(true, FormTimerMgr::GetInstance().dynamicRefreshTasks_.at(0).settedTime != 1); + + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_005 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_006 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(timerRefreshedCount >= 50) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_006 start"; + + int64_t formId = 6; + int64_t nextTime = Constants::MIN_NEXT_TIME; + int32_t callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = callingUid/UID_CALLINGUID_TRANSFORM_DIVISOR; + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, callingUid, userId); + + // set timerRefreshedCount + FormTimerMgr::GetInstance().refreshLimiter_.AddItem(formId); + auto iter = FormTimerMgr::GetInstance().refreshLimiter_.limiterMap_.find(formId); + if (iter == FormTimerMgr::GetInstance().refreshLimiter_.limiterMap_.end()) { + GTEST_LOG_(INFO) << "not found in limiterMap_!!!"; + } else { + iter->second.refreshCount = Constants::LIMIT_COUNT; + } + EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_REFRESH, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_006 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e0bbbf6854d11781fe899d59fa651be34ff12f54 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn @@ -0,0 +1,95 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormSysEventReceiverTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/src/form_mgr.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/aafwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_sys_event_receiver_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "//foundation/appexecfwk/standard/services/bundlemgr/test:bundlemgr_test_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/fmskit:fmskit_native", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${appexecfwk_path}/services/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormSysEventReceiverTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ada590a92a1c663f0f32c6b9cd07cdec0bbff63e --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp @@ -0,0 +1,477 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "common_event_manager.h" +#include "common_event_data.h" +#include "common_event_support.h" +#include "form_ams_helper.h" +#include "form_constants.h" +#define private public +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "form_refresh_limiter.h" +#include "form_sys_event_receiver.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "form_bms_helper.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_BUNDLE_NAME_1 = "com.form.provider.service1"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string KEY_UID = "uid"; +const std::string KEY_BUNDLE_NAME = "bundleName"; +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormSysEventReceiverTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + void CreateEventData(std::string bundle, int64_t formId, + int callingUid, std::string actionType, EventFwk::CommonEventData &eventData); + void CreateFormRecordAndFormInfo(std::string bundle, int64_t formId, int callingUid); + void ClearFormRecord(int64_t formId); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormSysEventReceiverTest::SetUpTestCase() +{} + +void FmsFormSysEventReceiverTest::TearDownTestCase() +{} + +void FmsFormSysEventReceiverTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormSysEventReceiverTest::TearDown() +{} + +void FmsFormSysEventReceiverTest::CreateEventData(std::string bundle, int64_t formId, + int callingUid, std::string actionType, EventFwk::CommonEventData &eventData) +{ + Want want; + want.SetAction(actionType); + want.SetBundle(bundle); + want.SetParam(KEY_UID, callingUid); + eventData.SetWant(want); +} + +void FmsFormSysEventReceiverTest::CreateFormRecordAndFormInfo(std::string bundle, int64_t formId, int callingUid) +{ + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetFormName(PARAM_FORM_NAME); + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(true); + + FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + + FormRecord realFormRecord; + FormDataMgr::GetInstance().GetFormRecord(formId, realFormRecord); + + FormDBInfo formDBInfo(formId, realFormRecord); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + + FormDataMgr::GetInstance().AllotFormHostRecord(record, token_, formId, callingUid); +} + +void FmsFormSysEventReceiverTest::ClearFormRecord(int64_t formId) +{ + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleProviderRemoved works. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_001 start"; + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcff00000000; + int callingUid {0}; + + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_PROVIDER_MODULE_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetFormName(PARAM_FORM_NAME); + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(false); + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + want.SetBundle(bundle); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + // Set database info + FormDBInfo formDBInfo(formId, realFormRecord); + std::vector allFormInfo; + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + EventFwk::CommonEventData eventData; + eventData.SetWant(want); + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + FormDbCache::GetInstance().GetAllFormInfo(allFormInfo); + FormDBInfo tempFormDBInfo; + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormDbCache::GetInstance().GetDBRecord(formId, tempFormDBInfo)); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * [COMMON_EVENT_PACKAGE_DATA_CLEARED] want's uid is 0. formrecord's uid is 15. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_002 start"; + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcff00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED; + EventFwk::CommonEventData eventData; + int callingUidForWant = 0; + CreateEventData(bundle, formId, callingUidForWant, actionType, eventData); + CreateFormRecordAndFormInfo(bundle, formId, callingUid); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * [COMMON_EVENT_PACKAGE_DATA_CLEARED] want's uid and formrecord's and hostrecord's uid is 15. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_003 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + std::string bundle1 = FORM_PROVIDER_BUNDLE_NAME_1; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle1, formId, callingUid, actionType, eventData); + CreateFormRecordAndFormInfo(bundle, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_FALSE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_004 start"; + EventFwk::CommonEventData eventData; + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int callingUid {15}; + Want want; + FormRecord tempFormRecord; + eventData.SetWant(want); + want.SetBundle(bundle); + want.SetParam(KEY_UID, callingUid); + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * invalid action. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_005 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED + "ERROR"; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_005 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * [COMMON_EVENT_PACKAGE_DATA_CLEARED] There is 2 callingUids. + */ +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_006 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + + // CreateFormRecordAndFormInfo + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetFormName(PARAM_FORM_NAME); + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + // AddFormUserUid + int new_callingUid = 150; + FormDataMgr::GetInstance().AddFormUserUid(formId, new_callingUid); + FormRecord realFormRecord; + FormDataMgr::GetInstance().GetFormRecord(formId, realFormRecord); + FormDBInfo formDBInfo(formId, realFormRecord); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + FormDataMgr::GetInstance().AllotFormHostRecord(record, token_, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_006 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleProviderUpdated works. + * [COMMON_EVENT_ABILITY_UPDATED] ProviderFormUpdated return false. delete formrecord. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_007 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {0}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + CreateFormRecordAndFormInfo(bundle, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_FALSE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_007 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleProviderUpdated works. + * [COMMON_EVENT_ABILITY_UPDATED] ProviderFormUpdated return true. refresh form. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_008 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + + // CreateFormRecordAndFormInfo + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_PROVIDER_MODULE_NAME); // model name + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); // ability name + record.SetFormName(PARAM_FORM_NAME); // form name + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(true); + + FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormRecord realFormRecord; + FormDataMgr::GetInstance().GetFormRecord(formId, realFormRecord); + FormDBInfo formDBInfo(formId, realFormRecord); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + FormDataMgr::GetInstance().AllotFormHostRecord(record, token_, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_008 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2dded5ef49f7735f9645e19bcf57aaecd71d6d0a --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "form_runtime/formmgrservice" + +ohos_unittest("FmsFormTimerMgrTest") { + module_out_path = module_output_path + + sources = [ "fms_form_timer_mgr_test.cpp" ] + + include_dirs = [ + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/aafwk/standard/services/formmgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", + "//base/miscservices/time/interfaces/innerkits/include", + ] + + configs = [ "${services_path}/formmgr/test:formmgr_test_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${services_path}/formmgr:fms_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//base/notification/ces_standard/frameworks/common:libevent_common", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "eventhandler:libeventhandler", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormTimerMgrTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e41de5bc00a17ef34651ae5448d870d61e196bd8 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp @@ -0,0 +1,547 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "common_event.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "form_constants.h" +#include "form_refresh_limiter.h" +#include "form_timer_mgr.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const int64_t PARAM_FORM_ID_VALUE_1 = 20210712; +const int64_t PARAM_FORM_ID_VALUE_2 = 20210713; +const int64_t PARAM_FORM_ID_VALUE_3 = 20210714; +const int64_t PARAM_FORM_ID_VALUE_4 = 20210715; +const int64_t PARAM_FORM_ID_VALUE_5 = 20210716; +const int64_t PARAM_FORM_ID_VALUE_6 = 20210717; + +class FmsFormTimerMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: +}; + +void FmsFormTimerMgrTest::SetUpTestCase() {} +void FmsFormTimerMgrTest::TearDownTestCase() {} +void FmsFormTimerMgrTest::SetUp() {} +void FmsFormTimerMgrTest::TearDown() {} + +/** + * @tc.number: Fms_FormTimerMgr_0001 + * @tc.name: AddFormTimer. + * @tc.desc: Add duration form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0001 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 1 * Constants::MIN_PERIOD); + EXPECT_EQ(isOk, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0001 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0002 + * @tc.name: AddFormTimer. + * @tc.desc: Add scheduled form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0002 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 2, 50, 0); + EXPECT_EQ(isOk, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0002 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0003 + * @tc.name: RemoveFormTimer. + * @tc.desc: Delete form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0003 start"; + bool isAddOk1 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 336 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk1, true); + bool isAddOk2 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 3, 30, 0); + EXPECT_EQ(isAddOk2, true); + bool isDelOk1 = FormTimerMgr::GetInstance().RemoveFormTimer(PARAM_FORM_ID_VALUE_3); + EXPECT_EQ(isDelOk1, true); + bool isDelOk2 = FormTimerMgr::GetInstance().RemoveFormTimer(PARAM_FORM_ID_VALUE_4); + EXPECT_EQ(isDelOk2, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0003 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0004 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0004, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0004 start"; + bool isAddOk1 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 3 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk1, true); + + // TYPE_INTERVAL_CHANGE + FormTimerCfg timerCfg1; + timerCfg1.enableUpdate = true; + timerCfg1.updateDuration = 2 * Constants::MIN_PERIOD; + bool isUpdateOk1 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_1, + UpdateType::TYPE_INTERVAL_CHANGE, timerCfg1); + EXPECT_EQ(isUpdateOk1, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0004 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0005 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0005, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0005 start"; + bool isAddOk2 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 3, 30, 0); + EXPECT_EQ(isAddOk2, true); + + // TYPE_ATTIME_CHANGE + FormTimerCfg timerCfg2; + timerCfg2.enableUpdate = true; + timerCfg2.updateAtHour = 6; + timerCfg2.updateAtMin = 55; + bool isUpdateOk2 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_2, + UpdateType::TYPE_ATTIME_CHANGE, timerCfg2); + EXPECT_EQ(isUpdateOk2, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0005 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0006 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_TO_ATTIME). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0006, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0006 start"; + bool isAddOk3 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 6 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk3, true); + + // TYPE_INTERVAL_TO_ATTIME + FormTimerCfg timerCfg3; + timerCfg3.enableUpdate = true; + timerCfg3.updateAtHour = 8; + timerCfg3.updateAtMin = 25; + bool isUpdateOk3 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_3, + UpdateType::TYPE_INTERVAL_TO_ATTIME, timerCfg3); + EXPECT_EQ(isUpdateOk3, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0006 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0007 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_TO_INTERVAL). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0007, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0007 start"; + bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 10, 30, 0); + EXPECT_EQ(isAddOk4, true); + + // TYPE_ATTIME_TO_INTERVAL + FormTimerCfg timerCfg4; + timerCfg4.enableUpdate = true; + timerCfg4.updateDuration = 5 * Constants::MIN_PERIOD; + bool isUpdateOk4 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_4, + UpdateType::TYPE_ATTIME_TO_INTERVAL, timerCfg4); + EXPECT_EQ(isUpdateOk4, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0007 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0008 + * @tc.name: HandleSystemTimeChanged. + * @tc.desc: Handle system time changed. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0008, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 11, 30, 0); + EXPECT_EQ(isAddOk5, true); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0009 + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(COMMON_EVENT_TIMEZONE_CHANGED). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0009, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 11, 30, 0); + EXPECT_EQ(isAddOk5, true); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0010 + * @tc.name: HandleResetLimiter. + * @tc.desc: Handle reset limiter. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0010, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 16, 30, 0); + EXPECT_EQ(isAddOk5, true); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleResetLimiter(); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0011 + * @tc.name: OnUpdateAtTrigger. + * @tc.desc:handle attimer update. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0011, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0011 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 11, 30, 0); + EXPECT_EQ(isAddOk5, true); + + bool isAddOk6 = FormTimerMgr::GetInstance().OnUpdateAtTrigger(90L); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0011 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0012 + * @tc.name: OnDynamicTimeTrigger. + * @tc.desc: handle dynamic update. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0012, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0012 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_5, 11, 30, 0); + EXPECT_EQ(isAddOk5, true); + + bool isAddOk6 = FormTimerMgr::GetInstance().OnDynamicTimeTrigger(90L); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0012 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0013 + * @tc.name: AddFormTimer. + * @tc.desc: Add duration form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0013, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0013 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 0); + EXPECT_EQ(isOk, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0013 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0014 + * @tc.name: AddFormTimer. + * @tc.desc: Add scheduled form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0014, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0014 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 0, 60, 0); + EXPECT_EQ(isOk, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0014 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0015 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0015, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0015 start"; + bool isAddOk1 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 3 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk1, true); + + // TYPE_INTERVAL_CHANGE + FormTimerCfg timerCfg1; + timerCfg1.enableUpdate = true; + timerCfg1.updateDuration = 0; + bool isUpdateOk1 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_1, + UpdateType::TYPE_INTERVAL_CHANGE, timerCfg1); + EXPECT_EQ(isUpdateOk1, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0015 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0016 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0016, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0016 start"; + bool isAddOk2 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 3, 30, 0); + EXPECT_EQ(isAddOk2, true); + + // TYPE_ATTIME_CHANGE + FormTimerCfg timerCfg2; + timerCfg2.enableUpdate = true; + timerCfg2.updateAtHour = 0; + timerCfg2.updateAtMin = 60; + bool isUpdateOk2 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_2, + UpdateType::TYPE_ATTIME_CHANGE, timerCfg2); + EXPECT_EQ(isUpdateOk2, false); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0016 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0017 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_TO_ATTIME). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0017, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0017 start"; + bool isAddOk3 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 6 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk3, true); + + // TYPE_INTERVAL_TO_ATTIME + FormTimerCfg timerCfg3; + timerCfg3.enableUpdate = true; + timerCfg3.updateAtHour = 0; + timerCfg3.updateAtMin = 60; + bool isUpdateOk3 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_3, + UpdateType::TYPE_INTERVAL_TO_ATTIME, timerCfg3); + EXPECT_EQ(isUpdateOk3, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0017 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0018 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_TO_INTERVAL). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0018, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0018 start"; + bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 10, 30, 0); + EXPECT_EQ(isAddOk4, true); + + // TYPE_ATTIME_TO_INTERVAL + FormTimerCfg timerCfg4; + timerCfg4.enableUpdate = true; + timerCfg4.updateDuration = 0; + bool isUpdateOk4 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_4, + UpdateType::TYPE_ATTIME_TO_INTERVAL, timerCfg4); + EXPECT_EQ(isUpdateOk4, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0018 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0019 + * @tc.name: FormRefreshLimiter::AddItem. + * @tc.desc: AddItem success. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0019, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0019 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_1); + EXPECT_EQ(isAddOk, true); + + EXPECT_EQ(refreshLimiter.GetItemCount(), 1); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0019 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0020 + * @tc.name: FormRefreshLimiter::DeleteItem. + * @tc.desc: DeleteItem success. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0020, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0020 start"; + + FormRefreshLimiter refreshLimiter; + refreshLimiter.DeleteItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(refreshLimiter.GetItemCount(), 0); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0020 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0021 + * @tc.name: FormRefreshLimiter::IsEnableRefresh. + * @tc.desc: IsEnableRefresh. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0021, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0021 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + bool isEnableRefresh = refreshLimiter.IsEnableRefresh(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isEnableRefresh, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0021 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0022 + * @tc.name: FormRefreshLimiter::Increase. + * @tc.desc: Increase refreshCount. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0022, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0022 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + + int count = refreshLimiter.GetRefreshCount(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(count, 1); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0022 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0023 + * @tc.name: FormRefreshLimiter::ResetLimit. + * @tc.desc: ResetLimit. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0023, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0023 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + + refreshLimiter.ResetLimit(); + + int count = refreshLimiter.GetRefreshCount(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(count, 0); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0023 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0024 + * @tc.name: FormRefreshLimiter::Increase. + * @tc.desc: report refresh to 50 count. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0024, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0024 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT; iIndex++) { + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + } + + int count = refreshLimiter.GetRefreshCount(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(count, Constants::LIMIT_COUNT); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0024 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0025 + * @tc.name: FormRefreshLimiter::IsEnableRefresh. + * @tc.desc: report refresh to 50 count. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0025, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0025 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + } + + bool isEnableRefresh = refreshLimiter.IsEnableRefresh(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isEnableRefresh, false); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0025 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0026 + * @tc.name: FormRefreshLimiter::MarkRemind. + * @tc.desc: Mark remind when refresh count >= 50. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0026, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0026 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + } + + refreshLimiter.MarkRemind(PARAM_FORM_ID_VALUE_6); + + std::vector vIdlist = refreshLimiter.GetRemindList(); + EXPECT_EQ(vIdlist.size() > 0, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0026 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0027 + * @tc.name: OnIntervalTimeOut. + * @tc.desc: Interval timer timeout. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0027, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 start"; + bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_6, 10, 30, 0); + EXPECT_EQ(isAddOk4, true); + + std::this_thread::sleep_for(std::chrono::milliseconds(Constants::MIN_PERIOD)); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 end"; +} +} diff --git a/services/test/BUILD.gn b/services/test/BUILD.gn index b43f69e222cc701692633f28acbc247243a5a750..b86e2c6cf0412e892f9b4bba75c80884682be63a 100644 --- a/services/test/BUILD.gn +++ b/services/test/BUILD.gn @@ -27,6 +27,19 @@ config("aafwk_module_test_config") { ] } +config("services_module_test_config") { + include_dirs = [ + "appmgr/mock/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", + ] + + configs = [] +} + +config("services_mock_ams_config") { + include_dirs = [ "../appmgr/test/mock/include" ] +} + group("moduletest") { testonly = true @@ -34,6 +47,7 @@ group("moduletest") { "moduletest/ability_mgr_service_test:moduletest", "moduletest/ability_record_test:moduletest", "moduletest/ability_stack_test:moduletest", + "moduletest/common/ams:moduletest", "moduletest/dump_module_test:moduletest", "moduletest/ipc_ability_connect_test:moduletest", "moduletest/ipc_ability_mgr_test:moduletest", diff --git a/services/test/mock/include/appmgr/mock_ability_mgr_host.h b/services/test/mock/include/appmgr/mock_ability_mgr_host.h new file mode 100644 index 0000000000000000000000000000000000000000..208285131c4c1cc5a76e9b679b597521b4fd6e92 --- /dev/null +++ b/services/test/mock/include/appmgr/mock_ability_mgr_host.h @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H + +#include +#include + +#include "ability_manager_interface.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace AAFwk; +class mock_ability_mgr_host { +public: + mock_ability_mgr_host() {}; + ~mock_ability_mgr_host() {}; +}; + +class MockAbilityMgrStub : public IRemoteStub { +public: + using Uri = OHOS::Uri; + MockAbilityMgrStub() = default; + virtual ~MockAbilityMgrStub() = default; + + virtual int StartAbility(const AAFwk::Want &want, int requestCode = -1) override + { + return 0; + } + virtual int StartAbility( + const AAFwk::Want &want, const sptr &callerToken, int requestCode = -1) override + { + return 0; + } + virtual int StartAbility(const Want &want, const sptr &callerToken, + int requestCode, int requestUid) override + { + return 0; + } + virtual int TerminateAbility( + const sptr &token, int resultCode, const AAFwk::Want *resultWant = nullptr) override + { + return 0; + } + virtual int MinimizeAbility(const sptr &token) override + { + return 0; + } + virtual int ConnectAbility(const AAFwk::Want &want, const sptr &connect, + const sptr &callerToken) override + { + return 0; + } + virtual int DisconnectAbility(const sptr &connect) override + { + return 0; + } + virtual sptr AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) override + { + return nullptr; + } + virtual int ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) override + { + return 0; + } + virtual void AddWindowInfo(const sptr &token, int32_t windowToken) override + { + return; + } + virtual int AttachAbilityThread( + const sptr &scheduler, const sptr &token) override + { + return 0; + } + virtual int AbilityTransitionDone(const sptr &token, int state, const PacMap &saveData) override + { + return 0; + } + virtual int ScheduleConnectAbilityDone( + const sptr &token, const sptr &remoteObject) override + { + return 0; + } + virtual int ScheduleDisconnectAbilityDone(const sptr &token) override + { + return 0; + } + virtual int ScheduleCommandAbilityDone(const sptr &token) override + { + return 0; + } + virtual void DumpState(const std::string &args, std::vector &state) override + { + return; + } + virtual int TerminateAbilityResult(const sptr &token, int startId) override + { + return 0; + } + virtual int StopServiceAbility(const AAFwk::Want &want, const sptr &callerToken) override + { + return 0; + } + virtual int GetAllStackInfo(AAFwk::StackInfo &stackInfo) override + { + return 0; + } + virtual int GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) override + { + return 0; + } + virtual int GetMissionSnapshot(const int32_t missionId, AAFwk::MissionPixelMap &missionPixelMap) override + { + return 0; + } + virtual int MoveMissionToTop(int32_t missionId) override + { + return 0; + } + virtual int RemoveMission(int id) override + { + return 0; + } + virtual int RemoveStack(int id) override + { + return 0; + } + virtual int KillProcess(const std::string &bundleName) override + { + return 0; + } + virtual int UninstallApp(const std::string &bundleName) override + { + return 0; + } + virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) override + { + return 0; + } + + virtual int MoveMissionToEnd(const sptr &token, const bool nonFirst) override + { + return 0; + } + + virtual bool IsFirstInMission(const sptr &token) override + { + return true; + } + + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override + { + return 0; + } + + virtual int PowerOff() override + { + return 0; + } + + virtual int PowerOn() override + { + return 0; + } + + virtual int LockMission(int missionId) override + { + return 0; + } + + virtual int UnlockMission(int missionId) override + { + return 0; + } + + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + + int GetMissionLockModeState() override + { + return 0; + } + + int UpdateConfiguration(const Configuration &config) override + { + return 0; + } + + virtual sptr GetWantSender( + const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override + { + return nullptr; + } + + virtual int SendWantSender(const sptr &target, const SenderInfo &senderInfo) override + { + return 0; + } + + virtual void CancelWantSender(const sptr &sender) override + {} + + virtual int GetPendingWantUid(const sptr &target) override + { + return 0; + } + + virtual int GetPendingWantUserId(const sptr &target) override + { + return 0; + } + + virtual std::string GetPendingWantBundleName(const sptr &target) override + { + return ""; + } + + virtual int GetPendingWantCode(const sptr &target) override + { + return 0; + } + + virtual int GetPendingWantType(const sptr &target) override + { + return 0; + } + + virtual void RegisterCancelListener( + const sptr &sender, const sptr &receiver) override + {} + + virtual void UnregisterCancelListener( + const sptr &sender, const sptr &receiver) override + {} + + virtual int GetPendingRequestWant(const sptr &target, std::shared_ptr &want) override + { + return 0; + } + virtual int SetShowOnLockScreen(bool isAllow) override + { + return 0; + } + int MoveMissionToFloatingStack(const MissionOption &missionOption) override + { + return 0; + } + int MoveMissionToSplitScreenStack(const MissionOption &primary, const MissionOption &secondary) override + { + return 0; + } + int MinimizeMultiWindow(int missionId) override + { + return 0; + } + int MaximizeMultiWindow(int missionId) override + { + return 0; + } + int GetFloatingMissions(std::vector &list) override + { + return 0; + } + int CloseMultiWindow(int missionId) override + { + return 0; + } + int SetMissionStackSetting(const StackSetting &stackSetting) override + { + return 0; + } + int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode) override + { + return 0; + } + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) override + { + return 0; + } + + void GetSystemMemoryAttr(AppExecFwk::SystemMemoryAttr &memoryInfo) override + {} + + int GetWantSenderInfo(const sptr &target, std::shared_ptr &info) override + { + return 0; + } + int ClearUpApplicationData(const std::string &bundleName) override + { + return 0; + } + int StartContinuation(const Want &want, const sptr &abilityToken, int32_t status) override + { + return 0; + } + int NotifyContinuationResult(int32_t missionId, const int32_t result) override + { + return 0; + } + int ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, + int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams) override + { + return 0; + } + int ContinueAbility(const std::string &deviceId, int32_t missionId) override + { + return 0; + } + void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) override + {} + + virtual int LockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int UnlockMissionForCleanup(int32_t missionId) override + { + return 0; + } + + virtual int RegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int UnRegisterMissionListener(const sptr &listener) override + { + return 0; + } + + virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, + std::vector &missionInfos) override + { + return 0; + } + + virtual int GetMissionInfo(const std::string& deviceId, int32_t missionId, + MissionInfo &missionInfo) override + { + return 0; + } + + virtual int CleanMission(int32_t missionId) override + { + return 0; + } + + virtual int CleanAllMissions() override + { + return 0; + } + + virtual int MoveMissionToFront(int32_t missionId) override + { + return 0; + } + virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override + { + return 0; + } + virtual int StopSyncRemoteMissions(const std::string& devId) override + { + return 0; + } + virtual int RegisterMissionListener(const std::string &deviceId, + const sptr &listener) override + { + return 0; + } + virtual int UnRegisterMissionListener(const std::string &deviceId, + const sptr &listener) override + { + return 0; + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H diff --git a/services/test/mock/include/appmgr/mock_status_receiver.h b/services/test/mock/include/appmgr/mock_status_receiver.h new file mode 100644 index 0000000000000000000000000000000000000000..2eaceceed38ab6fc83e5d404c723cb959224103a --- /dev/null +++ b/services/test/mock/include/appmgr/mock_status_receiver.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_STATUS_RECEIVER_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_STATUS_RECEIVER_H + +#include + +#include "nocopyable.h" + +#include "status_receiver_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class MockStatusReceiver : public IStatusReceiver { +public: + MockStatusReceiver() = default; + virtual ~MockStatusReceiver() override = default; + + virtual void OnStatusNotify(const int32_t progress) override; + virtual void OnFinished(const int32_t resultCode, [[maybe_unused]] const std::string &resultMsg) override; + virtual sptr AsObject() override; + int32_t GetResultCode(); + +private: + std::promise signal_; + + DISALLOW_COPY_AND_MOVE(MockStatusReceiver); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_STATUS_RECEIVER_H \ No newline at end of file diff --git a/services/test/mock/include/mock_ability_manager_proxy.h b/services/test/mock/include/mock_ability_manager_proxy.h index 9963caba0f4d62fe0eb6756064b8a3c602549437..c65309aabf5e174346441176c85d0325cadf299a 100644 --- a/services/test/mock/include/mock_ability_manager_proxy.h +++ b/services/test/mock/include/mock_ability_manager_proxy.h @@ -90,6 +90,17 @@ public: MOCK_METHOD1(GetPendingWantUserId, int(const sptr &target)); MOCK_METHOD1(SetShowOnLockScreen, int(bool isAllow)); + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + public: int id_; }; diff --git a/services/test/mock/include/mock_ability_mgr_service.h b/services/test/mock/include/mock_ability_mgr_service.h old mode 100755 new mode 100644 index 168aad5e16d1bd8bb5c3638226634c084aa025f6..d83a0c4429dae9ff06902d6517f8dab9c3b430eb --- a/services/test/mock/include/mock_ability_mgr_service.h +++ b/services/test/mock/include/mock_ability_mgr_service.h @@ -24,13 +24,14 @@ namespace OHOS { namespace AAFwk { class MockAbilityMgrService : public AbilityManagerStub { public: - MOCK_METHOD2(StartAbility, int(const Want &want, int requestCode)); - MOCK_METHOD3(StartAbility, int(const Want &want, const sptr &callerToken, int requestCode)); + MOCK_METHOD3(StartAbility, int(const Want &want, int32_t userId, int requestCode)); + MOCK_METHOD4(StartAbility, int(const Want &want, const sptr &callerToken, + int32_t userId, int requestCode)); MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); MOCK_METHOD3(TerminateAbility, int(const sptr &token, int resultCode, const Want *resultWant)); MOCK_METHOD1(MinimizeAbility, int(const sptr &token)); - MOCK_METHOD3(ConnectAbility, - int(const Want &want, const sptr &connect, const sptr &callerToken)); + MOCK_METHOD4(ConnectAbility, int(const Want &want, const sptr &connect, + const sptr &callerToken, int32_t userId)); MOCK_METHOD1(DisconnectAbility, int(const sptr &connect)); MOCK_METHOD3(AcquireDataAbility, sptr(const Uri &, bool, const sptr &)); MOCK_METHOD2(ReleaseDataAbility, int(sptr, const sptr &)); @@ -42,8 +43,11 @@ public: MOCK_METHOD1(ScheduleDisconnectAbilityDone, int(const sptr &token)); MOCK_METHOD1(ScheduleCommandAbilityDone, int(const sptr &)); MOCK_METHOD2(DumpState, void(const std::string &args, std::vector &state)); + MOCK_METHOD5( + DumpSysState, + void(const std::string &args, std::vector& info, bool isClient, bool isUserID, int UserID)); MOCK_METHOD2(TerminateAbilityResult, int(const sptr &, int startId)); - MOCK_METHOD1(StopServiceAbility, int(const Want &)); + MOCK_METHOD2(StopServiceAbility, int(const Want &, int32_t userId)); MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); MOCK_METHOD3(GetRecentMissions, int(const int32_t, const int32_t, std::vector &)); MOCK_METHOD2(GetMissionSnapshot, int(const int32_t, MissionPixelMap &)); @@ -75,8 +79,8 @@ public: MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); - MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode)); + MOCK_METHOD5(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int32_t userId, int requestCode)); MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); MOCK_METHOD2(MoveMissionToSplitScreenStack, int(const MissionOption &primary, const MissionOption &secondary)); MOCK_METHOD2( @@ -105,10 +109,26 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + MOCK_METHOD3(StartAbilityByCall, int(const Want &, const sptr &, const sptr &)); + + virtual int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int StartUser(int userId) override { return 0; @@ -137,6 +157,62 @@ public: return 0; } + virtual int ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) override + { + return 0; + } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + + virtual bool SendANRProcessID(int pid) override + { + return true; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } + void Wait() { sem_.Wait(); diff --git a/services/test/mock/include/mock_ability_scheduler.h b/services/test/mock/include/mock_ability_scheduler.h index 2d651247b8f69cfd1d9a791f61652281a83e876a..b4afe3f78cca5d9149c8dbcc8ee1c7682e2af15a 100755 --- a/services/test/mock/include/mock_ability_scheduler.h +++ b/services/test/mock/include/mock_ability_scheduler.h @@ -44,6 +44,7 @@ public: MOCK_METHOD1(ExecuteBatch, std::vector>(const std::vector> &operations)); MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { std::vector types; @@ -107,6 +108,10 @@ public: Uri urivalue(""); return urivalue; } + virtual sptr CallRequest() override + { + return sptr(nullptr); + } }; } // namespace AAFwk } // namespace OHOS diff --git a/services/test/mock/include/mock_ability_scheduler_stub.h b/services/test/mock/include/mock_ability_scheduler_stub.h index ac33739b0d9818d323347b266cf8725884f640b4..1913d5afb088e839c3f1d10432e28b0e698e94af 100755 --- a/services/test/mock/include/mock_ability_scheduler_stub.h +++ b/services/test/mock/include/mock_ability_scheduler_stub.h @@ -53,6 +53,12 @@ public: const std::vector> &operations)); MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); + + virtual sptr CallRequest() + { + return sptr(nullptr); + } }; } // namespace AAFwk } // namespace OHOS diff --git a/services/test/mock/include/mock_app_mgr_client.h b/services/test/mock/include/mock_app_mgr_client.h index 47aefe463a81c15ae3158735eeafb16056692e9c..fd8b3a43e60d4fdc14b7659c410cce110c92076e 100644 --- a/services/test/mock/include/mock_app_mgr_client.h +++ b/services/test/mock/include/mock_app_mgr_client.h @@ -31,6 +31,7 @@ public: MOCK_METHOD2(UpdateAbilityState, AppMgrResultCode(const sptr &token, const AbilityState state)); MOCK_METHOD1(KillApplication, AppMgrResultCode(const std::string &)); MOCK_METHOD1(KillProcessByAbilityToken, AppMgrResultCode(const sptr &token)); + MOCK_METHOD1(KillProcessesByUserId, AppMgrResultCode(int32_t userId)); MOCK_METHOD4(CompelVerifyPermission, int(const std::string &permission, int pid, int uid, std::string &message)); MOCK_METHOD1(AbilityAttachTimeOut, void(const sptr &token)); diff --git a/services/test/mock/include/mock_app_scheduler.h b/services/test/mock/include/mock_app_scheduler.h index ec261df051e7a1da36f54b74368bf5c17079dd01..1deff873f8eed0b28bc83c82cb9c9dd3e4680325 100644 --- a/services/test/mock/include/mock_app_scheduler.h +++ b/services/test/mock/include/mock_app_scheduler.h @@ -33,7 +33,7 @@ public: MOCK_METHOD0(ScheduleForegroundApplication, void()); MOCK_METHOD0(ScheduleBackgroundApplication, void()); MOCK_METHOD0(ScheduleTerminateApplication, void()); - MOCK_METHOD1(ScheduleLaunchApplication, void(const AppExecFwk::AppLaunchData &)); + MOCK_METHOD2(ScheduleLaunchApplication, void(const AppExecFwk::AppLaunchData &, const Configuration &config)); MOCK_METHOD2(ScheduleLaunchAbility, void(const AppExecFwk::AbilityInfo &, const sptr &)); MOCK_METHOD1(ScheduleCleanAbility, void(const sptr &)); MOCK_METHOD1(ScheduleProfileChanged, void(const AppExecFwk::Profile &)); diff --git a/services/test/mock/include/mock_bundle_mgr.h b/services/test/mock/include/mock_bundle_mgr.h index c3bfb9e307d47761378559df4543edf1b0766cb2..127a7b8be033a05f7c0cece161fca71127ad0e6a 100644 --- a/services/test/mock/include/mock_bundle_mgr.h +++ b/services/test/mock/include/mock_bundle_mgr.h @@ -258,6 +258,8 @@ public: MOCK_METHOD2(GetShortcutInfos, bool(const std::string &bundleName, std::vector &shortcutInfos)); MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector &abilityInfos)); + MOCK_METHOD4(GetDistributedBundleInfo, bool(const std::string &networkId, int32_t userId, + const std::string &bundleName, DistributedBundleInfo &distributedBundleInfo)); }; class BundleMgrStub : public IRemoteStub { @@ -373,7 +375,12 @@ public: { return true; } - + virtual bool GetDistributedBundleInfo( + const std::string &networkId, int32_t userId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) override + { + return true; + } BundleMgrService() { abilityInfoMap_.emplace(COM_IX_HIWORLD, HiWordInfo); diff --git a/services/test/mock/src/appmgr/mock_status_receiver.cpp b/services/test/mock/src/appmgr/mock_status_receiver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e843a6d68b2d55760ce6f2f1c75df6b64cecf97 --- /dev/null +++ b/services/test/mock/src/appmgr/mock_status_receiver.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "mock_status_receiver.h" + +namespace OHOS { +namespace AppExecFwk { +void MockStatusReceiver::OnFinished(const int32_t resultCode, [[maybe_unused]] const std::string &resultMsg) +{ + signal_.set_value(resultCode); +} + +void MockStatusReceiver::OnStatusNotify(const int32_t progress) +{ + return; +} + +sptr MockStatusReceiver::AsObject() +{ + return nullptr; +} + +int32_t MockStatusReceiver::GetResultCode() +{ + auto future = signal_.get_future(); + future.wait(); + return future.get(); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/mock/src/appmgr/system_ability_helper.cpp b/services/test/mock/src/appmgr/system_ability_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c7567701c2f8cabf31e402d97d28ebda660bb8f --- /dev/null +++ b/services/test/mock/src/appmgr/system_ability_helper.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "system_ability_helper.h" + +#include + +#include "app_log_wrapper.h" +#include "mock_ability_mgr_host.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +static std::map> g_abilities; + +sptr SystemAbilityHelper::GetSystemAbility(const int32_t systemAbilityId) +{ + APP_LOGD("mock system ability helper get %{public}d system ability", systemAbilityId); + auto iter = g_abilities.find(systemAbilityId); + if (iter != g_abilities.end()) { + return iter->second; + } + if (systemAbilityId == ABILITY_MGR_SERVICE_ID) { + return new MockAbilityMgrStub(); + } + return nullptr; +} + +bool SystemAbilityHelper::AddSystemAbility(const int32_t systemAbilityId, const sptr &systemAbility) +{ + if (g_abilities.erase(systemAbilityId) > 0) { + APP_LOGD("mock system ability helper add system ability erase exist key"); + } + APP_LOGD("mock system ability helper emplace %{public}d system ability", systemAbilityId); + g_abilities.emplace(systemAbilityId, systemAbility); + // mock helper always return true. + return true; +} + +bool SystemAbilityHelper::RemoveSystemAbility(const int32_t systemAbilityId) +{ + APP_LOGD("mock system ability helper remove system ability"); + if (g_abilities.erase(systemAbilityId) > 0) { + APP_LOGD("mock system ability helper remove %{public}d system ability erase exist key", systemAbilityId); + } + // mock helper always return true. + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/ability_mgr_service_test/BUILD.gn b/services/test/moduletest/ability_mgr_service_test/BUILD.gn index da3fc8dad7424fba8cfd37536ccc8f7e13caed30..beb1a9a0f44f6f387d268bf2fdff260ae1bafb3d 100644 --- a/services/test/moduletest/ability_mgr_service_test/BUILD.gn +++ b/services/test/moduletest/ability_mgr_service_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" ohos_moduletest("ability_mgr_module_test") { module_out_path = module_output_path @@ -22,7 +22,9 @@ ohos_moduletest("ability_mgr_module_test") { include_dirs = [ "${services_path}/test/mock/include", "//third_party/jsoncpp/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager/include", + "//base/hiviewdfx/hicollie/interfaces/native/innerkits/include/xcollie", ] sources = [ "ability_mgr_module_test.cpp" ] @@ -40,6 +42,8 @@ ohos_moduletest("ability_mgr_module_test") { "//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_stack_manager.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_token_stub.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/call_container.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/call_record.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/caller_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/connection_record.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/data_ability_manager.cpp", @@ -76,28 +80,32 @@ ohos_moduletest("ability_mgr_module_test") { "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager_public_config", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/sa_mgr:sa_mgr_mock_config", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base_sdk_config", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appmgr_sdk_config", + "${aafwk_path}/interfaces/innerkits/app_manager:appmgr_sdk_config", ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${innerkits_path}/base:base", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${innerkits_path}/want:want", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//third_party/jsoncpp:jsoncpp", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] @@ -106,6 +114,7 @@ ohos_moduletest("ability_mgr_module_test") { "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", "dsoftbus_standard:softbus_client", + "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", diff --git a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp index 2e5de6b2087d4003729b3f8deb5135d4abf90850..1c49229fb3f9eb24ba7555f6ae9512b3e4add2b3 100644 --- a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp +++ b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp @@ -35,7 +35,6 @@ #include "ability_manager_service.h" #include "ability_connect_callback_proxy.h" #include "ability_config.h" -#include "configuration_distributor.h" #include "pending_want_manager.h" #include "pending_want_record.h" #undef private @@ -43,6 +42,7 @@ #include "wants_info.h" #include "want_receiver_stub.h" #include "want_sender_stub.h" +#include "os_account_manager.h" using namespace std::placeholders; using namespace testing::ext; @@ -185,12 +185,8 @@ static void OnStartAms() AbilityMgrModuleTest::abilityMgrServ_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->pendingWantManager_); - AbilityMgrModuleTest::abilityMgrServ_->configuration_ = std::make_shared(); - EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->configuration_); - AbilityMgrModuleTest::abilityMgrServ_->GetGlobalConfiguration(); - int userId = AbilityMgrModuleTest::abilityMgrServ_->GetUserId(); - AbilityMgrModuleTest::abilityMgrServ_->SetStackManager(userId); + AbilityMgrModuleTest::abilityMgrServ_->SetStackManager(userId, true); AbilityMgrModuleTest::abilityMgrServ_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->systemAppManager_); @@ -1791,175 +1787,6 @@ HWTEST_F(AbilityMgrModuleTest, AmsConfigurationParameter_027, TestSize.Level1) EXPECT_EQ(startstatusbar, abilityMgrServ_->amsConfigResolver_->GetStatusBarState()); EXPECT_EQ(startnavigationbar, abilityMgrServ_->amsConfigResolver_->GetNavigationBarState()); } -/* - * Feature: AbilityManagerService - * Function: UpdateConfiguration - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: normal ability, page - */ -HWTEST_F(AbilityMgrModuleTest, UpdateConfiguration_028, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - std::string abilityName = "MusicAbility"; - std::string bundleName = "com.ix.hiMusic"; - - SetActive(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); - Want want = CreateWant(abilityName, bundleName); - auto startRef = abilityMgrServ_->StartAbility(want); - EXPECT_EQ(startRef, 0); - - auto abilityRecord = abilityMgrServ_->GetStackManager()->GetCurrentTopAbility(); - EXPECT_TRUE(abilityRecord); - - int displeyId = 1001; - std::string key = GlobalConfigurationKey::SYSTEM_LANGUAGE; - std::string val = "Chinese"; - auto Compare = [displeyId, key, val](const AppExecFwk::Configuration &config) { - auto item = config.GetItem(displeyId, key); - EXPECT_EQ(item, val); - }; - - sptr scheduler(new MockAbilityScheduler()); - EXPECT_CALL(*scheduler, ScheduleUpdateConfiguration(_)) - .Times(2) - .WillOnce(Return()) - .WillOnce(Invoke(Compare)); - - auto ref = abilityMgrServ_->AttachAbilityThread(scheduler, abilityRecord->GetToken()); - EXPECT_EQ(ref, 0); - - int size = DelayedSingleton::GetInstance()->observerList_.size(); - EXPECT_TRUE(size > 0); - - AppExecFwk::Configuration newConfig; - newConfig.AddItem(displeyId, key, val); - - auto updateRef = abilityMgrServ_->UpdateConfiguration(newConfig); - EXPECT_EQ(updateRef, 0); - - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(abilityRecord->GetToken(), 0, saveData); - - int num = size - 1; - size = DelayedSingleton::GetInstance()->observerList_.size(); - EXPECT_EQ(size, num); -} - -/* - * Feature: AbilityManagerService - * Function: UpdateConfiguration - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: service ability - */ -HWTEST_F(AbilityMgrModuleTest, UpdateConfiguration_029, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - std::string abilityName = "hiService"; - std::string bundleName = "com.ix.hiService"; - - SetActive(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); - Want want = CreateWant(abilityName, bundleName); - auto startRef = abilityMgrServ_->StartAbility(want); - EXPECT_EQ(startRef, 0); - - std::shared_ptr abilityRecord = abilityMgrServ_->GetStackManager()->GetCurrentTopAbility(); - EXPECT_TRUE(abilityRecord); - - int displeyId = 1001; - std::string key = GlobalConfigurationKey::SYSTEM_LANGUAGE; - std::string val = "German"; - auto Compare = [displeyId, key, val](const AppExecFwk::Configuration &config) { - auto item = config.GetItem(displeyId, key); - EXPECT_EQ(item, val); - }; - - sptr scheduler(new MockAbilityScheduler()); - EXPECT_CALL(*scheduler, ScheduleUpdateConfiguration(_)) - .Times(2) - .WillOnce(Return()) - .WillOnce(Invoke(Compare)); - - abilityMgrServ_->AttachAbilityThread(scheduler, abilityRecord->GetToken()); - - int size = DelayedSingleton::GetInstance()->observerList_.size(); - EXPECT_TRUE(size > 0); - - AppExecFwk::Configuration newConfig; - newConfig.AddItem(displeyId, key, val); - - auto updateRef = abilityMgrServ_->UpdateConfiguration(newConfig); - EXPECT_EQ(updateRef, 0); - - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(abilityRecord->GetToken(), 0, saveData); - - int num = size - 1; - size = DelayedSingleton::GetInstance()->observerList_.size(); - EXPECT_EQ(size, num); -} - -/* - * Feature: AbilityManagerService - * Function: UpdateConfiguration - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: luncher ability - */ -HWTEST_F(AbilityMgrModuleTest, UpdateConfiguration_030, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - std::string abilityName = "hiworld"; - std::string bundleName = "com.ix.hiworld"; - - SetActive(); - Want want = CreateWant(abilityName, bundleName); - auto startRef = abilityMgrServ_->StartAbility(want); - EXPECT_EQ(startRef, 0); - - std::shared_ptr abilityRecord = abilityMgrServ_->GetStackManager()->GetCurrentTopAbility(); - EXPECT_TRUE(abilityRecord); - - int displeyId = 1001; - std::string key = GlobalConfigurationKey::SYSTEM_LANGUAGE; - std::string val = "Italian"; - auto Compare = [displeyId, key, val](const AppExecFwk::Configuration &config) { - auto item = config.GetItem(displeyId, key); - EXPECT_EQ(item, val); - }; - - sptr scheduler(new MockAbilityScheduler()); - EXPECT_CALL(*scheduler, ScheduleUpdateConfiguration(_)) - .Times(2) - .WillOnce(Return()) - .WillOnce(Invoke(Compare)); - - abilityMgrServ_->AttachAbilityThread(scheduler, abilityRecord->GetToken()); - - int size = DelayedSingleton::GetInstance()->observerList_.size(); - EXPECT_TRUE(size > 0); - - AppExecFwk::Configuration newConfig; - newConfig.AddItem(displeyId, key, val); - - auto updateRef = abilityMgrServ_->UpdateConfiguration(newConfig); - EXPECT_EQ(updateRef, 0); - - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(abilityRecord->GetToken(), 0, saveData); - - int num = size - 1; - size = DelayedSingleton::GetInstance()->observerList_.size(); - EXPECT_EQ(size, num); -} /* * Function: UninstallApp diff --git a/services/test/moduletest/ability_record_test/BUILD.gn b/services/test/moduletest/ability_record_test/BUILD.gn index 613042090198d96bd970b40180d331938d82fefb..d4769d67f211a157da47d59d2c055fa1e332b85e 100644 --- a/services/test/moduletest/ability_record_test/BUILD.gn +++ b/services/test/moduletest/ability_record_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" EVENT_DIR = "//base/notification/ces_standard" ohos_moduletest("AbilityRecordModuleTest") { @@ -24,7 +24,9 @@ ohos_moduletest("AbilityRecordModuleTest") { "${EVENT_DIR}/frameworks/core/include", "${EVENT_DIR}/interfaces/innerkits/native/include", "//third_party/jsoncpp/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager/include", + "//base/hiviewdfx/hicollie/interfaces/native/innerkits/include/xcollie", ] sources = [ @@ -42,6 +44,8 @@ ohos_moduletest("AbilityRecordModuleTest") { "${services_path}/abilitymgr/src/ability_stack_manager.cpp", "${services_path}/abilitymgr/src/ability_token_stub.cpp", "${services_path}/abilitymgr/src/app_scheduler.cpp", + "${services_path}/abilitymgr/src/call_container.cpp", + "${services_path}/abilitymgr/src/call_record.cpp", "${services_path}/abilitymgr/src/caller_info.cpp", "${services_path}/abilitymgr/src/connection_record.cpp", "${services_path}/abilitymgr/src/data_ability_manager.cpp", @@ -87,19 +91,24 @@ ohos_moduletest("AbilityRecordModuleTest") { deps = [ "${innerkits_path}/base:base", "${innerkits_path}/want:want", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//third_party/jsoncpp:jsoncpp", + "//third_party/libpng:libpng", "//utils/native/base:utilsbase", ] @@ -108,6 +117,7 @@ ohos_moduletest("AbilityRecordModuleTest") { "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", "dsoftbus_standard:softbus_client", + "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", diff --git a/services/test/moduletest/ability_record_test/ability_record_module_test.cpp b/services/test/moduletest/ability_record_test/ability_record_module_test.cpp index 46e23d75fc931f1dc2bd220cced03365c83e49fc..e2d993272ff357d24c5b62e2bbf434e87a577bab 100644 --- a/services/test/moduletest/ability_record_test/ability_record_module_test.cpp +++ b/services/test/moduletest/ability_record_test/ability_record_module_test.cpp @@ -32,6 +32,7 @@ #include "connection_record.h" #include "mock_app_mgr_client.h" #include "mock_ability_scheduler_stub.h" +#include "os_account_manager.h" #undef private using namespace testing::ext; @@ -319,7 +320,7 @@ HWTEST_F(AbilityRecordModuleTest, AbilityScheduler_001, TestSize.Level3) for (int i = 0; i < COUNT; ++i) { EXPECT_CALL(*mockAbilityScheduerStub, ScheduleSaveAbilityState()).Times(1); - + // Activate auto mockActivateHandler = [&](const Want &want, const LifeCycleStateInfo &lifeCycleStateInfo) { testResult = (lifeCycleStateInfo.state == AbilityLifeCycleState::ABILITY_STATE_ACTIVE); diff --git a/services/test/moduletest/ability_stack_test/BUILD.gn b/services/test/moduletest/ability_stack_test/BUILD.gn index 1ff05c1af5d08ed7f30ee190d9be7a24730271c3..3a0d5cb3cfaeb7b6e65f05fbafac6ae7c31a5071 100644 --- a/services/test/moduletest/ability_stack_test/BUILD.gn +++ b/services/test/moduletest/ability_stack_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" ohos_moduletest("ability_stack_module_test") { module_out_path = module_output_path @@ -22,7 +22,9 @@ ohos_moduletest("ability_stack_module_test") { include_dirs = [ "${services_path}/test/mock/include", "//third_party/jsoncpp/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager/include", + "//base/hiviewdfx/hicollie/interfaces/native/innerkits/include/xcollie", ] sources = [ "ability_stack_module_test.cpp" ] @@ -40,6 +42,8 @@ ohos_moduletest("ability_stack_module_test") { "//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_stack_manager.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_token_stub.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/call_container.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/call_record.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/caller_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/connection_record.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/data_ability_manager.cpp", @@ -75,7 +79,7 @@ ohos_moduletest("ability_stack_module_test") { "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager_public_config", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/sa_mgr:sa_mgr_mock_config", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base_sdk_config", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appmgr_sdk_config", + "${aafwk_path}/interfaces/innerkits/app_manager:appmgr_sdk_config", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", ] cflags = [] @@ -83,21 +87,26 @@ ohos_moduletest("ability_stack_module_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${innerkits_path}/base:base", "${innerkits_path}/want:want", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//third_party/jsoncpp:jsoncpp", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] @@ -106,6 +115,7 @@ ohos_moduletest("ability_stack_module_test") { "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", "dsoftbus_standard:softbus_client", + "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "native_appdatamgr:native_appdatafwk", diff --git a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp index 85fff73c8f39ca352d8ab330ba74e336cc2f957d..e1edffa368ead64b17b7de906b2251f11c0e175f 100644 --- a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp +++ b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp @@ -34,7 +34,7 @@ #include "mock_bundle_mgr.h" #include "sa_mgr_client.h" #include "system_ability_definition.h" - +#include "os_account_manager.h" using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace testing; @@ -97,7 +97,7 @@ void AbilityStackModuleTest::OnStartabilityMs(std::shared_ptrpendingWantManager_); int userId = abilityMs->GetUserId(); - abilityMs->SetStackManager(userId); + abilityMs->SetStackManager(userId, true); abilityMs->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs->systemAppManager_); diff --git a/services/test/moduletest/common/ams/BUILD.gn b/services/test/moduletest/common/ams/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..6f2847bf6a709a8bb77e1a1daaf153590f520805 --- /dev/null +++ b/services/test/moduletest/common/ams/BUILD.gn @@ -0,0 +1,122 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_source_set("appmgr_mst_source") { + testonly = true + + sources = [ + "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/ams_mgr_scheduler.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", + "${services_path}/appmgr/src/app_lifecycle_deal.cpp", + "${services_path}/appmgr/src/app_mgr_service.cpp", + "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", + "${services_path}/appmgr/src/app_mgr_service_inner.cpp", + "${services_path}/appmgr/src/app_process_manager.cpp", + "${services_path}/appmgr/src/app_running_manager.cpp", + "${services_path}/appmgr/src/app_running_record.cpp", + "${services_path}/appmgr/src/app_spawn_client.cpp", + "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", + "${services_path}/appmgr/src/app_spawn_socket.cpp", + "${services_path}/appmgr/src/cgroup_manager.cpp", + "${services_path}/appmgr/src/lmks_client.cpp", + "${services_path}/appmgr/src/module_running_record.cpp", + "${services_path}/appmgr/src/process_optimizer.cpp", + "${services_path}/appmgr/src/process_optimizer_uba.cpp", + "${services_path}/appmgr/src/remote_client_manager.cpp", + "${services_path}/appmgr/test/mock/src/mock_bundle_manager.cpp", + + #"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/app_resident_process_info.cpp", + ] + + defines = [ "APP_LOG_TAG = \"AppMgrService\"" ] + + include_dirs = [ + "//third_party/json/include", + "${services_path}/appmgr/test/mock/include", + "${services_path}/appmgr/include/lmks", + "//base/account/os_account/frameworks/common/database/include", + "//base/account/os_account/frameworks/common/account_error/include", + ] + + public_configs = [ + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_config", + "${services_path}/test:services_module_test_config", + "${services_path}/appmgr:appmgr_config", + "${services_path}/test:services_mock_ams_config", + "${aafwk_path}/interfaces/innerkits/app_manager:appmgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base_sdk_config", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core_config", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:public_libeventhandler_config", + "//foundation/aafwk/standard/interfaces/innerkits/want:want_public_config", + "//foundation/aafwk/standard/interfaces/innerkits/base:base_public_config", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy_config", + "//utils/native/base:utils_config", + "//third_party/googletest:gtest_config", + "//third_party/googletest:gmock_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + public_deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "appspawn:appspawn_socket_client", + "bytrace_standard:bytrace_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("moduletest") { + testonly = true + + deps = [ + "ability_running_record_test:moduletest", + "app_life_cycle_test:moduletest", + "app_mgr_service_test:moduletest", + "app_recent_list_test:moduletest", + "app_running_record_test:moduletest", + "app_service_flow_test:moduletest", + "ipc_ams_mgr_test:moduletest", + "ipc_app_mgr_test:moduletest", + "ipc_app_scheduler_test:moduletest", + "service_app_spawn_client_test:moduletest", + "service_event_drive_test:moduletest", + "service_start_process_test:moduletest", + + # "process_optimizer_uba_test:moduletest", + ] +} diff --git a/services/test/moduletest/common/ams/ability_running_record_test/BUILD.gn b/services/test/moduletest/common/ams/ability_running_record_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..16ca5ba126c887c707a1459f77639b8d7b7e8325 --- /dev/null +++ b/services/test/moduletest/common/ams/ability_running_record_test/BUILD.gn @@ -0,0 +1,36 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsAbilityRunningRecordModuleTest") { + module_out_path = module_output_path + include_dirs = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include/hilog/", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + sources = [ "ams_ability_running_record_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsAbilityRunningRecordModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp b/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c00685518f8f47960fc56218bc4861f48f39a00 --- /dev/null +++ b/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp @@ -0,0 +1,498 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_running_record.h" +#include +#include "app_log_wrapper.h" +#include "app_record_id.h" +#include "app_scheduler_host.h" +#include "ability_info.h" +#include "application_info.h" +#include "app_running_record.h" +#include "mock_ability_token.h" + +using namespace testing::ext; +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string APP_RECORD_NAME = "App_Name_Z"; +const std::string ABILITY_RECORD_NAME = "Ability_Name_Z"; +// schedule phase +const int NONE_SCHEDULED = 0; +const int FOREGROUND_SCHEDULED = 1 << 0; +const int BACKGROUND_SCHEDULED = 1 << 1; +const int TERMINATE_SCHEDULED = 1 << 2; +const int SHRINK_MEMORY_SCHEDULED = 1 << 3; +const int LOW_MEMORY_SCHEDULED = 1 << 4; +const int LAUNCH_APPLICATION_SCHEDULED = 1 << 5; +const int LAUNCH_ABILITY_SCHEDULED = 1 << 6; +const int CLEAN_ABILITY_SCHEDULED = 1 << 7; +const int PROFILE_CHANGED_SCHEDULED = 1 << 8; +const int SCHEDULE_CONFIGURATION_UPDATED = 1 << 9; +const int ABILITY_RUNNING_RECORD_NUM = 1000; +} // namespace +class MockedSchedulerBase { +public: + MockedSchedulerBase() + { + Reset(); + } + + virtual ~MockedSchedulerBase() + {} + + virtual void Reset() + { + scheduled_ = NONE_SCHEDULED; + } + + bool IsScheduled(const int scheduledPhase) const + { + return (scheduled_ & scheduledPhase) > 0; + } + +protected: + unsigned int scheduled_ = NONE_SCHEDULED; +}; + +class MockedApplication : public AppSchedulerHost, public MockedSchedulerBase { +public: + void ScheduleForegroundApplication() override + { + scheduled_ |= FOREGROUND_SCHEDULED; + } + void ScheduleBackgroundApplication() override + { + scheduled_ |= BACKGROUND_SCHEDULED; + } + void ScheduleTerminateApplication() override + { + scheduled_ |= TERMINATE_SCHEDULED; + } + void ScheduleShrinkMemory(const int) override + { + scheduled_ |= SHRINK_MEMORY_SCHEDULED; + } + void ScheduleLowMemory() override + { + scheduled_ |= LOW_MEMORY_SCHEDULED; + } + void ScheduleLaunchApplication(const AppLaunchData &, const Configuration &) override + { + scheduled_ |= LAUNCH_APPLICATION_SCHEDULED; + appLaunchTime++; + } + void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) override + { + scheduled_ |= LAUNCH_ABILITY_SCHEDULED; + abilityLaunchTime++; + } + void ScheduleCleanAbility(const sptr &) override + { + scheduled_ |= CLEAN_ABILITY_SCHEDULED; + } + void ScheduleProfileChanged(const Profile &) override + { + scheduled_ |= PROFILE_CHANGED_SCHEDULED; + } + void ScheduleConfigurationUpdated(const Configuration &config) + { + scheduled_ |= SCHEDULE_CONFIGURATION_UPDATED; + } + void ScheduleProcessSecurityExit() + {} + int GetAppLaunchTime() const + { + return appLaunchTime; + } + int GetAbilityLaunchTime() const + { + return abilityLaunchTime; + } + + void ScheduleAbilityStage(const HapModuleInfo &) override + {} + + void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) override + {} + + void Reset() override + { + MockedSchedulerBase::Reset(); + abilityLaunchTime = 0; + appLaunchTime = 0; + } + +private: + int abilityLaunchTime = 0; + int appLaunchTime = 0; +}; + +class AmsAbilityRunningRecordModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr QueryAppRunningRecord(); + sptr QueryMockedAppSchedulerClient(); + +protected: + sptr mockedAppClient_; + sptr client_; + std::shared_ptr caseAppRunningRecord_; +}; + +void AmsAbilityRunningRecordModuleTest::SetUpTestCase() +{} + +void AmsAbilityRunningRecordModuleTest::TearDownTestCase() +{} + +void AmsAbilityRunningRecordModuleTest::SetUp() +{ + mockedAppClient_ = new (std::nothrow) MockedApplication(); +} + +void AmsAbilityRunningRecordModuleTest::TearDown() +{ + caseAppRunningRecord_.reset(); +} + +sptr AmsAbilityRunningRecordModuleTest::QueryMockedAppSchedulerClient() +{ + if (!client_) { + client_ = iface_cast(mockedAppClient_.GetRefPtr()); + } + return client_; +} + +std::shared_ptr AmsAbilityRunningRecordModuleTest::QueryAppRunningRecord() +{ + if (caseAppRunningRecord_ == nullptr) { + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + caseAppRunningRecord_.reset( + new (std::nothrow) AppRunningRecord(appInfo, AppRecordId::Create(), appInfo->bundleName)); + caseAppRunningRecord_->SetApplicationClient(QueryMockedAppSchedulerClient()); + } + return caseAppRunningRecord_; +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Create AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function creating two same names of AbilityRunningRecord. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, AddAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGI("AddAbilityRunningRecord_001 start"); + auto appRunningRecord = QueryAppRunningRecord(); + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME; + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + sptr token = new MockAbilityToken(); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + auto abilityRunningRecordWithSameName = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(abilityRunningRecordWithSameName == nullptr); + appRunningRecord->ClearAbility(caseAbilityRunningRecord); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) == nullptr); + APP_LOGI("AddAbilityRunningRecord_001 end"); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Create AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function creating more AbilityRunningRecords. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, AddAbilityRunningRecord_002, TestSize.Level1) +{ + APP_LOGI("AddAbilityRunningRecord_002 start"); + int i; + auto appRunningRecord = QueryAppRunningRecord(); + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + EXPECT_EQ(caseAbilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_BEGIN); + } + APP_LOGI("AddAbilityRunningRecord_002 end"); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function updating more AbilityRunningRecords. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, UpdateAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGI("UpdateAbilityRunningRecord_001 start"); + int i; + auto appRunningRecord = QueryAppRunningRecord(); + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + caseAbilityRunningRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); + appRunningRecord->SetState(ApplicationState::APP_STATE_FOREGROUND); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_FOREGROUND); + EXPECT_EQ(caseAbilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_FOREGROUND); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(caseAbilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_BACKGROUND); + } + APP_LOGI("UpdateAbilityRunningRecord_001 end"); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function updating an illegal state of AbilityRunningRecord. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, UpdateAbilityRunningRecord_002, TestSize.Level1) +{ + APP_LOGI("UpdateAbilityRunningRecord_002 start"); + int i; + auto appRunningRecord = QueryAppRunningRecord(); + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_END); + EXPECT_EQ(caseAbilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_BEGIN); + } + APP_LOGI("UpdateAbilityRunningRecord_002 end"); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Update AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function updating more AbilityRunningRecords. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, UpdateAbilityRunningRecord_003, TestSize.Level1) +{ + APP_LOGI("UpdateAbilityRunningRecord_003 start"); + int i; + auto appRunningRecord = QueryAppRunningRecord(); + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + caseAbilityRunningRecord->SetState(AbilityState::ABILITY_STATE_FOREGROUND); + appRunningRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(caseAbilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_BACKGROUND); + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_READY); + EXPECT_EQ(caseAbilityRunningRecord->GetState(), AbilityState::ABILITY_STATE_BACKGROUND); + } + APP_LOGI("UpdateAbilityRunningRecord_003 end"); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Clear AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function clearing more AbilityRunningRecords. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, ClearAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGI("ClearAbilityRunningRecord_001 start"); + int i; + auto appRunningRecord = QueryAppRunningRecord(); + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + } + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + auto caseAbilityRunningRecord = appRunningRecord->GetAbilityRunningRecordByToken(token); + appRunningRecord->ClearAbility(caseAbilityRunningRecord); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) == nullptr); + } + APP_LOGI("ClearAbilityRunningRecord_001 end"); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Clear AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function clearing all AbilityRunningRecords, the AbilityRunningRecord is null. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, ClearAbilityRunningRecord_002, TestSize.Level1) +{ + APP_LOGI("ClearAbilityRunningRecord_002 start"); + int i; + auto appRunningRecord = QueryAppRunningRecord(); + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + appRunningRecord->ClearAbility(caseAbilityRunningRecord); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) == nullptr); + } + if (i == ABILITY_RUNNING_RECORD_NUM) { + auto abilityMap = appRunningRecord->GetAbilities(); + EXPECT_TRUE(abilityMap.empty()); + } + APP_LOGI("ClearAbilityRunningRecord_002 end"); +} + +/* + * Feature: AMS + * Function: AbilityRunningRecord + * SubFunction: NA + * FunctionPoints: Add ,update and Clear AbilityRunningRecord succeed + * EnvConditions: NA + * CaseDescription: Verify the function Add ,update and clear more AbilityRunningRecords. + */ +HWTEST_F(AmsAbilityRunningRecordModuleTest, OperateAbilityRunningRecord_001, TestSize.Level1) +{ + APP_LOGI("OperateAbilityRunningRecord_001 start"); + int i; + auto appRunningRecord = QueryAppRunningRecord(); + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); + EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); + } + for (i = 0; i < ABILITY_RUNNING_RECORD_NUM; i++) { + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME + "_" + std::to_string(i); + sptr token = new MockAbilityToken(); + auto caseAbilityRunningRecord = appRunningRecord->GetAbilityRunningRecordByToken(token); + appRunningRecord->ClearAbility(caseAbilityRunningRecord); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) == nullptr); + } + APP_LOGI("OperateAbilityRunningRecord_001 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/test/moduletest/common/ams/app_life_cycle_test/BUILD.gn b/services/test/moduletest/common/ams/app_life_cycle_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..0a03ebe4df9c01bf2239499c0def04999d16ab2f --- /dev/null +++ b/services/test/moduletest/common/ams/app_life_cycle_test/BUILD.gn @@ -0,0 +1,37 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsAppLifeCycleModuleTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/hiviewdfx/hilog/interfaces/native/kits/include/hilog/", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + sources = [ "ams_app_life_cycle_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsAppLifeCycleModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..41ae0c5b356eb4ae89040f745f099435a68b994d --- /dev/null +++ b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp @@ -0,0 +1,1825 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "remote_client_manager.h" +#include "app_mgr_service_inner.h" +#undef private + +#include +#include +#include "app_launch_data.h" +#include "iremote_object.h" +#include "app_state_callback_proxy.h" +#include "app_log_wrapper.h" +#include "refbase.h" +#include "mock_bundle_manager.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" +#include "mock_app_spawn_socket.h" +#include "mock_iapp_state_callback.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; + +namespace { +const int32_t ABILITY_NUM = 100; +const int32_t APPLICATION_NUM = 100; +const int32_t INDEX_NUM_100 = 100; +const int32_t INDEX_NUM_MAX = 100; +const std::string TEST_APP_NAME = "com.ohos.test.helloworld"; +const std::string TEST_ABILITY_NAME = "test_ability_"; +#define CHECK_POINTER_IS_NULLPTR(object) \ + do { \ + if (object == nullptr) { \ + return; \ + } \ + } while (0) +} // namespace + +namespace OHOS { +namespace AppExecFwk { +struct TestProcessInfo { + pid_t pid = 0; + bool isStart = false; +}; +// specify process condition +class AmsAppLifeCycleModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr GetApplicationInfo(const std::string &appName) const; + std::shared_ptr GetAbilityInfo(const std::string &abilityIndex, const std::string &name, + const std::string &process, const std::string &applicationName) const; + void StartAppProcess(const pid_t &pid) const; + std::shared_ptr StartProcessAndLoadAbility(const sptr &mockAppScheduler, + const sptr &token, const std::shared_ptr &abilityInfo, + const std::shared_ptr &appInfo, const TestProcessInfo &testProcessInfo) const; + void ChangeAbilityStateAfterAppStart(const sptr &mockAppScheduler, const pid_t &pid) const; + void ChangeAbilityStateToForegroud(const sptr &mockAppScheduler, + const std::shared_ptr &appRunningRecord, const sptr &token, + const bool isChange = false) const; + void ChangeAbilityStateToBackGroud(const sptr &mockAppScheduler, + const std::shared_ptr &appRunningRecord, const sptr &token, + const bool isChange = false) const; + void ChangeAbilityStateToTerminate( + const sptr &mockAppScheduler, const sptr &token) const; + void ChangeAppToTerminate(const sptr &mockAppScheduler, + const std::shared_ptr &appRunningRecord, const sptr &token, + const bool isStop = false) const; + void CheckState(const std::shared_ptr &appRunningRecord, const sptr &token, + const AbilityState abilityState, const ApplicationState appState) const; + void CheckStateAfterClearAbility(const std::shared_ptr &appRunningRecord, + const std::vector> &tokens, const int32_t &recordId, + const sptr &mockAppScheduler) const; + void CheckStateAfterChangeAbility(const std::shared_ptr &appRunningRecord, + const std::vector> &tokens, const sptr &mockAppScheduler); + void CreateAppRecentList(const int32_t appNum); + + sptr GetAbilityToken(); + +protected: + std::shared_ptr serviceInner_ = nullptr; + sptr mockToken_ = nullptr; + sptr mockAppStateCallbackStub_ = nullptr; + std::shared_ptr inner_ = nullptr; + sptr mockBundleMgr; + std::shared_ptr handler_ = nullptr; +}; + +void AmsAppLifeCycleModuleTest::SetUpTestCase() +{} + +void AmsAppLifeCycleModuleTest::TearDownTestCase() +{} + +void AmsAppLifeCycleModuleTest::SetUp() +{ + serviceInner_.reset(new (std::nothrow) AppMgrServiceInner()); + mockAppStateCallbackStub_ = new (std::nothrow) MockAppStateCallback(); + + inner_ = std::make_shared(); + + if (serviceInner_ && mockAppStateCallbackStub_) { + auto mockAppStateCallbackProxy = iface_cast(mockAppStateCallbackStub_); + if (mockAppStateCallbackProxy) { + serviceInner_->RegisterAppStateCallback(mockAppStateCallbackProxy); + inner_->RegisterAppStateCallback(mockAppStateCallbackProxy); + } + } + + mockBundleMgr = new (std::nothrow) BundleMgrService(); + serviceInner_->SetBundleManager(mockBundleMgr); + + serviceInner_->ProcessOptimizerInit(); + + auto runner = EventRunner::Create("AmsAppLifeCycleModuleTest"); + handler_ = std::make_shared(runner, serviceInner_); + serviceInner_->SetEventHandler(handler_); +} + +void AmsAppLifeCycleModuleTest::TearDown() +{ + serviceInner_.reset(); + mockAppStateCallbackStub_.clear(); +} + +std::shared_ptr AmsAppLifeCycleModuleTest::GetApplicationInfo(const std::string &appName) const +{ + auto appInfo = std::make_shared(); + appInfo->name = appName; + appInfo->bundleName = appName; + return appInfo; +} + +std::shared_ptr AmsAppLifeCycleModuleTest::GetAbilityInfo(const std::string &abilityIndex, + const std::string &name, const std::string &process, const std::string &applicationName) const +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = name + abilityIndex; + if (!process.empty()) { + abilityInfo->process = process; + } + abilityInfo->applicationName = applicationName; + abilityInfo->applicationInfo.bundleName = applicationName; + return abilityInfo; +} + +std::shared_ptr AmsAppLifeCycleModuleTest::StartProcessAndLoadAbility( + const sptr &mockAppScheduler, const sptr &token, + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const TestProcessInfo &testProcessInfo) const +{ + if (!testProcessInfo.isStart) { + StartAppProcess(testProcessInfo.pid); + } else { + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + } + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + + std::shared_ptr record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + if (record == nullptr) { + EXPECT_TRUE(false); + } else { + pid_t newPid = record->GetPriorityObject()->GetPid(); + EXPECT_EQ(newPid, testProcessInfo.pid); + } + return record; +} + +void AmsAppLifeCycleModuleTest::StartAppProcess(const pid_t &pid) const +{ + MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockClientPtr); + + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + EXPECT_CALL(*mockAppStateCallbackStub_, OnAppStateChanged(_)).Times(1); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); +} + +void AmsAppLifeCycleModuleTest::ChangeAbilityStateAfterAppStart( + const sptr &mockAppScheduler, const pid_t &pid) const +{ + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchApplication(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + serviceInner_->AttachApplication(pid, client); +} + +void AmsAppLifeCycleModuleTest::ChangeAbilityStateToForegroud(const sptr &mockAppScheduler, + const std::shared_ptr &appRunningRecord, const sptr &token, + const bool isChange) const +{ + if (!isChange) { + EXPECT_CALL(*mockAppScheduler, ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*mockAppStateCallbackStub_, OnAppStateChanged(_)).Times(testing::AtLeast(1)); + EXPECT_CALL(*mockAppStateCallbackStub_, OnAbilityRequestDone(_, _)).Times(testing::AtLeast(1)); + } + + serviceInner_->UpdateAbilityState(token, AbilityState::ABILITY_STATE_FOREGROUND); + + if (!isChange) { + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); + int32_t recordId = appRunningRecord->GetRecordId(); + serviceInner_->ApplicationForegrounded(recordId); + } +} + +void AmsAppLifeCycleModuleTest::ChangeAbilityStateToBackGroud(const sptr &mockAppScheduler, + const std::shared_ptr &appRunningRecord, const sptr &token, + const bool isChange) const +{ + if (!isChange) { + EXPECT_CALL(*mockAppScheduler, ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*mockAppStateCallbackStub_, OnAppStateChanged(_)).Times(testing::AtLeast(1)); + EXPECT_CALL(*mockAppStateCallbackStub_, OnAbilityRequestDone(_, _)).Times(testing::AtLeast(1)); + } + + serviceInner_->UpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); + + if (!isChange) { + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); + int32_t recordId = appRunningRecord->GetRecordId(); + serviceInner_->ApplicationBackgrounded(recordId); + } +} + +void AmsAppLifeCycleModuleTest::ChangeAppToTerminate(const sptr &mockAppScheduler, + const std::shared_ptr &appRunningRecord, const sptr &token, + const bool isStop) const +{ + ChangeAbilityStateToTerminate(mockAppScheduler, token); + + if (isStop) { + EXPECT_CALL(*mockAppScheduler, ScheduleTerminateApplication()).Times(1); + EXPECT_CALL(*mockAppStateCallbackStub_, OnAppStateChanged(_)).Times(testing::AtLeast(1)); + serviceInner_->AbilityTerminated(token); + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); + int32_t recordId = appRunningRecord->GetRecordId(); + serviceInner_->ApplicationTerminated(recordId); + } else { + serviceInner_->AbilityTerminated(token); + } +} + +void AmsAppLifeCycleModuleTest::ChangeAbilityStateToTerminate( + const sptr &mockAppScheduler, const sptr &token) const +{ + EXPECT_CALL(*mockAppScheduler, ScheduleCleanAbility(_)).Times(1); + serviceInner_->TerminateAbility(token); +} + +void AmsAppLifeCycleModuleTest::CheckState(const std::shared_ptr &appRunningRecord, + const sptr &token, const AbilityState abilityState, const ApplicationState appState) const +{ + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); + auto abilityRunningRecord = appRunningRecord->GetAbilityRunningRecordByToken(token); + ApplicationState getAppState = appRunningRecord->GetState(); + EXPECT_EQ(appState, getAppState); + EXPECT_NE(abilityRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRunningRecord); + AbilityState getAbilityState = abilityRunningRecord->GetState(); + EXPECT_EQ(abilityState, getAbilityState); +} + +void AmsAppLifeCycleModuleTest::CheckStateAfterClearAbility(const std::shared_ptr &appRunningRecord, + const std::vector> &tokens, const int32_t &recordId, + const sptr &mockAppScheduler) const +{ + unsigned long size = tokens.size(); + for (unsigned long i = 0; i < size; i++) { + if (i != size - 1) { + ChangeAppToTerminate(mockAppScheduler, appRunningRecord, tokens[i], false); + ApplicationState getAppState = appRunningRecord->GetState(); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, getAppState); + } else { + ChangeAppToTerminate(mockAppScheduler, appRunningRecord, tokens[i], true); + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId); + EXPECT_EQ(nullptr, record); + } + } +} + +void AmsAppLifeCycleModuleTest::CheckStateAfterChangeAbility(const std::shared_ptr &appRunningRecord, + const std::vector> &tokens, const sptr &mockAppScheduler) +{ + unsigned long size = tokens.size(); + for (unsigned long i = 0; i < size; i++) { + if (i != size - 1) { + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, tokens[i], true); + CheckState(appRunningRecord, + tokens[i], + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_FOREGROUND); + } else { + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, tokens[i], false); + CheckState(appRunningRecord, + tokens[i], + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + } + } +} + +void AmsAppLifeCycleModuleTest::CreateAppRecentList(const int32_t appNum) +{ + for (int32_t i = INDEX_NUM_MAX - appNum + 1; i <= INDEX_NUM_MAX; i++) { + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(i); + appInfo->bundleName = appInfo->name; + abilityInfo->name = TEST_ABILITY_NAME + std::to_string(i); + abilityInfo->applicationName = TEST_APP_NAME + std::to_string(i); + abilityInfo->applicationInfo.bundleName = appInfo->name; + pid_t pid = i; + sptr token = new (std::nothrow) MockAbilityToken(); + MockAppSpawnClient *mockedSpawnClient = new (std::nothrow) MockAppSpawnClient(); + EXPECT_TRUE(mockedSpawnClient); + EXPECT_CALL(*mockedSpawnClient, StartProcess(_, _)) + .Times(1) + .WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + EXPECT_CALL(*mockAppStateCallbackStub_, OnAppStateChanged(_)).Times(1); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + } + return; +} + +sptr AmsAppLifeCycleModuleTest::GetAbilityToken() +{ + if (mockToken_ != nullptr) { + return mockToken_; + } + mockToken_ = new (std::nothrow) MockAbilityToken(); + return mockToken_; +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of ability + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start app + * 2.switch ability to foreground and call ScheduleForegroundApplication API to enable Application + * foreground + * 3.switch ability to background and call ScheduleBackgroundApplication API to enable Application + * background + * 4.terminate ability + * 5.call ScheduleTerminateApplication API to make app terminated + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid = 1024; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); + auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + EXPECT_TRUE(mockAppScheduler); + + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + auto appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + int32_t recordId = appRunningRecord->GetRecordId(); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + ChangeAppToTerminate(mockAppScheduler, appRunningRecord, token, true); + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of abilities + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start app + * 2.switch ability to foreground and call ScheduleForegroundApplication API to enable Application + * foreground + * 3.load other ability, and switch last ability to background and call ScheduleBackgroundApplication + * API to enable Application background + * 4.terminate every ability + * 5.call ScheduleTerminateApplication API to make app terminated + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_002, TestSize.Level3) +{ + pid_t pid = 1023; + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + std::shared_ptr appRunningRecord = nullptr; + std::vector> tokens; + auto abilityInfo = std::make_shared(); + auto appInfo = std::make_shared(); + sptr token; + int32_t recordId; + bool flag = false; + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + + for (int i = 0; i < ABILITY_NUM; i++) { + abilityInfo = GetAbilityInfo(std::to_string(i), "MainAbility", "p1", "com.ohos.test.helloworld"); + appInfo = GetApplicationInfo("com.ohos.test.helloworld"); + token = new (std::nothrow) MockAbilityToken(); + tokens.push_back(token); + testProcessInfo.isStart = flag; + appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + if (!flag) { + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid); + recordId = appRunningRecord->GetRecordId(); + flag = true; + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + } else { + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_BACKGROUND); + } + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token); + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + } + auto abilities = appRunningRecord->GetAbilities(); + int size = abilities.size(); + EXPECT_EQ(size, ABILITY_NUM); + CheckStateAfterClearAbility(appRunningRecord, tokens, recordId, mockAppScheduler); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of abilities at the same time + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start 1000 abilities + * 2.switch every ability to foreground + * 3.switch every ability to background + * 4.terminate every ability + * 5.call ScheduleTerminateApplication API to make app terminated + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_003, TestSize.Level3) +{ + pid_t pid = 1025; + EXPECT_TRUE(serviceInner_); + std::shared_ptr appRunningRecord = nullptr; + std::vector> tokens; + auto abilityInfo = std::make_shared(); + auto appInfo = std::make_shared(); + sptr token; + int32_t recordId; + bool flag = false; + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + + for (int i = 0; i < ABILITY_NUM; i++) { + abilityInfo = GetAbilityInfo(std::to_string(i), "MainAbility", "p1", "com.ohos.test.helloworld1"); + appInfo = GetApplicationInfo("com.ohos.test.helloworld1"); + token = new (std::nothrow) MockAbilityToken(); + tokens.push_back(token); + + testProcessInfo.isStart = flag; + appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + if (!flag) { + ChangeAbilityStateAfterAppStart(mockAppScheduler, testProcessInfo.pid); + recordId = appRunningRecord->GetRecordId(); + flag = true; + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + } else { + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_FOREGROUND); + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token, true); + } + } + CheckStateAfterChangeAbility(appRunningRecord, tokens, mockAppScheduler); + CheckStateAfterClearAbility(appRunningRecord, tokens, recordId, mockAppScheduler); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of abilities + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start app + * 2.switch ability to foreground and call ScheduleForegroundApplication API to enable Application + * foreground + * 3.switch ability to background and call ScheduleBackgroundApplication API to enable Application + * background + * 4.repeat step 2~3 1000 times + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_004, TestSize.Level3) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid = 1024; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p3", "com.ohos.test.helloworld"); + auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); + + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + + auto appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + int count = 1000; + while (count > 0) { + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token); + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + count--; + } +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of ability + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start app + * 2.switch ability to foreground and call ScheduleForegroundApplication API to enable Application + * foreground + * 3.switch ability to background + * 4.start new ability to foreground + * 5.switch ability to background and call ScheduleBackgroundApplication API to enable Application + * background + * 6.call ScheduleTerminateApplication API to make app terminated + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_005, TestSize.Level2) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid = 1024; + + sptr token0 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); + auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); + + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + + auto appRunningRecord = + StartProcessAndLoadAbility(mockAppScheduler, token0, abilityInfo0, appInfo, testProcessInfo); + + int32_t recordId = appRunningRecord->GetRecordId(); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid); + CheckState(appRunningRecord, token0, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token0); + CheckState( + appRunningRecord, token0, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token0); + CheckState( + appRunningRecord, token0, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + sptr token1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo1 = GetAbilityInfo("1", "SubAbility", "p1", "com.ohos.test.helloworld"); + testProcessInfo.isStart = true; + appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token1, abilityInfo1, appInfo, testProcessInfo); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token1); + CheckState( + appRunningRecord, token1, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token1); + CheckState( + appRunningRecord, token1, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + ChangeAppToTerminate(mockAppScheduler, appRunningRecord, token0); + ChangeAppToTerminate(mockAppScheduler, appRunningRecord, token1, true); + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of ability + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start app + * 2.switch ability to foreground and call ScheduleForegroundApplication API to enable Application + * foreground + * 3.switch ability to background and call ScheduleBackgroundApplication API to enable Application + * background + * 4.through appName kill application + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + + pid_t pid = fork(); + if (pid == 0) { + pause(); + exit(0); + } + + EXPECT_TRUE(pid > 0); + usleep(50000); + + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); + auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); + appInfo->bundleName = "com.ohos.test.helloworld"; + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + + auto appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + int32_t recordId = appRunningRecord->GetRecordId(); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication(appInfo->bundleName); + EXPECT_EQ(ret, 0); + serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of ability + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start app + * 2.switch ability to foreground and call ScheduleForegroundApplication API to enable Application + * foreground + * 3.switch ability to background and call ScheduleBackgroundApplication API to enable Application + * background + * 4.terminate ability + * 5.call ScheduleTerminateApplication API to make app terminated + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_007, TestSize.Level2) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid = 1024; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); + auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + + auto appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + int32_t recordId = appRunningRecord->GetRecordId(); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + ChangeAppToTerminate(mockAppScheduler, appRunningRecord, token, true); + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of ability + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start app + * 2.switch ability to foreground and call ScheduleForegroundApplication API to enable Application + * foreground + * 3.switch ability to background and call ScheduleBackgroundApplication API to enable Application + * background + * 4.call loadAbility API to start new app + * 5.switch ability to foreground and call ScheduleForegroundApplication API to enable new Application + * foreground + * 6.switch ability to background and call ScheduleBackgroundApplication API to enable new Application + * background + * 7.terminate ability + * 8.call ScheduleTerminateApplication API to make app terminated + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_008, TestSize.Level2) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + pid_t pid_1 = 2048; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld0"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld0"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld1"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld1"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + + testProcessInfo.pid = pid_1; + testProcessInfo.isStart = false; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord_0, token_0); + CheckState( + appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord_0, token_0); + CheckState( + appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid_1); + CheckState(appRunningRecord_1, token_1, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord_1, token_1); + CheckState( + appRunningRecord_1, token_1, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord_1, token_1); + CheckState( + appRunningRecord_1, token_1, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + ChangeAppToTerminate(mockAppScheduler, appRunningRecord_0, token_0, true); + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId_0); + EXPECT_EQ(nullptr, record); + + ChangeAppToTerminate(mockAppScheduler, appRunningRecord_1, token_1, true); + record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId_1); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test app life cycle change with the start of abilities at the same time + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start 100 app + * 2.switch every ability to foreground + * 3.switch every ability to background + * 4.terminate every ability + * 5.call ScheduleTerminateApplication API to make app terminated + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_009, TestSize.Level3) +{ + pid_t pid = 1025; + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + std::shared_ptr appRunningRecord = nullptr; + auto abilityInfo = std::make_shared(); + auto appInfo = std::make_shared(); + sptr token; + int32_t recordId; + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + + TestProcessInfo testProcessInfo; + + for (int i = 0; i < APPLICATION_NUM; i++) { + abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld1"); + appInfo = GetApplicationInfo("com.ohos.test.helloworld1"); + token = new (std::nothrow) MockAbilityToken(); + pid += i; + + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + ChangeAbilityStateAfterAppStart(mockAppScheduler, testProcessInfo.pid); + recordId = appRunningRecord->GetRecordId(); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + + ChangeAbilityStateToBackGroud(mockAppScheduler, appRunningRecord, token); + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + ChangeAppToTerminate(mockAppScheduler, appRunningRecord, token, true); + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId); + EXPECT_EQ(nullptr, record); + } +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test get and stop all process. + * EnvConditions: system running normally + * CaseDescription: 1.call loadAbility API to start 100 app + * 2.stop all process + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_010, TestSize.Level3) +{ + pid_t pid = 1025; + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + std::shared_ptr appRunningRecord = nullptr; + int32_t recordId[APPLICATION_NUM]; + sptr mockAppScheduler[APPLICATION_NUM]; + + TestProcessInfo testProcessInfo; + for (int i = 0; i < APPLICATION_NUM; i++) { + mockAppScheduler[i] = new MockAppScheduler(); + + char index[32]; + int ref = snprintf_s(index, sizeof(index), sizeof(index) - 1, "%d", i); + EXPECT_TRUE(ref > 0); + char name[128]; + ref = snprintf_s(name, sizeof(name), sizeof(name) - 1, "com.ohos.test.helloworld%d", i); + EXPECT_TRUE(ref > 0); + auto abilityInfo = GetAbilityInfo(index, "MainAbility", index, name); + auto appInfo = GetApplicationInfo(name); + auto token = new (std::nothrow) MockAbilityToken(); + pid += i; + + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + + appRunningRecord = + StartProcessAndLoadAbility(mockAppScheduler[i], token, abilityInfo, appInfo, testProcessInfo); + EXPECT_TRUE(appRunningRecord); + + ChangeAbilityStateAfterAppStart(mockAppScheduler[i], testProcessInfo.pid); + + recordId[i] = appRunningRecord->GetRecordId(); + + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + ChangeAbilityStateToForegroud(mockAppScheduler[i], appRunningRecord, token); + + ChangeAbilityStateToBackGroud(mockAppScheduler[i], appRunningRecord, token); + CheckState( + appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + EXPECT_CALL(*mockAppScheduler[i], ScheduleProcessSecurityExit()).Times(1); + } + + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); + std::vector allRunningProcessInfo; + serviceInner_->GetAllRunningProcesses(allRunningProcessInfo); + EXPECT_EQ(allRunningProcessInfo.size(), size_t(APPLICATION_NUM)); + + serviceInner_->StopAllProcess(); + + for (int i = 0; i < APPLICATION_NUM; i++) { + serviceInner_->OnRemoteDied(mockAppScheduler[i]); // A faked death recipient. + auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId[i]); + EXPECT_EQ(nullptr, record); + } +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test getrecentapplist and removeappfromrecentlist all process. + * EnvConditions: system running normally + * CaseDescription: 1.call getrecentapplist API to get current app list + * 2.call removeappfromrecentlist API to remove current app list + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_011, TestSize.Level1) +{ + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_100); + EXPECT_EQ(INDEX_NUM_100, static_cast(serviceInner_->GetRecentAppList().size())); + for (int32_t i = INDEX_NUM_MAX; i > 0; i--) { + std::shared_ptr appInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(i); + appInfo->bundleName = appInfo->name; // specify process condition + auto appTaskInfo = + serviceInner_->appProcessManager_->GetAppTaskInfoByProcessName(appInfo->name, appInfo->bundleName); + serviceInner_->appProcessManager_->RemoveAppFromRecentList(appTaskInfo); + } + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test getrecentapplist and clearrecentappList all process. + * EnvConditions: system running normally + * CaseDescription: 1.call getrecentapplist API to get current app list + * 2.call clearrecentapplist API to clear current app list + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_012, TestSize.Level1) +{ + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_100); + EXPECT_EQ(INDEX_NUM_100, static_cast(serviceInner_->GetRecentAppList().size())); + + serviceInner_->appProcessManager_->ClearRecentAppList(); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test get and stop all process. + * EnvConditions: system running normally + * CaseDescription: OnStop + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_013, TestSize.Level3) +{ + EXPECT_TRUE(serviceInner_); + EXPECT_TRUE(serviceInner_->remoteClientManager_); + EXPECT_TRUE(serviceInner_->remoteClientManager_->GetSpawnClient()); + + auto mockAppSpawnSocket = std::make_shared(); + EXPECT_TRUE(mockAppSpawnSocket); + serviceInner_->remoteClientManager_->GetSpawnClient()->SetSocket(mockAppSpawnSocket); + + EXPECT_EQ(serviceInner_->QueryAppSpawnConnectionState(), SpawnConnectionState::STATE_NOT_CONNECT); + + EXPECT_CALL(*mockAppSpawnSocket, OpenAppSpawnConnection()).Times(1).WillOnce(Return(0)); + + int ret = serviceInner_->OpenAppSpawnConnection(); + EXPECT_EQ(ret, 0); + EXPECT_EQ(serviceInner_->QueryAppSpawnConnectionState(), SpawnConnectionState::STATE_CONNECTED); + + EXPECT_CALL(*mockAppSpawnSocket, CloseAppSpawnConnection()).Times(1); + + serviceInner_->OnStop(); + usleep(50000); + EXPECT_EQ(serviceInner_->QueryAppSpawnConnectionState(), SpawnConnectionState::STATE_NOT_CONNECT); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: test get app Running Record,When the app is added for the first time + * EnvConditions: system running normally + * CaseDescription: GetOrCreateAppRunningRecord + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_014, TestSize.Level1) +{ + + pid_t pid = 1000; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + sptr mockAppScheduler = new MockAppScheduler(); + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + auto appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + + // Because GetOrCreateAppRunningRecord was called in LoadAbility. + // When the app is added for the first time + EXPECT_EQ(appRunningRecord->GetName(), "com.ohos.test.special"); + EXPECT_EQ(appRunningRecord->GetProcessName(), "p1"); +} + +/* + * Feature: Ams + * Function: AppLifeCycle + * SubFunction: NA + * FunctionPoints: Ability Status change received + * EnvConditions: system running normally + * CaseDescription: OnAbilityRequestDone + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_015, TestSize.Level1) +{ + pid_t pid = 1000; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + sptr mockAppScheduler = new MockAppScheduler(); + TestProcessInfo testProcessInfo; + testProcessInfo.pid = pid; + testProcessInfo.isStart = false; + + auto appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler, token, abilityInfo, appInfo, testProcessInfo); + + EXPECT_CALL(*mockAppScheduler, ScheduleBackgroundApplication()).Times(1); + ChangeAbilityStateAfterAppStart(mockAppScheduler, testProcessInfo.pid); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord, token); + CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + std::weak_ptr inner = inner_; + appRunningRecord->SetAppMgrServiceInner(inner); + + appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); +} + +/* + * Feature: Ams + * Function: AbilityBehaviorAnalysis + * SubFunction: NA + * FunctionPoints: Ability Status change received + * EnvConditions: system running normally + * CaseDescription: Ability record update(specify process mode) + */ +HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_01, TestSize.Level1) +{ + const int32_t formateVaule = 0; + const int32_t visibility = 1; + const int32_t perceptibility = 1; + const int32_t connectionState = 1; + + pid_t pid = 123; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "pNew", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + sptr mockAppScheduler = new MockAppScheduler(); + + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); + + StartAppProcess(pid); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + std::shared_ptr record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + if (record == nullptr) { + EXPECT_TRUE(false); + } else { + pid_t newPid = record->GetPriorityObject()->GetPid(); + EXPECT_EQ(newPid, pid); + } + + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord->GetVisibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetPerceptibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetConnectionState(), formateVaule); + + serviceInner_->AbilityBehaviorAnalysis(token, nullptr, visibility, perceptibility, connectionState); + + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(token); + auto abilityRecord_1 = appRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord_1->GetToken(), token); + EXPECT_EQ(abilityRecord_1->GetPreToken(), nullptr); + EXPECT_EQ(abilityRecord_1->GetVisibility(), visibility); + EXPECT_EQ(abilityRecord_1->GetPerceptibility(), perceptibility); + EXPECT_EQ(abilityRecord_1->GetConnectionState(), connectionState); +} + +/* + * Feature: Ams + * Function: AbilityBehaviorAnalysis + * SubFunction: NA + * FunctionPoints: Ability Status change received + * EnvConditions: system running normally + * CaseDescription: Ability record update(specify process mode and assign visibility) + */ +HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_02, TestSize.Level1) +{ + const int32_t formateVaule = 0; + const int32_t visibility = 1; + const int32_t perceptibility = 0; + const int32_t connectionState = 0; + + pid_t pid = 123; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "pNew", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + sptr mockAppScheduler = new MockAppScheduler(); + + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); + + StartAppProcess(pid); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + std::shared_ptr record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + if (record == nullptr) { + EXPECT_TRUE(false); + } else { + pid_t newPid = record->GetPriorityObject()->GetPid(); + EXPECT_EQ(newPid, pid); + } + + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord->GetVisibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetPerceptibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetConnectionState(), formateVaule); + + serviceInner_->AbilityBehaviorAnalysis(token, nullptr, visibility, perceptibility, connectionState); + + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(token); + auto abilityRecord_1 = appRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord_1->GetToken(), token); + EXPECT_EQ(abilityRecord_1->GetPreToken(), nullptr); + EXPECT_EQ(abilityRecord_1->GetVisibility(), visibility); + EXPECT_EQ(abilityRecord_1->GetPerceptibility(), perceptibility); + EXPECT_EQ(abilityRecord_1->GetConnectionState(), connectionState); +} + +/* + * Feature: Ams + * Function: AbilityBehaviorAnalysis + * SubFunction: NA + * FunctionPoints: Ability Status change received + * EnvConditions: system running normally + * CaseDescription: Ability record update(specify process mode and assign perceptibility) + */ +HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_03, TestSize.Level1) +{ + const int32_t formateVaule = 0; + const int32_t visibility = 0; + const int32_t perceptibility = 1; + const int32_t connectionState = 0; + + pid_t pid = 123; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "pNew", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + sptr mockAppScheduler = new MockAppScheduler(); + + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); + + StartAppProcess(pid); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + std::shared_ptr record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + if (record == nullptr) { + EXPECT_TRUE(false); + } else { + pid_t newPid = record->GetPriorityObject()->GetPid(); + EXPECT_EQ(newPid, pid); + } + + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord->GetVisibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetPerceptibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetConnectionState(), formateVaule); + + serviceInner_->AbilityBehaviorAnalysis(token, nullptr, visibility, perceptibility, connectionState); + + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(token); + auto abilityRecord_1 = appRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord_1->GetToken(), token); + EXPECT_EQ(abilityRecord_1->GetPreToken(), nullptr); + EXPECT_EQ(abilityRecord_1->GetVisibility(), visibility); + EXPECT_EQ(abilityRecord_1->GetPerceptibility(), perceptibility); + EXPECT_EQ(abilityRecord_1->GetConnectionState(), connectionState); +} + +/* + * Feature: Ams + * Function: AbilityBehaviorAnalysis + * SubFunction: NA + * FunctionPoints: Ability Status change received + * EnvConditions: system running normally + * CaseDescription: Ability record update(specify process mode and assign connectionState) + */ +HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_04, TestSize.Level1) +{ + const int32_t formateVaule = 0; + const int32_t visibility = 0; + const int32_t perceptibility = 0; + const int32_t connectionState = 1; + + pid_t pid = 123; + sptr token = GetAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "pNew", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + sptr mockAppScheduler = new MockAppScheduler(); + + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); + + StartAppProcess(pid); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + std::shared_ptr record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + if (record == nullptr) { + EXPECT_TRUE(false); + } else { + pid_t newPid = record->GetPriorityObject()->GetPid(); + EXPECT_EQ(newPid, pid); + } + + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord->GetVisibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetPerceptibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetConnectionState(), formateVaule); + + serviceInner_->AbilityBehaviorAnalysis(token, nullptr, visibility, perceptibility, connectionState); + + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(token); + auto abilityRecord_1 = appRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord_1->GetToken(), token); + EXPECT_EQ(abilityRecord_1->GetPreToken(), nullptr); + EXPECT_EQ(abilityRecord_1->GetVisibility(), visibility); + EXPECT_EQ(abilityRecord_1->GetPerceptibility(), perceptibility); + EXPECT_EQ(abilityRecord_1->GetConnectionState(), connectionState); +} + +/* + * Feature: Ams + * Function: AbilityBehaviorAnalysis + * SubFunction: NA + * FunctionPoints: Ability Status change received + * EnvConditions: system running normally + * CaseDescription: Ability record update(specify process mode and assign proken) + */ +HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_05, TestSize.Level1) +{ + const int32_t formateVaule = 0; + const int32_t visibility = 0; + const int32_t perceptibility = 0; + const int32_t connectionState = 0; + + pid_t pid = 123; + sptr token = new (std::nothrow) MockAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "pNew", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + sptr mockAppScheduler = new MockAppScheduler(); + + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); + + StartAppProcess(pid); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + std::shared_ptr record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + if (record == nullptr) { + EXPECT_TRUE(false); + } else { + pid_t newPid = record->GetPriorityObject()->GetPid(); + EXPECT_EQ(newPid, pid); + } + + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord->GetVisibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetPerceptibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetConnectionState(), formateVaule); + + sptr preToken = new (std::nothrow) MockAbilityToken(); + serviceInner_->AbilityBehaviorAnalysis(token, preToken, visibility, perceptibility, connectionState); + + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(token); + auto abilityRecord_1 = appRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord_1->GetToken(), token); + EXPECT_EQ(abilityRecord_1->GetPreToken(), preToken); + EXPECT_EQ(abilityRecord_1->GetVisibility(), visibility); + EXPECT_EQ(abilityRecord_1->GetPerceptibility(), perceptibility); + EXPECT_EQ(abilityRecord_1->GetConnectionState(), connectionState); +} + +/* + * Feature: Ams + * Function: AbilityBehaviorAnalysis + * SubFunction: NA + * FunctionPoints: Ability Status change received + * EnvConditions: system running normally + * CaseDescription: Ability record update(specify process mode and assign bundleName) + */ +HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_06, TestSize.Level1) +{ + const int32_t formateVaule = 0; + const int32_t visibility = 0; + const int32_t perceptibility = 0; + const int32_t connectionState = 0; + + pid_t pid = 123; + sptr token = new (std::nothrow) MockAbilityToken(); + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "pNew", "com.ohos.test.special"); + auto appInfo = GetApplicationInfo("com.ohos.test.special"); + appInfo->bundleName = appInfo->name; + sptr mockAppScheduler = new MockAppScheduler(); + + sptr bundleMgr = new BundleMgrService(); + serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); + + StartAppProcess(pid); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + std::shared_ptr record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + if (record == nullptr) { + EXPECT_TRUE(false); + } else { + pid_t newPid = record->GetPriorityObject()->GetPid(); + EXPECT_EQ(newPid, pid); + } + + auto abilityRecord = record->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord->GetVisibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetPerceptibility(), formateVaule); + EXPECT_EQ(abilityRecord->GetConnectionState(), formateVaule); + + sptr preToken = new (std::nothrow) MockAbilityToken(); + serviceInner_->AbilityBehaviorAnalysis(token, preToken, visibility, perceptibility, connectionState); + + auto appRecord = serviceInner_->GetAppRunningRecordByAbilityToken(token); + auto abilityRecord_1 = appRecord->GetAbilityRunningRecordByToken(token); + + EXPECT_EQ(abilityRecord_1->GetToken(), token); + EXPECT_EQ(abilityRecord_1->GetPreToken(), preToken); + EXPECT_EQ(abilityRecord_1->GetVisibility(), visibility); + EXPECT_EQ(abilityRecord_1->GetPerceptibility(), perceptibility); + EXPECT_EQ(abilityRecord_1->GetConnectionState(), connectionState); +} + +/* + * Feature: AbilityMgr + * Function: LoadResidentProcess + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, LoadResidentProcess_01, TestSize.Level1) +{ + pid_t pid = 123; + sptr token = GetAbilityToken(); + std::string appName = "KeepAliveApp"; + std::string proc = "KeepAliveApplication"; + int uid = 2100; + BundleInfo info; + info.name = proc; + info.uid = uid; + + ApplicationInfo appInfo; + appInfo.name = "KeepAliveApp"; + appInfo.bundleName = "KeepAliveApplication"; + appInfo.uid = uid; + + info.applicationInfo = appInfo; + sptr mockAppScheduler = new MockAppScheduler(); + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, info); + EXPECT_FALSE(appRecord); + + StartAppProcess(pid); + serviceInner_->LoadResidentProcess(); + appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, info); + EXPECT_TRUE(appRecord); + pid_t newPid = appRecord->GetPriorityObject()->GetPid(); + EXPECT_TRUE(newPid == pid); +} + +/* + * Feature: AbilityMgr + * Function: StartResidentProcess + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, StartResidentProcess_01, TestSize.Level1) +{ + pid_t pid = 123; + sptr token = GetAbilityToken(); + std::string appName = "KeepAliveApp"; + std::string proc = "KeepAliveApplication"; + int uid = 2100; + + std::vector infos; + BundleInfo info; + info.name = proc; + info.uid = uid; + + ApplicationInfo appInfo; + appInfo.name = "KeepAliveApp"; + appInfo.bundleName = "KeepAliveApplication"; + appInfo.uid = 2100; + + info.applicationInfo = appInfo; + HapModuleInfo hapModuleInfo; + hapModuleInfo.name = "Module"; + HapModuleInfo hapModuleInfo1; + hapModuleInfo1.name = "Module1"; + info.hapModuleInfos.push_back(hapModuleInfo); + info.hapModuleInfos.push_back(hapModuleInfo1); + + infos.push_back(info); + + sptr mockAppScheduler = new MockAppScheduler(); + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, info); + EXPECT_FALSE(appRecord); + + StartAppProcess(pid); + serviceInner_->StartResidentProcess(infos, -1); + appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist(appName, proc, uid, info); + EXPECT_TRUE(appRecord); + pid_t newPid = appRecord->GetPriorityObject()->GetPid(); + EXPECT_TRUE(newPid == pid); +} + +/* + * Feature: AbilityMgr + * Function: LoadAbility + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, LoadAbility_001, TestSize.Level1) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + pid_t pid_1 = 2048; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld0"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld0"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility1", "p2", "com.ohos.test.helloworld0"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld0"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + + testProcessInfo.pid = pid_1; + testProcessInfo.isStart = false; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + EXPECT_NE(recordId_0, recordId_1); + EXPECT_NE(appRunningRecord_0, appRunningRecord_1); + auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(2, static_cast(appMap.size())); +} + +/* + * Feature: AbilityMgr + * Function: LoadAbility + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, LoadAbility_002, TestSize.Level1) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld0"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld0"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility1", "p1", "com.ohos.test.helloworld0"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld0"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord_0, token_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_FOREGROUND, + ApplicationState::APP_STATE_FOREGROUND); + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = true; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + EXPECT_EQ(recordId_0, recordId_1); + EXPECT_EQ(appRunningRecord_0, appRunningRecord_1); + auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(1, static_cast(appMap.size())); +} + +/* + * Feature: AbilityMgr + * Function: LoadAbility + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, LoadAbility_003, TestSize.Level1) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld101"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld101"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility1", "p1", "com.ohos.test.helloworld102"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld102"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord_0, token_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_FOREGROUND, + ApplicationState::APP_STATE_FOREGROUND); + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = true; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + EXPECT_EQ(recordId_0, recordId_1); + EXPECT_EQ(appRunningRecord_0, appRunningRecord_1); + auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(1, static_cast(appMap.size())); +} + +/* + * Feature: AbilityMgr + * Function: LoadAbility + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, LoadAbility_004, TestSize.Level1) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + pid_t pid_1 = 2048; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld103"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld103"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility1", "p1", "com.ohos.test.helloworld104"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld104"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + + testProcessInfo.pid = pid_1; + testProcessInfo.isStart = false; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + EXPECT_NE(recordId_0, recordId_1); + EXPECT_NE(appRunningRecord_0, appRunningRecord_1); + auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(2, static_cast(appMap.size())); +} + +/* + * Feature: AbilityMgr + * Function: KillApplication + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_001, TestSize.Level1) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + pid_t pid_1 = 2048; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld0"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld0"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility1", "p2", "com.ohos.test.helloworld0"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld0"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr mockAppScheduler1 = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + + testProcessInfo.pid = pid_1; + testProcessInfo.isStart = false; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler1, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + ChangeAbilityStateAfterAppStart(mockAppScheduler1, pid_1); + CheckState(appRunningRecord_1, token_1, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + EXPECT_NE(recordId_0, recordId_1); + EXPECT_NE(appRunningRecord_0, appRunningRecord_1); + auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(2, static_cast(appMap.size())); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + EXPECT_CALL(*mockAppScheduler1, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld0"); + EXPECT_EQ(ret, 0); + serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. + auto appMap1 = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(1, static_cast(appMap1.size())); + serviceInner_->OnRemoteDied(mockAppScheduler1); + auto appMap2 = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(0, static_cast(appMap2.size())); +} + +/* + * Feature: AbilityMgr + * Function: KillApplication + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_002, TestSize.Level1) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + pid_t pid_1 = 2048; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld103"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld103"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility1", "p1", "com.ohos.test.helloworld104"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld104"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr mockAppScheduler1 = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + + testProcessInfo.pid = pid_1; + testProcessInfo.isStart = false; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler1, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + ChangeAbilityStateAfterAppStart(mockAppScheduler1, pid_1); + CheckState(appRunningRecord_1, token_1, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + EXPECT_NE(recordId_0, recordId_1); + EXPECT_NE(appRunningRecord_0, appRunningRecord_1); + auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(2, static_cast(appMap.size())); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld103"); + EXPECT_EQ(ret, 0); + serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. + auto appMap1 = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(1, static_cast(appMap1.size())); +} + +/* + * Feature: AbilityMgr + * Function: KillApplication + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: NA + */ +HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_003, TestSize.Level1) +{ + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); + pid_t pid_0 = 1024; + sptr token_0 = new (std::nothrow) MockAbilityToken(); + sptr token_1 = new (std::nothrow) MockAbilityToken(); + auto abilityInfo_0 = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld101"); + auto appInfo_0 = GetApplicationInfo("com.ohos.test.helloworld101"); + auto abilityInfo_1 = GetAbilityInfo("0", "MainAbility1", "p1", "com.ohos.test.helloworld102"); + auto appInfo_1 = GetApplicationInfo("com.ohos.test.helloworld102"); + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + TestProcessInfo testProcessInfo; + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = false; + auto appRunningRecord_0 = + StartProcessAndLoadAbility(mockAppScheduler, token_0, abilityInfo_0, appInfo_0, testProcessInfo); + ChangeAbilityStateAfterAppStart(mockAppScheduler, pid_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_READY, ApplicationState::APP_STATE_READY); + + ChangeAbilityStateToForegroud(mockAppScheduler, appRunningRecord_0, token_0); + CheckState(appRunningRecord_0, token_0, AbilityState::ABILITY_STATE_FOREGROUND, + ApplicationState::APP_STATE_FOREGROUND); + + testProcessInfo.pid = pid_0; + testProcessInfo.isStart = true; + auto appRunningRecord_1 = + StartProcessAndLoadAbility(mockAppScheduler, token_1, abilityInfo_1, appInfo_1, testProcessInfo); + int32_t recordId_0 = appRunningRecord_0->GetRecordId(); + int32_t recordId_1 = appRunningRecord_1->GetRecordId(); + EXPECT_EQ(recordId_0, recordId_1); + EXPECT_EQ(appRunningRecord_0, appRunningRecord_1); + auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(1, static_cast(appMap.size())); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld101"); + EXPECT_EQ(ret, 0); + serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. + auto appMap1 = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); + EXPECT_EQ(0, static_cast(appMap1.size())); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/app_mgr_service_test/BUILD.gn b/services/test/moduletest/common/ams/app_mgr_service_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..d14fc2bb5af3117cb1a866935ca30180ebf3a30e --- /dev/null +++ b/services/test/moduletest/common/ams/app_mgr_service_test/BUILD.gn @@ -0,0 +1,42 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsAppMgrServiceModuleTest") { + module_out_path = module_output_path + include_dirs = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include/hilog/", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + sources = [ + "//foundation/aafwk/standard/services/appmgr/src/system_environment_information.cpp", + "ams_app_mgr_service_module_test.cpp", + ] + + deps = [ + "${services_path}/test/moduletest/common/ams:appmgr_mst_source", + "//base/global/i18n_standard/frameworks/intl:intl_util", + ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsAppMgrServiceModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cf2697ee730eee1351e0f6f82f97a9515eb952e --- /dev/null +++ b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp @@ -0,0 +1,488 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_mgr_service.h" +#include "app_mgr_service_inner.h" +#undef private + +#include +#include + +#include "app_scheduler_host.h" +#include "app_scheduler_proxy.h" +#include "mock_app_mgr_service_inner.h" +#include "mock_app_spawn_socket.h" +#include "semaphore_ex.h" + +using namespace testing::ext; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; +using testing::Return; + +namespace { +constexpr int COUNT = 1; +} + +namespace OHOS { +namespace AppExecFwk { +class TestAppSchedulerImpl : public AppSchedulerHost { +public: + void ScheduleForegroundApplication() override + {} + void ScheduleBackgroundApplication() override + {} + void ScheduleTerminateApplication() override + {} + void ScheduleShrinkMemory(const int) override + {} + void ScheduleLowMemory() override + {} + void ScheduleLaunchApplication(const AppLaunchData &, const Configuration &) override + {} + void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) override + {} + void ScheduleCleanAbility(const sptr &) override + {} + void ScheduleProfileChanged(const Profile &) override + {} + void ScheduleConfigurationUpdated(const Configuration &) override + {} + void ScheduleProcessSecurityExit() override + {} + void ScheduleAbilityStage(const HapModuleInfo &) override + {} + void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) override + {} +}; +class AppMgrServiceModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + inline static std::shared_ptr mockAppMgrServiceInner_ {nullptr}; + inline static std::shared_ptr appMgrService_ {nullptr}; + inline static sptr testRemoteObject_ {nullptr}; +}; + +void AppMgrServiceModuleTest::SetUpTestCase() +{ + if (!appMgrService_) { + appMgrService_ = std::make_shared(); + } + + if (!mockAppMgrServiceInner_) { + mockAppMgrServiceInner_ = std::make_shared(); + } + + if (appMgrService_ && mockAppMgrServiceInner_) { + appMgrService_->appMgrServiceInner_ = mockAppMgrServiceInner_; + appMgrService_->OnStart(); + } + + if (!testRemoteObject_) { + testRemoteObject_ = static_cast(new TestAppSchedulerImpl); + } +} + +void AppMgrServiceModuleTest::TearDownTestCase() +{ + if (testRemoteObject_) { + testRemoteObject_.clear(); + } + + if (mockAppMgrServiceInner_) { + mockAppMgrServiceInner_.reset(); + } + + if (appMgrService_) { + appMgrService_->OnStop(); + int sleepTime = 1; + sleep(sleepTime); // Waiting for appMgrService_'s event loop backend thread exited. + if (appMgrService_->appMgrServiceInner_) { + appMgrService_->appMgrServiceInner_.reset(); + } + if (appMgrService_->amsMgrScheduler_) { + appMgrService_->amsMgrScheduler_.clear(); + } + appMgrService_.reset(); + } +} + +void AppMgrServiceModuleTest::SetUp() +{} + +void AppMgrServiceModuleTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: AttachApplication + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: AttachApplication + * CaseDescription: Check event loop AttachApplication task post from AppMgrService to AppMgrServiceInner. + */ +HWTEST_F(AppMgrServiceModuleTest, AttachApplication_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(testRemoteObject_); + + for (int i = 0; i < COUNT; ++i) { + EXPECT_CALL(*mockAppMgrServiceInner_, AddAppDeathRecipient(_, _)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner_.get(), &MockAppMgrServiceInner::Post)); + EXPECT_CALL(*mockAppMgrServiceInner_, AttachApplication(_, _)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner_.get(), &MockAppMgrServiceInner::Post)); + + sptr client; + appMgrService_->AttachApplication(client); + mockAppMgrServiceInner_->Wait(); + } +} + +/* + * Feature: AppMgrService + * Function: ApplicationForegrounded + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: ApplicationForegrounded + * CaseDescription: Check event loop ApplicationForegrounded task post from AppMgrService to AppMgrServiceInner. + */ +HWTEST_F(AppMgrServiceModuleTest, ApplicationForegrounded_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + int32_t testRecordId = 123; + bool testResult = false; + Semaphore sem(0); + + auto mockHandler = [&](const int32_t recordId) { + testResult = (recordId == testRecordId); + sem.Post(); + }; + + for (int i = 0; i < COUNT; ++i) { + testResult = false; + + EXPECT_CALL(*mockAppMgrServiceInner_, ApplicationForegrounded(_)).Times(1).WillOnce(Invoke(mockHandler)); + + appMgrService_->ApplicationForegrounded(testRecordId); + + sem.Wait(); + + EXPECT_TRUE(testResult); + } +} + +/* + * Feature: AppMgrService + * Function: ApplicationBackgrounded + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: ApplicationBackgrounded + * CaseDescription: Check event loop ApplicationBackgrounded task post from AppMgrService to AppMgrServiceInner. + */ +HWTEST_F(AppMgrServiceModuleTest, ApplicationBackgrounded_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + int32_t testRecordId = 123; + bool testResult = false; + Semaphore sem(0); + + auto mockHandler = [&](const int32_t recordId) { + testResult = (recordId == testRecordId); + sem.Post(); + }; + + for (int i = 0; i < COUNT; ++i) { + testResult = false; + + EXPECT_CALL(*mockAppMgrServiceInner_, ApplicationBackgrounded(_)).Times(1).WillOnce(Invoke(mockHandler)); + + appMgrService_->ApplicationBackgrounded(testRecordId); + + sem.Wait(); + + EXPECT_TRUE(testResult); + } +} + +/* + * Feature: AppMgrService + * Function: ApplicationTerminated + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: ApplicationTerminated + * CaseDescription: Check event loop ApplicationTerminated task post from AppMgrService to AppMgrServiceInner. + */ +HWTEST_F(AppMgrServiceModuleTest, ApplicationTerminated_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + int32_t testRecordId = 123; + bool testResult = false; + Semaphore sem(0); + + auto mockHandler = [&testResult, testRecordId, &sem](const int32_t recordId) { + testResult = (recordId == testRecordId); + sem.Post(); + }; + + for (int i = 0; i < COUNT; ++i) { + testResult = false; + + EXPECT_CALL(*mockAppMgrServiceInner_, ApplicationTerminated(_)).Times(1).WillOnce(Invoke(mockHandler)); + + appMgrService_->ApplicationTerminated(testRecordId); + + sem.Wait(); + + EXPECT_TRUE(testResult); + } +} + +/* + * Feature: AppMgrService + * Function: AbilityCleaned + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: AbilityCleaned + * CaseDescription: Check event loop AbilityCleaned task post from AppMgrService to AppMgrServiceInner. + */ +HWTEST_F(AppMgrServiceModuleTest, AbilityCleaned_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(testRemoteObject_); + + bool testResult = false; + Semaphore sem(0); + + auto mockHandler = [&testResult, &sem](const sptr &token) { + testResult = (token == testRemoteObject_); + sem.Post(); + }; + + for (int i = 0; i < COUNT; ++i) { + testResult = false; + + EXPECT_CALL(*mockAppMgrServiceInner_, AbilityTerminated(_)).Times(1).WillOnce(Invoke(mockHandler)); + + appMgrService_->AbilityCleaned(testRemoteObject_); + + sem.Wait(); + + EXPECT_TRUE(testResult); + } +} + +/* + * Feature: AppMgrService + * Function: ClearUpApplicationData + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: ClearUpApplicationData + * CaseDescription: Check event loop ClearUpApplicationData task post from AppMgrService to AppMgrServiceInner. + */ +HWTEST_F(AppMgrServiceModuleTest, ClearUpApplicationData_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + std::string testAppName("testApp"); + bool testResult = false; + Semaphore sem(0); + + auto mockHandler = [&testResult, testAppName, &sem](const std::string &appName, const int32_t, const pid_t) { + testResult = (appName == testAppName); + sem.Post(); + }; + + for (int i = 0; i < COUNT; ++i) { + testResult = false; + + EXPECT_CALL(*mockAppMgrServiceInner_, ClearUpApplicationData(_, _, _)).Times(1).WillOnce(Invoke(mockHandler)); + + appMgrService_->ClearUpApplicationData(testAppName); + + sem.Wait(); + + EXPECT_TRUE(testResult); + } +} + +/* + * Feature: AppMgrService + * Function: IsBackgroundRunningRestricted + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: IsBackgroundRunningRestricted + * CaseDescription: Check IsBackgroundRunningRestricted. + */ +HWTEST_F(AppMgrServiceModuleTest, IsBackgroundRunningRestricted_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + std::string testAppName("testApp"); + bool testResult = false; + Semaphore sem(0); + + auto mockHandler = [&testResult, testAppName, &sem](const std::string &appName) { + testResult = (appName == testAppName); + sem.Post(); + return ERR_OK; + }; + + for (int i = 0; i < COUNT; ++i) { + testResult = false; + + EXPECT_CALL(*mockAppMgrServiceInner_, IsBackgroundRunningRestricted(_)).Times(1).WillOnce(Invoke(mockHandler)); + + auto result = appMgrService_->IsBackgroundRunningRestricted(testAppName); + + sem.Wait(); + + EXPECT_TRUE(testResult); + EXPECT_EQ(result, ERR_OK); + } +} + +/* + * Feature: AppMgrService + * Function: GetAllRunningProcesses + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: GetAllRunningProcesses + * CaseDescription: Check GetAllRunningProcesses. + */ +HWTEST_F(AppMgrServiceModuleTest, GetAllRunningProcesses_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + std::vector testRunningProcessInfo; + + int32_t testPid = 456; + std::string testProcessName = "testProcess"; + + Semaphore sem(0); + auto mockHandler = [testProcessName, testPid, &sem](std::vector &runningProcessInfo) { + auto &it = runningProcessInfo.emplace_back(); + it.processName_ = testProcessName; + it.pid_ = testPid; + sem.Post(); + return ERR_OK; + }; + + for (int i = 0; i < COUNT; ++i) { + testRunningProcessInfo.clear(); + EXPECT_CALL(*mockAppMgrServiceInner_, GetAllRunningProcesses(_)).Times(1).WillOnce(Invoke(mockHandler)); + + auto result = appMgrService_->GetAllRunningProcesses(testRunningProcessInfo); + sem.Wait(); + + EXPECT_EQ(testRunningProcessInfo.size(), size_t(1)); + EXPECT_EQ(testRunningProcessInfo[0].processName_, testProcessName); + EXPECT_EQ(testRunningProcessInfo[0].pid_, testPid); + EXPECT_EQ(result, ERR_OK); + } +} + +/* + * Feature: AppMgrService + * Function: KillApplication + * SubFunction: NA + * FunctionPoints: AppMgrService => AppMgrServiceInner: KillApplication + * CaseDescription: Check KillApplication task post from AppMgrService to AppMgrServiceInner. + */ +HWTEST_F(AppMgrServiceModuleTest, KillApplication_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + std::string testBundleName("testApp"); + bool testResult = false; + Semaphore sem(0); + + auto mockHandler = [&testResult, testBundleName, &sem](const std::string &bundleName) { + testResult = (bundleName == testBundleName); + sem.Post(); + return 0; + }; + + for (int i = 0; i < COUNT; ++i) { + testResult = false; + + EXPECT_CALL(*mockAppMgrServiceInner_, KillApplication(_)).Times(1).WillOnce(Invoke(mockHandler)); + + int ret = appMgrService_->GetAmsMgr()->KillApplication(testBundleName); + + sem.Wait(); + + EXPECT_TRUE(testResult); + EXPECT_EQ(ret, 0); + } +} + +/* + * Feature: AppMgrService + * Function: QueryServiceState + * SubFunction: AppMgrService => AppMgrServiceInner: QueryAppSpawnConnectionState + * FunctionPoints: NA + * CaseDescription: Check QueryServiceState. + */ +HWTEST_F(AppMgrServiceModuleTest, QueryServiceState_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + + SpawnConnectionState testSpawnConnectionState = SpawnConnectionState::STATE_CONNECTED; + Semaphore sem(0); + + auto mockHandler = [&]() { + sem.Post(); + return testSpawnConnectionState; + }; + + for (int i = 0; i < COUNT; ++i) { + EXPECT_CALL(*mockAppMgrServiceInner_, QueryAppSpawnConnectionState()).Times(1).WillOnce(Invoke(mockHandler)); + + auto serviceState = appMgrService_->QueryServiceState(); + + sem.Wait(); + + EXPECT_EQ(serviceState.connectionState, testSpawnConnectionState); + } +} + +/* + * Feature: AppMgrService + * Function: GetAmsMgr + * SubFunction: NA + * FunctionPoints: NA + * CaseDescription: Check GetAmsMgr. + */ +HWTEST_F(AppMgrServiceModuleTest, GetAmsMgr_001, TestSize.Level1) +{ + EXPECT_TRUE(appMgrService_); + + auto amsMgr = appMgrService_->GetAmsMgr(); + + EXPECT_TRUE(amsMgr); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/app_recent_list_test/BUILD.gn b/services/test/moduletest/common/ams/app_recent_list_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..fc6c4758cf3f10f0c0b56416990e09742c412fb6 --- /dev/null +++ b/services/test/moduletest/common/ams/app_recent_list_test/BUILD.gn @@ -0,0 +1,36 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" +ohos_moduletest("AmsAppRecentListModuleTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include/hilog/", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + sources = [ "ams_app_recent_list_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsAppRecentListModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp b/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6abb9ed978dc6f15483cdac4800bfde2a61eb403 --- /dev/null +++ b/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "app_mgr_service_inner.h" +#undef private + +#include +#include + +#include "app_log_wrapper.h" +#include "refbase.h" +#include "iremote_object.h" +#include "mock_bundle_manager.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t INDEX_NUM_1 = 1; +const int32_t INDEX_NUM_2 = 2; +const int32_t INDEX_NUM_3 = 3; +const int32_t INDEX_NUM_10 = 10; +const std::string TEST_APP_NAME = "com.ohos.test.helloworld"; +const std::string TEST_ABILITY_NAME = "test_ability_"; +} // namespace + +class AmsAppRecentListModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + const std::shared_ptr GetApplicationByIndex(const int32_t index) const; + const std::shared_ptr CreateAppRunningRecordByIndex(const int32_t index) const; + void CreateAppRecentList(const int32_t appNum); + + std::unique_ptr serviceInner_{nullptr}; + sptr mockToken_{nullptr}; + sptr mockBundleMgr{nullptr}; +}; + +void AmsAppRecentListModuleTest::SetUpTestCase() +{} + +void AmsAppRecentListModuleTest::TearDownTestCase() +{} + +void AmsAppRecentListModuleTest::SetUp() +{ + serviceInner_.reset(new (std::nothrow) AppMgrServiceInner()); + mockBundleMgr = new (std::nothrow) BundleMgrService(); + serviceInner_->SetBundleManager(mockBundleMgr); +} + +void AmsAppRecentListModuleTest::TearDown() +{} + +const std::shared_ptr AmsAppRecentListModuleTest::GetApplicationByIndex(const int32_t index) const +{ + std::shared_ptr appInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(index); + return appInfo; +} + +const std::shared_ptr AmsAppRecentListModuleTest::CreateAppRunningRecordByIndex( + const int32_t index) const +{ + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(index); + abilityInfo->name = TEST_ABILITY_NAME + std::to_string(index); + abilityInfo->applicationName = appInfo->name; + abilityInfo->applicationInfo.bundleName = appInfo->name; + abilityInfo->process = appInfo->name; + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + auto appRunningRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, abilityInfo->process, abilityInfo->applicationInfo.uid, bundleInfo); + EXPECT_NE(nullptr, appRunningRecord); + return appRunningRecord; +} + +void AmsAppRecentListModuleTest::CreateAppRecentList(const int32_t appNum) +{ + for (int32_t i = 0; i < appNum; i++) { + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(i); + appInfo->bundleName = appInfo->name; + appInfo->process = appInfo->name; + abilityInfo->name = TEST_ABILITY_NAME + std::to_string(i); + abilityInfo->applicationName = appInfo->name; + abilityInfo->applicationInfo.bundleName = appInfo->name; + abilityInfo->process = appInfo->name; + pid_t pid = i; + sptr token = new (std::nothrow) MockAbilityToken(); + MockAppSpawnClient *mockedSpawnClient = new MockAppSpawnClient(); + + EXPECT_CALL(*mockedSpawnClient, StartProcess(_, _)) + .Times(1) + .WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + } + return; +} + +/* + * Feature: Ams + * Function: AppRecentList + * SubFunction: create + * FunctionPoints: Add app to RecentAppList when start a same process failed. + * EnvConditions: AppRecentList is empty. + * CaseDescription: Verity ams add app to AppRecentList failed when start a same process. + */ +HWTEST_F(AmsAppRecentListModuleTest, Create_Recent_List_001, TestSize.Level1) +{ + APP_LOGI("Create_Recent_List_001 start"); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_10); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + + // Load ability_2 again, fail to add. + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(INDEX_NUM_2); + abilityInfo->name = TEST_ABILITY_NAME + std::to_string(INDEX_NUM_2); + abilityInfo->applicationName = TEST_APP_NAME + std::to_string(INDEX_NUM_2); + abilityInfo->applicationInfo.bundleName = appInfo->name; + abilityInfo->process = appInfo->name; + + sptr token = new MockAbilityToken(); + MockAppSpawnClient *mockedSpawnClient = new MockAppSpawnClient(); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + APP_LOGI("Create_Recent_List_001 end"); +} + +/* + * Feature: Ams + * Function: AppRecentList + * SubFunction: create + * FunctionPoints: Add app to RecentAppList when start a new process success. + * EnvConditions: AppRecentList is empty. + * CaseDescription: Verity ams can add app to AppRecentList success when start a new process success. + */ +HWTEST_F(AmsAppRecentListModuleTest, Create_Recent_List_002, TestSize.Level1) +{ + APP_LOGI("Create_Recent_List_002 start"); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_10); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + + // Load ability_11 , add successful. + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(INDEX_NUM_10 + INDEX_NUM_1); + appInfo->bundleName = appInfo->name; + abilityInfo->name = TEST_ABILITY_NAME + std::to_string(INDEX_NUM_10 + INDEX_NUM_1); + abilityInfo->applicationName = TEST_APP_NAME + std::to_string(INDEX_NUM_10 + INDEX_NUM_1); + abilityInfo->applicationInfo.bundleName = appInfo->name; + abilityInfo->process = appInfo->name; + pid_t pid = static_cast(INDEX_NUM_10 + INDEX_NUM_1); + sptr token = new MockAbilityToken(); + MockAppSpawnClient *mockedSpawnClient = new MockAppSpawnClient(); + EXPECT_CALL(*mockedSpawnClient, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + EXPECT_EQ(INDEX_NUM_10 + INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + APP_LOGI("Create_Recent_List_002 end"); +} + +/* + * Feature: Ams + * Function: AppRecentList + * SubFunction: update + * FunctionPoints: Remove app from RecentAppList when app terminated. + * EnvConditions: AppRecentList has application. + * CaseDescription: Verity ams can remove app from AppRecentList when app terminated. + */ +HWTEST_F(AmsAppRecentListModuleTest, Update_Recent_List_001, TestSize.Level1) +{ + APP_LOGI("Update_Recent_List_001 start"); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_10); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + + auto appRecord = CreateAppRunningRecordByIndex(INDEX_NUM_10 - INDEX_NUM_1); + appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + auto p = appRecord->GetRecordId(); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + serviceInner_->ApplicationTerminated(p); + EXPECT_EQ(INDEX_NUM_10 - INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + APP_LOGI("Update_Recent_List_001 end"); +} + +/* + * Feature: Ams + * Function: AppRecentList + * SubFunction: update + * FunctionPoints: Remove app from AppRecentList when app died. + * EnvConditions: AppRecentList has application. + * CaseDescription: Verity ams can remove app from AppRecentList when app died. + */ +HWTEST_F(AmsAppRecentListModuleTest, Update_Recent_List_002, TestSize.Level1) +{ + APP_LOGI("Update_Recent_List_002 start"); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_10); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + + auto appRecord = CreateAppRunningRecordByIndex(INDEX_NUM_10 - INDEX_NUM_3); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + sptr object = client->AsObject(); + wptr app = object; + serviceInner_->OnRemoteDied(app); + EXPECT_EQ(INDEX_NUM_10 - INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + APP_LOGI("Update_Recent_List_002 end"); +} + +/* + * Feature: Ams + * Function: AppRecentList + * SubFunction: remove + * FunctionPoints: Remove app from AppRecentList. + * EnvConditions: AppRecentList has application. + * CaseDescription: Verity ams can remove app from AppRecentList when call remove app from RecentList. + */ +HWTEST_F(AmsAppRecentListModuleTest, Remove_Recent_List_001, TestSize.Level1) +{ + APP_LOGI("Remove_Recent_List_001 start"); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_10); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + + std::shared_ptr appInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(INDEX_NUM_10 - INDEX_NUM_1); + appInfo->bundleName = appInfo->name; + + auto appRecord = CreateAppRunningRecordByIndex(INDEX_NUM_10 - INDEX_NUM_1); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + + serviceInner_->RemoveAppFromRecentList(appInfo->name, appInfo->bundleName); // specify process condition + EXPECT_EQ(INDEX_NUM_10 - INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); + APP_LOGI("Remove_Recent_List_001 end"); +} + +/* + * Feature: Ams + * Function: AppRecentList + * SubFunction: remove + * FunctionPoints: Remove app from AppRecentList. + * EnvConditions: AppRecentList has application. + * CaseDescription: Verity ams can remove all app from AppRecentList. + */ +HWTEST_F(AmsAppRecentListModuleTest, Remove_Recent_List_002, TestSize.Level1) +{ + APP_LOGI("Remove_Recent_List_002 start"); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_10); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + for (int32_t i = 0; i < INDEX_NUM_10; i++) { + std::shared_ptr appInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(i); + appInfo->bundleName = appInfo->name; + + auto appRecord = CreateAppRunningRecordByIndex(i); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + serviceInner_->RemoveAppFromRecentList(appInfo->name, appInfo->bundleName); // specify process condition + } + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + APP_LOGI("Remove_Recent_List_002 end"); +} + +/* + * Feature: Ams + * Function: AppRecentList + * SubFunction: clear + * FunctionPoints: Clear AppRecentList. + * EnvConditions: AppRecentList has application. + * CaseDescription: Verity ams can clear AppRecentList after removing some apps. + */ +HWTEST_F(AmsAppRecentListModuleTest, Clear_Recent_List_001, TestSize.Level1) +{ + APP_LOGI("Clear_Recent_List_002 start"); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + CreateAppRecentList(INDEX_NUM_10); + EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); + + for (int32_t i = 0; i < INDEX_NUM_10; i++) { + std::shared_ptr appInfo = std::make_shared(); + appInfo->name = TEST_APP_NAME + std::to_string(i); + appInfo->bundleName = appInfo->name; + + auto appRecord = CreateAppRunningRecordByIndex(i); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + + if (appRecord) { + appRecord->SetApplicationClient(client); + } + + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + serviceInner_->RemoveAppFromRecentList(appInfo->name, appInfo->bundleName); // specify process condition + } + serviceInner_->ClearRecentAppList(); + EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); + APP_LOGI("Clear_Recent_List_002 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/test/moduletest/common/ams/app_running_record_test/BUILD.gn b/services/test/moduletest/common/ams/app_running_record_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..5a949c9b30c66e705614d8266a0525221b7995f8 --- /dev/null +++ b/services/test/moduletest/common/ams/app_running_record_test/BUILD.gn @@ -0,0 +1,37 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsAppRunningRecordModuleTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include/hilog/", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + sources = [ "ams_app_running_record_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsAppRunningRecordModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b683cbb65bb41ed26b88cfb79d96f7696d407527 --- /dev/null +++ b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp @@ -0,0 +1,517 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ +#define private public +#include "app_running_record.h" +#undef private +#include +#include +#include "iremote_object.h" +#include "app_record_id.h" +#include "app_scheduler_proxy.h" +#include "app_scheduler_host.h" +#define private public +#include "app_mgr_service_inner.h" +#undef private +#include "mock_application.h" +#include "ability_info.h" +#include "application_info.h" +#include "mock_bundle_manager.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" + +using namespace testing::ext; +using OHOS::iface_cast; +using OHOS::IRemoteObject; +using OHOS::sptr; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; + +namespace OHOS { +namespace AppExecFwk { +class AmsAppRunningRecordModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::string GetTestAppName(const unsigned long num) const + { + if (num < appName_.size()) { + return appName_[num]; + } + return ""; + } + + std::string GetTestAbilityName(const unsigned long num) const + { + if (num < abilityName_.size()) { + return abilityName_[num]; + } + return ""; + } + + void CheckLaunchApplication(const sptr &mockApplication, const unsigned long index, + std::shared_ptr record, const std::string &testPoint) const + { + EXPECT_TRUE(record != nullptr) << "record is nullptr!"; + sptr client = iface_cast(mockApplication); + record->SetApplicationClient(client); + + std::string applicationName(GetTestAppName(index)); + ApplicationInfo info; + info.name = applicationName; + std::string processInfoName(GetTestAppName(index)); + pid_t pidId = 123; + ProcessInfo processInfo(processInfoName, pidId); + + AppLaunchData launchData; + launchData.SetApplicationInfo(info); + launchData.SetProcessInfo(processInfo); + + Configuration config; + EXPECT_CALL(*mockApplication, ScheduleLaunchApplication(_, _)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::LaunchApplication)); + record->LaunchApplication(config); + mockApplication->Wait(); + + bool isEqual = mockApplication->CompareAppLaunchData(launchData); + EXPECT_EQ(isEqual, true) << testPoint << ",fail"; + } + + void CheckAppRunningRecording(const std::shared_ptr appInfo, + const std::shared_ptr abilityInfo, const std::shared_ptr record, const int index, + RecordQueryResult &result) const + { + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; + EXPECT_TRUE(appInfo != nullptr) << "appInfo is nullptr!"; + EXPECT_TRUE(abilityInfo != nullptr) << "abilityInfo is nullptr!"; + EXPECT_TRUE(record != nullptr) << "record is nullptr!"; + auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName(index)); + int32_t id = record->GetRecordId(); + auto name = record->GetName(); + sptr token = abilityRecord->GetToken(); + auto abilityName = abilityRecord->GetName(); + std::string processName = GetTestAppName(index); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + + auto appRecordFromServ = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, processName, appInfo->uid, bundleInfo); + EXPECT_TRUE(appRecordFromServ); + auto abilityRecordFromServ = appRecordFromServ->GetAbilityRunningRecord(GetTestAbilityName(index)); + int32_t idFromServ = appRecordFromServ->GetRecordId(); + sptr tokenFromServ = abilityRecordFromServ->GetToken(); + auto nameFromServ = appRecordFromServ->GetName(); + auto abilityNameFromServ = abilityRecordFromServ->GetName(); + EXPECT_TRUE(id == idFromServ) << "fail, RecordId is not equal!"; + EXPECT_TRUE(tokenFromServ.GetRefPtr() == token.GetRefPtr()) << "fail, token is not equal!"; + EXPECT_EQ(name, nameFromServ) << "fail, app record name is not equal!"; + EXPECT_EQ(abilityName, abilityNameFromServ) << "fail, app record name is not equal!"; + } + + std::unique_ptr service_ {nullptr}; + sptr mockBundleMgr_ {nullptr}; + + sptr GetMockToken() const + { + return mockToken_; + } + +private: + std::vector appName_ = { + "test_app_name1", + "test_app_name2", + "test_app_name3", + "test_app_name4", + "test_app_name5", + }; + std::vector abilityName_ = { + "test_ability_name1", + "test_ability_name2", + "test_ability_name3", + "test_ability_name4", + "test_ability_name5", + }; + sptr mockToken_{nullptr}; +}; + +void AmsAppRunningRecordModuleTest::SetUpTestCase() +{} + +void AmsAppRunningRecordModuleTest::TearDownTestCase() +{} + +void AmsAppRunningRecordModuleTest::SetUp() +{ + service_.reset(new (std::nothrow) AppMgrServiceInner()); + mockToken_ = new (std::nothrow) MockAbilityToken(); + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + service_->SetBundleManager(mockBundleMgr_); +} + +void AmsAppRunningRecordModuleTest::TearDown() +{} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: ApprunningRecord + * FunctionPoints: run application and use Iapplication LaunchApplication and + * ScheduleForegroundRunning interface to control application, + * check whether function is good or not + * EnvConditions: system running normally + * CaseDescription: 1. start application + * 2. use Iapplication LaunchApplication and ScheduleForegroundRunning interface + */ +HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStart_001, TestSize.Level1) +{ + // init AppRunningRecord + unsigned long index = 0L; + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(index); + abilityInfo->applicationInfo.uid = 0; + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(index); + appInfo->uid = 0; + std::string processName = GetTestAppName(index); + RecordQueryResult result; + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + record->SetUid(0); + EXPECT_TRUE(record != nullptr) << ",create apprunningrecord fail!"; + + // check apprunningrecord + int32_t id = record->GetRecordId(); + CheckAppRunningRecording(appInfo, abilityInfo, record, index, result); + + // LaunchApplication + sptr mockApplication(new MockApplication()); + std::string testPoint = "ApplicationStart_001"; + CheckLaunchApplication(mockApplication, index, record, testPoint); + + EXPECT_CALL(*mockApplication, ScheduleForegroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + // application enter in foreground and check the result + record->ScheduleForegroundRunning(); + mockApplication->Wait(); + + // update application state and check the state + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + auto newRecord = service_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, processName, appInfo->uid, bundleInfo); + EXPECT_TRUE(newRecord); + newRecord->SetUid(0); + auto stateFromRec = newRecord->GetState(); + EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_FOREGROUND); + + // clear apprunningrecord + record->SetState(ApplicationState::APP_STATE_BACKGROUND); + service_->ApplicationTerminated(id); + record = service_->GetAppRunningRecordByAppRecordId(id); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: ApprunningRecord + * FunctionPoints: run multi application at the same time, then use Iapplication + * LaunchApplication and ScheduleForegroundRunning interface to control + * application, check whether function is good or not + * EnvConditions: system running normally + * CaseDescription: 1. start 5 application at the same time + * 2. use Iapplication LaunchApplication and ScheduleForegroundRunning interface + */ +HWTEST_F(AmsAppRunningRecordModuleTest, MultiApplicationStart_002, TestSize.Level1) +{ + unsigned long count = 5; + for (unsigned long i = 0; i < count; i++) { + // init AppRunningRecord + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(i); + abilityInfo->applicationInfo.uid = 0; + std::string processName = GetTestAppName(i); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(i); + appInfo->uid = 0; + RecordQueryResult result; + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + record->SetUid(0); + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + + // check abilityrunningrecord & apprunningrecord + int32_t id = record->GetRecordId(); + CheckAppRunningRecording(appInfo, abilityInfo, record, i, result); + + // LaunchApplication + sptr mockApplication(new MockApplication()); + std::string testPoint = "multiApplicationStart_002"; + CheckLaunchApplication(mockApplication, i, record, testPoint); + + // clear apprunningrecord + record->SetState(ApplicationState::APP_STATE_BACKGROUND); + service_->ApplicationTerminated(id); + record = service_->GetAppRunningRecordByAppRecordId(id); + EXPECT_EQ(nullptr, record); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: ApprunningRecord + * FunctionPoints: run application, then use Iapplication LaunchApplication and ScheduleTrimMemory + * interface to control application,check whether function is good or not + * EnvConditions: system running normally + * CaseDescription: 1. start application + * 2. use Iapplication LaunchApplication and ScheduleTrimMemory interface + */ +HWTEST_F(AmsAppRunningRecordModuleTest, ScheduleTrimMemory_003, TestSize.Level1) +{ + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; + + // init AppRunningRecord + unsigned long index = 0; + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(index); + std::string processName = GetTestAppName(index); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(index); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + + // LaunchApplication + sptr mockApplication(new MockApplication()); + std::string testPoint = "ScheduleTrimMemory_003"; + CheckLaunchApplication(mockApplication, index, record, testPoint); + + EXPECT_CALL(*mockApplication, ScheduleShrinkMemory(_)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::ShrinkMemory)); + // set ScheduleTrimMemory API + record->ScheduleTrimMemory(); + mockApplication->Wait(); + int level = mockApplication->GetShrinkLevel(); + EXPECT_EQ(level, 0) << "fail, level is wrong!"; + + // clear apprunningrecord + record->SetState(ApplicationState::APP_STATE_BACKGROUND); + int32_t id = record->GetRecordId(); + service_->ApplicationTerminated(id); + record = service_->GetAppRunningRecordByAppRecordId(id); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: ApprunningRecord + * FunctionPoints: run application, then use Iapplication LaunchApplication and LowMemoryWarning + * interface to control application,check whether function is good or not + * EnvConditions: system running normally + * CaseDescription: 1. start application + * 2. use Iapplication LaunchApplication and LowMemoryWarning interface + */ +HWTEST_F(AmsAppRunningRecordModuleTest, LowMemoryWarning_004, TestSize.Level1) +{ + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; + + // init AppRunningRecord + unsigned long index = 0; + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(index); + std::string processName = GetTestAppName(index); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(index); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + + // LaunchApplication + sptr mockApplication(new MockApplication()); + std::string testPoint = "LowMemoryWarning_004"; + CheckLaunchApplication(mockApplication, index, record, testPoint); + + EXPECT_CALL(*mockApplication, ScheduleLowMemory()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + // set LowMemoryWarning + record->LowMemoryWarning(); + mockApplication->Wait(); + + // clear apprunningrecord + record->SetState(ApplicationState::APP_STATE_BACKGROUND); + int32_t id = record->GetRecordId(); + service_->ApplicationTerminated(id); + record = service_->GetAppRunningRecordByAppRecordId(id); + EXPECT_EQ(nullptr, record); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: ApprunningRecord + * FunctionPoints: run application and quit repeatly, then check whether function is good or not + * EnvConditions: system running normally + * CaseDescription: 1. start application + * 2. use Iapplication LaunchApplication and ScheduleForegroundRunning interface + * 3. use ScheduleBackgroundRunning interface + * 4. use ScheduleTerminate and OnApplicationTerminated to stop application + * 5. repeat 1~4 10000 times + */ +HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStartAndQuit_005, TestSize.Level2) +{ + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; + + unsigned long index = 0; + int startCount = 10000; + for (int i = 0; i < startCount; i++) { + // init AppRunningRecord + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(index); + std::string processName = GetTestAppName(index); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(index); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + + // LaunchApplication + sptr mockApplication(new MockApplication()); + std::string testPoint = "ApplicationStartAndQuit_005"; + CheckLaunchApplication(mockApplication, index, record, testPoint); + + EXPECT_CALL(*mockApplication, ScheduleForegroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + // set foreground and update foreground state + record->ScheduleForegroundRunning(); + mockApplication->Wait(); + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + auto stateFromRec = record->GetState(); + EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_FOREGROUND); + + EXPECT_CALL(*mockApplication, ScheduleBackgroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + // set background and update foreground state + record->ScheduleBackgroundRunning(); + mockApplication->Wait(); + record->SetState(ApplicationState::APP_STATE_BACKGROUND); + stateFromRec = record->GetState(); + EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*mockApplication, ScheduleTerminateApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + // set application terminate + record->ScheduleTerminate(); + mockApplication->Wait(); + + // clear apprunnningrecord + int32_t id = record->GetRecordId(); + service_->ApplicationTerminated(id); + record = service_->GetAppRunningRecordByAppRecordId(id); + EXPECT_EQ(nullptr, record); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: ApprunningRecord + * FunctionPoints: run application, make application foreground and background repeatly, + * then check whether function is good or not + * EnvConditions: system running normally + * CaseDescription: 1. start application + * 2. use Iapplication LaunchApplication and ScheduleForegroundRunning interface + * 3. use ScheduleBackgroundRunning and SetState to update state + * 4. repeat 1~4 10000 times + */ +HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStatusChange_006, TestSize.Level2) +{ + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; + + // init AppRunningRecord + unsigned long index = 0; + auto abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityName(index); + std::string processName = GetTestAppName(index); + auto appInfo = std::make_shared(); + appInfo->name = GetTestAppName(index); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + auto record = service_->CreateAppRunningRecord( + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + + // LaunchApplication + sptr mockApplication(new MockApplication()); + std::string testPoint = "ApplicationStatusChange_006"; + CheckLaunchApplication(mockApplication, index, record, testPoint); + int startCount = 10000; + for (int i = 0; i < startCount; i++) { + EXPECT_CALL(*mockApplication, ScheduleForegroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + // set foreground and update foreground state + record->ScheduleForegroundRunning(); + mockApplication->Wait(); + record->SetState(ApplicationState::APP_STATE_FOREGROUND); + auto stateFromRec = record->GetState(); + EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_FOREGROUND); + + EXPECT_CALL(*mockApplication, ScheduleBackgroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + // set background and update background state + record->ScheduleBackgroundRunning(); + mockApplication->Wait(); + record->SetState(ApplicationState::APP_STATE_BACKGROUND); + stateFromRec = record->GetState(); + EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_BACKGROUND); + } + int32_t id = record->GetRecordId(); + service_->ApplicationTerminated(id); + auto stateFromRec = record->GetState(); + EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_TERMINATED); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/app_service_flow_test/BUILD.gn b/services/test/moduletest/common/ams/app_service_flow_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..71c4adaef32c30f8ea48274bf5eaf7faef2fffdb --- /dev/null +++ b/services/test/moduletest/common/ams/app_service_flow_test/BUILD.gn @@ -0,0 +1,35 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsAppServiceFlowModuleTest") { + module_out_path = module_output_path + + include_dirs = + [ "//base/hiviewdfx/hilog/interfaces/native/innerkits/include/" ] + sources = [ "ams_app_service_flow_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsAppServiceFlowModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp b/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e05981c13326588bd5d3400cb1f4a1fcd8ce2ba9 --- /dev/null +++ b/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp @@ -0,0 +1,721 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "iremote_object.h" +#include "refbase.h" + +#include "app_launch_data.h" +#include "app_log_wrapper.h" +#define private public +#include "app_mgr_service_inner.h" +#undef private +#include "mock_ability_token.h" +#include "mock_bundle_manager.h" +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_app_spawn_client.h" + +using namespace testing::ext; +using testing::_; +using testing::Return; +using testing::SetArgReferee; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const uint32_t CYCLE_NUMBER = 10; +} // namespace +struct TestApplicationPreRunningRecord { + TestApplicationPreRunningRecord( + const std::shared_ptr &appRecord, const sptr &mockAppScheduler) + : appRecord_(appRecord), mockAppScheduler_(mockAppScheduler) + {} + sptr GetToken(const std::string &abilityName) const + { + auto abilityRecord = appRecord_->GetAbilityRunningRecord(abilityName); + return abilityRecord ? abilityRecord->GetToken() : nullptr; + } + + std::shared_ptr GetAbility(const std::string &abilityName) const + { + return appRecord_->GetAbilityRunningRecord(abilityName); + } + + virtual ~TestApplicationPreRunningRecord() + {} + + std::shared_ptr appRecord_; + sptr mockAppScheduler_; + static pid_t g_pid; +}; + +pid_t TestApplicationPreRunningRecord::g_pid = 0; +class AmsAppServiceFlowModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr TestCreateApplicationClient(const std::shared_ptr &appRecord) const; + TestApplicationPreRunningRecord TestCreateApplicationRecordAndSetState(const std::string &abilityName, + const std::string &appName, const AbilityState abilityState, const ApplicationState appState) const; + +protected: + std::shared_ptr serviceInner_ = nullptr; + std::shared_ptr handler_ = nullptr; + sptr mockBundleMgr_ {nullptr}; +}; + +void AmsAppServiceFlowModuleTest::SetUpTestCase() +{} + +void AmsAppServiceFlowModuleTest::TearDownTestCase() +{} + +void AmsAppServiceFlowModuleTest::SetUp() +{ + serviceInner_.reset(new (std::nothrow) AppMgrServiceInner()); + + auto runner = EventRunner::Create("AmsAppServiceFlowModuleTest"); + handler_ = std::make_shared(runner, serviceInner_); + serviceInner_->SetEventHandler(handler_); + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + serviceInner_->SetBundleManager(mockBundleMgr_); +} + +void AmsAppServiceFlowModuleTest::TearDown() +{} + +sptr AmsAppServiceFlowModuleTest::TestCreateApplicationClient( + const std::shared_ptr &appRecord) const +{ + if (appRecord->GetApplicationClient()) { + return nullptr; + } + sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + appRecord->LaunchPendingAbilities(); + return mockAppScheduler; +} + +// create one application that include one ability, and set state +TestApplicationPreRunningRecord AmsAppServiceFlowModuleTest::TestCreateApplicationRecordAndSetState( + const std::string &abilityName, const std::string &appName, const AbilityState abilityState, + const ApplicationState appState) const +{ + auto abilityInfo = std::make_shared(); + auto appInfo = std::make_shared(); + + appInfo->name = appName; + appInfo->bundleName = appName; // specify process condition + appInfo->uid = 0; + abilityInfo->name = abilityName; + abilityInfo->applicationInfo.uid = 0; + sptr token = new (std::nothrow) MockAbilityToken(); + + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); + + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appName, appInfo->uid, bundleInfo); + if (!appRecord) { + appRecord = serviceInner_->CreateAppRunningRecord( + token, nullptr, appInfo, abilityInfo, appName, bundleInfo, hapModuleInfo); + appRecord->GetPriorityObject()->SetPid(TestApplicationPreRunningRecord::g_pid++); + } else { + serviceInner_->StartAbility(token, nullptr, abilityInfo, appRecord, hapModuleInfo); + } + + EXPECT_TRUE(appRecord); + appRecord->SetUid(0); + appRecord->SetEventHandler(handler_); + + auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); + EXPECT_NE(abilityRecord, nullptr); + abilityRecord->SetState(abilityState); + appRecord->SetState(appState); + sptr mockAppScheduler = TestCreateApplicationClient(appRecord); + TestApplicationPreRunningRecord testAppPreRecord(appRecord, mockAppScheduler); + return testAppPreRecord; +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: BackKey + * CaseDescription: when two abilities on foreground, previous ability in another app, simulate press back key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_001, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_001 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_FOREGROUND, + ApplicationState::APP_STATE_FOREGROUND); + // The previous app and ability + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityB2", + testAppB.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + // simulate press back key + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility("abilityB1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppB.GetAbility("abilityB2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppB.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_001 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: BackKey + * CaseDescription: when two abilities on foreground, previous ability in another app, simulate press back key twice. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_002, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_002 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestApplicationPreRunningRecord testappC = TestCreateApplicationRecordAndSetState( + "abilityC1", "appC", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + // simulate press back key + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility("abilityB1")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppB.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppA.appRecord_->GetState()); + + EXPECT_CALL(*(testappC.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + // simulate press back key again + serviceInner_->UpdateAbilityState(testappC.GetToken("abilityC1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testappC.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testappC.GetAbility("abilityC1")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testappC.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_002 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: BackKey + * CaseDescription: app have three abilities , previous ability in same app, simulate press back key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_003, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_003 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_FOREGROUND); + TestCreateApplicationRecordAndSetState("abilityA3", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_FOREGROUND); + + // simulate press back key + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA3"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA3")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_003 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: BackKey + * CaseDescription:app with two abilities on foreground, previous ability in another app, simulate press back and exit. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_004, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_004 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_FOREGROUND, + ApplicationState::APP_STATE_FOREGROUND); + // The previous app and ability + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityB2", + testAppB.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(2); + + // simulate press back key + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB2"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_FOREGROUND); + + serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); + + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_BACKGROUND); + + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + + serviceInner_->TerminateAbility(testAppA.GetToken("abilityA1")); + serviceInner_->AbilityTerminated(testAppA.GetToken("abilityA1")); + serviceInner_->TerminateAbility(testAppA.GetToken("abilityA2")); + serviceInner_->AbilityTerminated(testAppA.GetToken("abilityA2")); + serviceInner_->ApplicationTerminated(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility("abilityB1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility("abilityB2")->GetState()); + + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppB.appRecord_->GetState()); + + EXPECT_EQ(testAppA.GetAbility("abilityA1"), nullptr); + EXPECT_EQ(testAppA.GetAbility("abilityA2"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_004 end"); +} + +/* + * Feature: AMS + * AR_AMS_ENV04_003 + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: BackKey + * CaseDescription: Three applications,only one on foreground, previous ability in another app, + simulate press back key twice. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_005, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_005 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestApplicationPreRunningRecord testappC = TestCreateApplicationRecordAndSetState( + "abilityC1", "appC", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + + // simulate press back key, AppA to backgroud and exit. + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(testAppA.GetToken("abilityA1")); + serviceInner_->AbilityTerminated(testAppA.GetToken("abilityA1")); + serviceInner_->ApplicationTerminated(testAppA.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility("abilityB1")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppB.appRecord_->GetState()); + EXPECT_EQ(testAppA.GetAbility("abilityA1"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppA.appRecord_->GetState()); + + EXPECT_CALL(*(testappC.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + // simulate press back key again + serviceInner_->UpdateAbilityState(testappC.GetToken("abilityC1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testappC.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(testAppB.GetToken("abilityB1")); + serviceInner_->AbilityTerminated(testAppB.GetToken("abilityB1")); + serviceInner_->ApplicationTerminated(testAppB.appRecord_->GetRecordId()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testappC.GetAbility("abilityC1")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testappC.appRecord_->GetState()); + EXPECT_EQ(testAppB.GetAbility("abilityB1"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppB.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_BackKey_005 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOff + * CaseDescription: when two applications with two abilities on foreground, simulate press screenoff key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_001, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_001 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + // The previous app and ability + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + + // simulate press screenOff key + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(testAppB.GetToken("abilityB1")); + serviceInner_->AbilityTerminated(testAppB.GetToken("abilityB1")); + serviceInner_->ApplicationTerminated(testAppB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(testAppA.GetToken("abilityA1")); + serviceInner_->AbilityTerminated(testAppA.GetToken("abilityA1")); + serviceInner_->ApplicationTerminated(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(testAppA.GetAbility("abilityA1"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppA.appRecord_->GetState()); + EXPECT_EQ(testAppB.GetAbility("abilityB1"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppB.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_001 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOff + * CaseDescription: when two applications with two abilities on foreground, simulate press screenoff key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_002, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_002 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_FOREGROUND, + ApplicationState::APP_STATE_FOREGROUND); + // The previous app and ability + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityB2", + testAppB.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + + // simulate press screenOff key + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB2"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppB.GetAbility("abilityB1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppB.GetAbility("abilityB2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppB.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_002 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOff + * CaseDescription: when two applications with two abilities on foreground, simulate press screenoff key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_003, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_003 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_FOREGROUND); + // The previous app and ability + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleCleanAbility(_)).Times(2); + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleCleanAbility(_)).Times(1); + + // simulate press screenOff key + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(testAppB.GetToken("abilityB1")); + serviceInner_->AbilityTerminated(testAppB.GetToken("abilityB1")); + serviceInner_->ApplicationTerminated(testAppB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(testAppA.GetToken("abilityA1")); + serviceInner_->AbilityTerminated(testAppA.GetToken("abilityA1")); + serviceInner_->TerminateAbility(testAppA.GetToken("abilityA2")); + serviceInner_->AbilityTerminated(testAppA.GetToken("abilityA2")); + serviceInner_->ApplicationTerminated(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(testAppA.GetAbility("abilityA1"), nullptr); + EXPECT_EQ(testAppA.GetAbility("abilityA2"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppA.appRecord_->GetState()); + EXPECT_EQ(testAppB.GetAbility("abilityB1"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppB.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_003 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOff + * CaseDescription: when two applications with two abilities on foreground, simulate press screenoff key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_004, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_004 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_FOREGROUND); + // The previous app and ability + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityB2", + testAppB.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleCleanAbility(_)).Times(2); + + // simulate press screenOff key + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); + serviceInner_->TerminateAbility(testAppB.GetToken("abilityB1")); + serviceInner_->AbilityTerminated(testAppB.GetToken("abilityB1")); + serviceInner_->TerminateAbility(testAppB.GetToken("abilityB2")); + serviceInner_->AbilityTerminated(testAppB.GetToken("abilityB2")); + serviceInner_->ApplicationTerminated(testAppB.appRecord_->GetRecordId()); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(testAppB.GetAbility("abilityB1"), nullptr); + EXPECT_EQ(testAppB.GetAbility("abilityB2"), nullptr); + EXPECT_EQ(ApplicationState::APP_STATE_TERMINATED, testAppB.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOff_004 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOn + * CaseDescription: when an application with three abilities on foreground, simulate press screenon key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOn_001, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOn_001 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityA3", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + + // simulate press ScreenOn key + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppA.GetAbility("abilityA3")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOn_001 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOn + * CaseDescription: when an application with three abilities on foreground, simulate press screenon key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOn_002, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOn_002 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityA3", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + + // simulate press ScreenOn key + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA3"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA3")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOn_002 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOn + * CaseDescription: when an application with two abilities on foreground, simulate press screenon key. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOn_003, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOn_003 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + TestApplicationPreRunningRecord testAppB = TestCreateApplicationRecordAndSetState( + "abilityB1", "appB", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityB2", + testAppB.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); + + // simulate press ScreenOn key + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppB.GetToken("abilityB2"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); + serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppA.appRecord_->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility("abilityB1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility("abilityB2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppB.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOn_003 end"); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ServiceFlow + * FunctionPoints: ScreenOn + * CaseDescription: an application with two abilities on foreground, simulate press screenon and screenoff 1000 times. + */ +HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOnAndOff_001, TestSize.Level1) +{ + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOnAndOff_001 start"); + TestApplicationPreRunningRecord testAppA = TestCreateApplicationRecordAndSetState( + "abilityA1", "appA", AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); + TestCreateApplicationRecordAndSetState("abilityA2", + testAppA.appRecord_->GetName(), + AbilityState::ABILITY_STATE_BACKGROUND, + ApplicationState::APP_STATE_BACKGROUND); + + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleForegroundApplication()).Times(CYCLE_NUMBER + 1); + EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(CYCLE_NUMBER); + + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + // simulate press ScreenOn key + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); + + // simulate press ScreenOff key + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_BACKGROUND); + serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); + } + + // simulate press ScreenOn key + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA1"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->UpdateAbilityState(testAppA.GetToken("abilityA2"), AbilityState::ABILITY_STATE_FOREGROUND); + serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); + + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA1")->GetState()); + EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility("abilityA2")->GetState()); + EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppA.appRecord_->GetState()); + APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOnAndOff_001 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/test/moduletest/common/ams/ipc_ams_mgr_test/BUILD.gn b/services/test/moduletest/common/ams/ipc_ams_mgr_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..81dff48201ce3477e93f998779225d8c7bca7f2a --- /dev/null +++ b/services/test/moduletest/common/ams/ipc_ams_mgr_test/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsIpcAmsmgrModuleTest") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/appmgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + sources = [ "ams_ipc_ams_mgr_module_test.cpp" ] + + deps = [ + "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${services_path}/appmgr/test:appmgr_test_source", + "${services_path}/test/moduletest/common/ams:appmgr_mst_source", + ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsIpcAmsmgrModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b85df8ce86fde64468c9c2aacdd56985641c687f --- /dev/null +++ b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp @@ -0,0 +1,421 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 + +#define private public +#include "app_mgr_client.h" +#undef private +#include "ams_mgr_scheduler.h" +#include "app_mgr_proxy.h" +#include "app_mgr_service_event_handler.h" +#include "app_record_id.h" +#include "app_scheduler_proxy.h" +#include "mock_ability_token.h" +#include "mock_application.h" +#include "mock_iapp_state_callback.h" +#include "mock_app_mgr_service.h" +#include "mock_app_mgr_service_inner.h" +#include "mock_app_service_mgr.h" +#include "iremote_object.h" + +using namespace testing::ext; +using OHOS::iface_cast; +using OHOS::sptr; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t COUNT = 1000; +} // namespace +class AmsIpcAmsmgrModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr GetApplicationInfo(const std::string &appName) const; + std::shared_ptr GetAbilityInfo( + const std::string &abilityIndex, const std::string &name, const std::string &applicationName) const; + + sptr GetAbilityToken() + { + mockToken_ = new (std::nothrow) MockAbilityToken(); + return mockToken_; + } + + std::shared_ptr GetMockAppMgrServiceInner(); + std::shared_ptr GetAmsEventHandler(); + +protected: + sptr mockToken_ = nullptr; + sptr token_{nullptr}; + std::unique_ptr client_{nullptr}; + + std::shared_ptr mockAppMgrServiceInner_{nullptr}; + std::shared_ptr amsEventHandler_{nullptr}; +}; + +class MockMockAppMgrService : public MockAppMgrService { +public: + MOCK_METHOD0(GetAmsMgr, sptr()); + MOCK_METHOD1(ClearUpApplicationData, int32_t(const std::string &)); + MOCK_METHOD1(IsBackgroundRunningRestricted, int(const std::string &appName)); + MOCK_METHOD1(GetAllRunningProcesses, int(std::vector &)); +}; + +void AmsIpcAmsmgrModuleTest::SetUpTestCase() +{} + +void AmsIpcAmsmgrModuleTest::TearDownTestCase() +{} + +void AmsIpcAmsmgrModuleTest::SetUp() +{ + token_ = new (std::nothrow) MockAbilityToken(); +} + +void AmsIpcAmsmgrModuleTest::TearDown() +{ + amsEventHandler_.reset(); + mockAppMgrServiceInner_.reset(); +} + +std::shared_ptr AmsIpcAmsmgrModuleTest::GetApplicationInfo(const std::string &appName) const +{ + auto appInfo = std::make_shared(); + appInfo->name = appName; + return appInfo; +} + +std::shared_ptr AmsIpcAmsmgrModuleTest::GetAbilityInfo( + const std::string &abilityIndex, const std::string &name, const std::string &applicationName) const +{ + auto abilityInfo = std::make_shared(); + abilityInfo->name = name + abilityIndex; + abilityInfo->applicationName = applicationName; + return abilityInfo; +} + +std::shared_ptr AmsIpcAmsmgrModuleTest::GetMockAppMgrServiceInner() +{ + if (!mockAppMgrServiceInner_) { + mockAppMgrServiceInner_ = std::make_shared(); + } + return mockAppMgrServiceInner_; +} + +std::shared_ptr AmsIpcAmsmgrModuleTest::GetAmsEventHandler() +{ + if (!amsEventHandler_) { + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + amsEventHandler_ = + std::make_shared(EventRunner::Create("AmsMgrSchedulerTest"), mockAppMgrServiceInner); + } + return amsEventHandler_; +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AmsmgrIPCInterface + * FunctionPoints: test loadAbility API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute loadAbility API 1000 times + */ +HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_001, TestSize.Level3) +{ + auto abilityInfo = GetAbilityInfo("0", "MainAbility", "com.ohos.test.helloworld"); + auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(amsMgrScheduler.get()); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); + mockMockAppMgr->Wait(); + sptr token = new MockAbilityToken(); + + for (int i = 0; i < COUNT; i++) { + EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler_->LoadAbility(token_, nullptr, abilityInfo, appInfo); + mockAppMgrServiceInner->Wait(); + } + + mockAppMgrServiceInner.reset(); + amsMgrScheduler.release(); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AmsmgrIPCInterface + * FunctionPoints: test terminateAbility API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute terminateAbility API 1000 times + */ +HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_002, TestSize.Level3) +{ + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(amsMgrScheduler.get()); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); + mockMockAppMgr->Wait(); + sptr token = new MockAbilityToken(); + + for (int i = 0; i < COUNT; i++) { + EXPECT_CALL(*mockAppMgrServiceInner, TerminateAbility(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler_->TerminateAbility(token_); + mockAppMgrServiceInner->Wait(); + } + + mockAppMgrServiceInner.reset(); + amsMgrScheduler.release(); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AmsmgrIPCInterface + * FunctionPoints: test updateAbilityState API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute updateAbilityState API 1000 times + */ +HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_003, TestSize.Level3) +{ + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(amsMgrScheduler.get()); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); + mockMockAppMgr->Wait(); + + sptr token = new MockAbilityToken(); + AbilityState abilityState = AbilityState::ABILITY_STATE_BEGIN; + + for (int i = 0; i < COUNT; i++) { + EXPECT_CALL(*mockAppMgrServiceInner, UpdateAbilityState(_, _)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler_->UpdateAbilityState(token, abilityState); + mockAppMgrServiceInner->Wait(); + } + + mockAppMgrServiceInner.reset(); + amsMgrScheduler.release(); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AmsmgrIPCInterface + * FunctionPoints: test registerappstatecallback API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute registerappstatecallback API 1000 times + */ +HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_004, TestSize.Level3) +{ + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + sptr callback = new MockAppStateCallback(); + + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(amsMgrScheduler.get()); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); + mockMockAppMgr->Wait(); + + for (int i = 0; i < COUNT; i++) { + EXPECT_CALL(*mockAppMgrServiceInner, RegisterAppStateCallback(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler_->RegisterAppStateCallback(callback); + mockAppMgrServiceInner->Wait(); + } + + mockAppMgrServiceInner.reset(); + amsMgrScheduler.release(); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AmsmgrIPCInterface + * FunctionPoints: test AbilityBehaviorAnalysis API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute AbilityBehaviorAnalysis API 1000 times + */ +HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_005, TestSize.Level3) +{ + const int32_t visibility = 1; + const int32_t perceptibility = 1; + const int32_t connectionState = 1; + + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(amsMgrScheduler.get()); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); + mockMockAppMgr->Wait(); + sptr token = new MockAbilityToken(); + + for (int i = 0; i < COUNT; i++) { + EXPECT_CALL(*mockAppMgrServiceInner, AbilityBehaviorAnalysis(_, _, _, _, _)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler_->AbilityBehaviorAnalysis(token, nullptr, visibility, perceptibility, connectionState); + mockAppMgrServiceInner->Wait(); + } + + mockAppMgrServiceInner.reset(); + amsMgrScheduler.release(); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AmsmgrIPCInterface + * FunctionPoints: test KillApplication API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute KillApplication API 1000 times + */ +HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_006, TestSize.Level3) +{ + const std::string bundleName = "p1"; + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(amsMgrScheduler.get()); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); + mockMockAppMgr->Wait(); + + for (int i = 0; i < COUNT; i++) { + EXPECT_CALL(*mockAppMgrServiceInner, KillApplication(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post4Int)); + amsMgrScheduler_->KillApplication(bundleName); + mockAppMgrServiceInner->Wait(); + } + + mockAppMgrServiceInner.reset(); + amsMgrScheduler.release(); +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AmsmgrIPCInterface + * FunctionPoints: test KillProcessByAbilityToken API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute KillProcessByAbilityToken API 1000 times + */ +HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_007, TestSize.Level3) +{ + auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); + auto amsEventHandler = GetAmsEventHandler(); + std::unique_ptr amsMgrScheduler = + std::make_unique(mockAppMgrServiceInner, amsEventHandler); + + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(amsMgrScheduler.get()); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); + mockMockAppMgr->Wait(); + sptr token = new MockAbilityToken(); + + for (int i = 0; i < COUNT; i++) { + EXPECT_CALL(*mockAppMgrServiceInner, KillProcessByAbilityToken(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); + amsMgrScheduler_->KillProcessByAbilityToken(token); + mockAppMgrServiceInner->Wait(); + } + + mockAppMgrServiceInner.reset(); + amsMgrScheduler.release(); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/ipc_app_mgr_test/BUILD.gn b/services/test/moduletest/common/ams/ipc_app_mgr_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..7e8d703699985ccf009e2ce8fb06392bbaf55021 --- /dev/null +++ b/services/test/moduletest/common/ams/ipc_app_mgr_test/BUILD.gn @@ -0,0 +1,35 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsIpcAppmgrModuleTest") { + module_out_path = module_output_path + + include_dirs = [] + + sources = [ "ams_ipc_app_mgr_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsIpcAppmgrModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/ipc_app_mgr_test/ams_ipc_app_mgr_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_mgr_test/ams_ipc_app_mgr_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..caf863ae46c4cccec695e057ebdae030fd3392e9 --- /dev/null +++ b/services/test/moduletest/common/ams/ipc_app_mgr_test/ams_ipc_app_mgr_module_test.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_mgr_proxy.h" +#include "app_scheduler_proxy.h" +#include "app_record_id.h" + +#include "mock_app_mgr_service.h" +#include "mock_application.h" +#include "mock_ability_token.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using OHOS::iface_cast; +using OHOS::sptr; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; +namespace { +const int32_t COUNT = 10000; +} // namespace +class AmsIpcAppmgrModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsIpcAppmgrModuleTest::SetUpTestCase() +{} + +void AmsIpcAppmgrModuleTest::TearDownTestCase() +{} + +void AmsIpcAppmgrModuleTest::SetUp() +{} + +void AmsIpcAppmgrModuleTest::TearDown() +{} + +class MockMockAppMgrService : public MockAppMgrService { +public: + MOCK_METHOD0(GetAmsMgr, sptr()); + MOCK_METHOD1(ClearUpApplicationData, int32_t(const std::string &)); + MOCK_METHOD1(IsBackgroundRunningRestricted, int(const std::string &bundleName)); + MOCK_METHOD1(GetAllRunningProcesses, int(std::vector &)); +}; + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test attachApplication API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute attachApplication API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_001, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + sptr app(new MockApplication()); + + EXPECT_CALL(*mockAppMgr, AttachApplication(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + appMgrClient->AttachApplication(app); + mockAppMgr->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test applicationForegrounded API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute applicationForegrounded API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_002, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + auto recordId = AppRecordId::Create(); + + EXPECT_CALL(*mockAppMgr, ApplicationForegrounded(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + appMgrClient->ApplicationForegrounded(recordId); + mockAppMgr->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test applicationBackgrounded API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute applicationBackgrounded API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_003, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + auto recordId = AppRecordId::Create(); + + EXPECT_CALL(*mockAppMgr, ApplicationBackgrounded(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + appMgrClient->ApplicationBackgrounded(recordId); + mockAppMgr->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test ApplicationTerminated API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ApplicationTerminated API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_004, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + auto recordId = AppRecordId::Create(); + + EXPECT_CALL(*mockAppMgr, ApplicationTerminated(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + appMgrClient->ApplicationTerminated(recordId); + mockAppMgr->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test AbilityCleaned API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute AbilityClenaed API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_005, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockAppMgr(new MockAppMgrService()); + sptr appMgrClient = iface_cast(mockAppMgr); + sptr token = new MockAbilityToken; + + EXPECT_CALL(*mockAppMgr, AbilityCleaned(_)) + .WillOnce(InvokeWithoutArgs(mockAppMgr.GetRefPtr(), &MockAppMgrService::Post)); + appMgrClient->AbilityCleaned(token); + mockAppMgr->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test GetAmsMgr API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute KillApplication API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_006, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + + auto mockHandler = [&]() -> sptr { + mockMockAppMgr->Post(); + return sptr(nullptr); + }; + + EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); + + appMgrClient->GetAmsMgr(); + + mockMockAppMgr->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test ClearUpApplicationData API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ClearUpApplicationData API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_007, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + std::string testBundleName("testApp"); + bool testResult = false; + + auto mockHandler = [&](const std::string &name) { + testResult = (name == testBundleName); + mockMockAppMgr->Post(); + return 0; + }; + + EXPECT_CALL(*mockMockAppMgr, ClearUpApplicationData(_)).WillOnce(Invoke(mockHandler)); + + appMgrClient->ClearUpApplicationData(testBundleName); + mockMockAppMgr->Wait(); + + EXPECT_TRUE(testResult); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test IsBackgroundRunningRestricted API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute IsBackgroundRunningRestricted API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_008, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + std::string testBundleName("testApp"); + bool testResult = false; + + auto mockHandler = [&](const std::string &name) { + testResult = (name == testBundleName); + mockMockAppMgr->Post(); + return 0; + }; + + EXPECT_CALL(*mockMockAppMgr, IsBackgroundRunningRestricted(_)).WillOnce(Invoke(mockHandler)); + + appMgrClient->IsBackgroundRunningRestricted(testBundleName); + mockMockAppMgr->Wait(); + + EXPECT_TRUE(testResult); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: AppmgrIPCInterface + * FunctionPoints: test GetAllRunningProcesses API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute GetAllRunningProcesses API 10000 times + */ +HWTEST_F(AmsIpcAppmgrModuleTest, ExcuteAppmgrIPCInterface_09, TestSize.Level3) +{ + const std::string testBundleName_1("testApp1"); + pid_t testApp1Pid = 1001; + const std::string testBundleName_2("testApp2"); + pid_t testApp2Pid = 1002; + + for (int i = 0; i < COUNT; i++) { + sptr mockMockAppMgr(new MockMockAppMgrService()); + sptr appMgrClient = iface_cast(mockMockAppMgr); + std::vector allRunningProcessInfo; + + auto mockHandler = [&](std::vector &result) { + result.clear(); + + auto &r1 = result.emplace_back(); + r1.processName_ = testBundleName_1; + r1.pid_ = testApp1Pid; + + auto &r2 = result.emplace_back(); + r2.processName_ = testBundleName_2; + r2.pid_ = testApp2Pid; + + mockMockAppMgr->Post(); + + return 0; + }; + + EXPECT_CALL(*mockMockAppMgr, GetAllRunningProcesses(_)).WillOnce(Invoke(mockHandler)); + + appMgrClient->GetAllRunningProcesses(allRunningProcessInfo); + mockMockAppMgr->Wait(); + + EXPECT_TRUE(allRunningProcessInfo.size() == 2); + EXPECT_EQ(allRunningProcessInfo[0].processName_, testBundleName_1); + EXPECT_EQ(allRunningProcessInfo[0].pid_, testApp1Pid); + EXPECT_EQ(allRunningProcessInfo[1].processName_, testBundleName_2); + EXPECT_EQ(allRunningProcessInfo[1].pid_, testApp2Pid); + } +} diff --git a/services/test/moduletest/common/ams/ipc_app_scheduler_test/BUILD.gn b/services/test/moduletest/common/ams/ipc_app_scheduler_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..2f51d57cbe151aeb965d46ae73d51d3ab83bd0a9 --- /dev/null +++ b/services/test/moduletest/common/ams/ipc_app_scheduler_test/BUILD.gn @@ -0,0 +1,34 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsIpcAppSchedulerModuleTest") { + module_out_path = module_output_path + + include_dirs = [] + sources = [ "ams_ipc_app_scheduler_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsIpcAppSchedulerModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb42c380bcb1371c06f92c4f0ada0db0f1c4e2e2 --- /dev/null +++ b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_scheduler_host.h" +#include "app_scheduler_proxy.h" +#include "semaphore_ex.h" + +#include "mock_ability_token.h" +#include "mock_app_scheduler.h" +#include "mock_application.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using OHOS::iface_cast; +using OHOS::sptr; +using testing::_; +using testing::Invoke; +using testing::InvokeWithoutArgs; + +namespace { +const int32_t COUNT = 10000; +} // namespace +class AmsIpcAppSchedulerModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + sptr GetMockToken() const + { + return mock_token_; + } + +private: + sptr mock_token_; +}; + +void AmsIpcAppSchedulerModuleTest::SetUpTestCase() +{} + +void AmsIpcAppSchedulerModuleTest::TearDownTestCase() +{} + +void AmsIpcAppSchedulerModuleTest::SetUp() +{} + +void AmsIpcAppSchedulerModuleTest::TearDown() +{} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleForegroundApplication API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleForegroundApplication API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_001, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleForegroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleForegroundApplication(); + mockApplication->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleBackgroundApplication API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleBackgroundApplication API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_002, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleBackgroundApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleBackgroundApplication(); + mockApplication->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleTerminateApplication API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleTerminateApplication API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_003, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleTerminateApplication()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleTerminateApplication(); + mockApplication->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleTrimMemory API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleTrimMemory API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_004, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleShrinkMemory(_)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::ShrinkMemory)); + int level = 1; + client->ScheduleShrinkMemory(level); + mockApplication->Wait(); + int getLevel = mockApplication->GetShrinkLevel(); + EXPECT_EQ(getLevel, level) << "excute fail, index is " << i; + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test scheduleLowMemory API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute LowMemoryWarning API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_005, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + EXPECT_CALL(*mockApplication, ScheduleLowMemory()) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleLowMemory(); + mockApplication->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test scheduleProfileChanged API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute scheduleProfileChanged API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_006, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + std::string profileName("mockProfile"); + Profile profile(profileName); + + EXPECT_CALL(*mockApplication, ScheduleProfileChanged(_)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::ProfileChanged)); + client->ScheduleProfileChanged(profile); + mockApplication->Wait(); + bool result = mockApplication->CompareProfile(profile); + EXPECT_EQ(result, true) << "excute fail, index is " << i; + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleLaunchAbility API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleLaunchAbility API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_007, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + std::string abilityName("mockAbilityInfo"); + AbilityInfo info; + info.name = abilityName; + + EXPECT_CALL(*mockApplication, ScheduleLaunchAbility(_, _)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::LaunchAbility)); + client->ScheduleLaunchAbility(info, GetMockToken()); + mockApplication->Wait(); + bool result = mockApplication->CompareAbilityInfo(info); + EXPECT_EQ(result, true) << "excute fail, index is " << i; + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleLaunchApplication API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleLaunchApplication API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_008, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + std::string applicationName("mockApplicationInfo"); + ApplicationInfo applicationInfo; + applicationInfo.name = applicationName; + std::string profileName("mockProfile"); + Profile profile(profileName); + std::string processName("mockProcessInfo"); + ProcessInfo processInfo(processName, 123); + + AppLaunchData launchData; + launchData.SetApplicationInfo(applicationInfo); + launchData.SetProfile(profile); + launchData.SetProcessInfo(processInfo); + + Configuration config; + EXPECT_CALL(*mockApplication, ScheduleLaunchApplication(_, _)) + .Times(1) + .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::LaunchApplication)); + client->ScheduleLaunchApplication(launchData, config); + mockApplication->Wait(); + + bool isEqual = mockApplication->CompareAppLaunchData(launchData); + EXPECT_EQ(true, isEqual) << "excute fail, index is " << i; + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleCleanAbility API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleCleanAbility API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_009, TestSize.Level3) +{ + for (int i = 0; i < COUNT; i++) { + sptr mockApplication(new MockApplication()); + sptr client = iface_cast(mockApplication); + + std::string abilityName("mockAbilityInfo"); + + EXPECT_CALL(*mockApplication, ScheduleCleanAbility(_)) + .Times(1) + .WillOnce(InvokeWithoutArgs(mockApplication.GetRefPtr(), &MockApplication::Post)); + client->ScheduleCleanAbility(GetMockToken()); + mockApplication->Wait(); + } +} + +/* + * Feature: ApplicationFramework + * Function: AppManagerService + * SubFunction: IApplicationScheduler + * FunctionPoints: test ScheduleConfigurationUpdated API,then check the function whether is good or not + * EnvConditions: system running normally + * CaseDescription: excute ScheduleConfigurationUpdated API 10000 times + */ +HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_010, TestSize.Level3) +{ + OHOS::Semaphore sem(0); + Configuration testConfig; + std::string val = "ZH-HANS"; + testConfig.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, val); + for (int i = 0; i < COUNT; i++) { + sptr mockAppScheduler(new MockAppScheduler()); + sptr client = iface_cast(mockAppScheduler); + bool testResult = false; + + auto mockHandler = [&](const Configuration &config) { + testResult = (val == config.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE)); + sem.Post(); + }; + + EXPECT_CALL(*mockAppScheduler, ScheduleConfigurationUpdated(_)).Times(1).WillOnce(Invoke(mockHandler)); + + client->ScheduleConfigurationUpdated(testConfig); + + sem.Wait(); + + EXPECT_TRUE(testResult); + } +} diff --git a/services/test/moduletest/common/ams/process_optimizer_uba_test/BUILD.gn b/services/test/moduletest/common/ams/process_optimizer_uba_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8277f2720da8a3cb9afb387c5fec9b7347589b5c --- /dev/null +++ b/services/test/moduletest/common/ams/process_optimizer_uba_test/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsProcessOptimizerModuleTest") { + module_out_path = module_output_path + + include_dirs = + [ "//base/hiviewdfx/hilog/interfaces/native/innerkits/include" ] + + defines = [ + "APP_LOG_TAG = \"AppMgrService\"", + "LOG_DOMAIN = 0xD001110", + ] + + sources = [ "ams_process_optimizer_uba_module_test.cpp" ] + + deps = [ "${services_path}/test/moduletest/common/ams:appmgr_mst_source" ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsProcessOptimizerModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/process_optimizer_uba_test/ams_process_optimizer_uba_module_test.cpp b/services/test/moduletest/common/ams/process_optimizer_uba_test/ams_process_optimizer_uba_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ebf5e92855f2e2f3e04d5b8061fa904abbb3c6e --- /dev/null +++ b/services/test/moduletest/common/ams/process_optimizer_uba_test/ams_process_optimizer_uba_module_test.cpp @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ +#define private public +#define protected public +#include "app_mgr_service.h" +#undef private +#undef protected + +#include +#include "app_log_wrapper.h" + +using namespace testing::ext; +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string APP_RECORD_NAME = "App_Name_Z"; +// foreground process oom_adj +constexpr int APP_OOM_ADJ_FOREGROUND = 0; +// background process oom_adj +constexpr int APP_OOM_ADJ_BACKGROUND_MIN = 400; +// suspend process oom_adj +constexpr int APP_OOM_ADJ_SUSPEND_MIN = 600; + +static constexpr int APP_SUSPEND_TIMEOUT_DEFAULT = 100; +static constexpr int APP_USLEEP = 200 * 1000; +} // namespace +class AmsProcessOptimizerUbaModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + void SuspendApplication(const std::shared_ptr &appRecord); + void ResumeApplication(const std::shared_ptr &appRecord); + std::shared_ptr processOptimizerUBA = + std::make_unique(nullptr, nullptr, APP_SUSPEND_TIMEOUT_DEFAULT); +}; + +void AmsProcessOptimizerUbaModuleTest::SuspendApplication(const std::shared_ptr &appRecord) +{ + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + APP_LOGD("%{public}s : app name is %{public}s , Uid is %{public}d", + __func__, + appRecord->GetName().c_str(), + appRecord->GetUid()); + // Temporary unsubscribe via UID + appRecord->SetState(ApplicationState::APP_STATE_SUSPENDED); + processOptimizerUBA->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND); +} + +void AmsProcessOptimizerUbaModuleTest::ResumeApplication(const std::shared_ptr &appRecord) +{ + if (!appRecord) { + APP_LOGE("app record is null"); + return; + } + APP_LOGD("%{public}s : app name is %{public}s , Uid is %{public}d", + __func__, + appRecord->GetName().c_str(), + appRecord->GetUid()); +} + +void AmsProcessOptimizerUbaModuleTest::SetUpTestCase() +{} + +void AmsProcessOptimizerUbaModuleTest::TearDownTestCase() +{} + +void AmsProcessOptimizerUbaModuleTest::SetUp() +{} + +void AmsProcessOptimizerUbaModuleTest::TearDown() +{} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppAdded + * FunctionPoints: add application + * CaseDescription: Call the OnAppAdded function to add multiple application + */ +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppAdded_001, TestSize.Level1) +{ + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppAdded_001 start"); + + bool isSuccess = processOptimizerUBA->Init(); + EXPECT_TRUE(true == isSuccess); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto app1 = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app1->GetPriorityObject()->SetPid(1000); + auto priorityObject1 = app1->GetPriorityObject(); + processOptimizerUBA->OnAppAdded(app1); + + auto oomAdj1 = priorityObject1->GetCurAdj(); + EXPECT_TRUE(oomAdj1 == APP_OOM_ADJ_FOREGROUND); + + auto app2 = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app2->GetPriorityObject()->SetPid(1100); + auto priorityObject2 = app2->GetPriorityObject(); + processOptimizerUBA->OnAppAdded(app2); + + auto oomAdj2 = priorityObject2->GetCurAdj(); + EXPECT_TRUE(oomAdj2 == APP_OOM_ADJ_FOREGROUND); + + oomAdj1 = priorityObject1->GetCurAdj(); + + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppAdded_001 end"); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppStateChanged + * FunctionPoints: change application status + * CaseDescription: Set a different state, check the value of adj + */ +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppStateChanged_001, TestSize.Level1) +{ + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_001 start"); + + bool isSuccess = processOptimizerUBA->Init(); + EXPECT_TRUE(true == isSuccess); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + app->SetState(ApplicationState::APP_STATE_FOREGROUND); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetPid(1200); + + processOptimizerUBA->OnAppStateChanged(app, ApplicationState::APP_STATE_BACKGROUND); + auto oomAdj = priorityObject->GetCurAdj(); + EXPECT_TRUE(oomAdj == APP_OOM_ADJ_FOREGROUND); + + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_001 end"); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppStateChanged + * FunctionPoints: change application status + * CaseDescription: Set a different state, check the value of adj + */ +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppStateChanged_002, TestSize.Level1) +{ + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_002 start"); + + bool isSuccess = processOptimizerUBA->Init(); + EXPECT_TRUE(true == isSuccess); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + processOptimizerUBA->OnAppAdded(app); + app->SetState(ApplicationState::APP_STATE_BACKGROUND); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetPid(1300); + + processOptimizerUBA->OnAppStateChanged(app, ApplicationState::APP_STATE_FOREGROUND); + auto oomAdj = priorityObject->GetCurAdj(); + EXPECT_TRUE(oomAdj == APP_OOM_ADJ_BACKGROUND_MIN); + + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_002 end"); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppStateChanged + * FunctionPoints: change application status + * CaseDescription: 1. Call the OnAppStateChanged function, make the conditions meet, call the StartAppSuspendTimer + function, make the app state suspended + 2. Call the OnAppStateChanged function to remove the suspended state + */ +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppStateChanged_003, TestSize.Level1) +{ + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_003 start"); + + processOptimizerUBA->AppSuspended = + std::bind(&AmsProcessOptimizerUbaModuleTest::SuspendApplication, this, std::placeholders::_1); + processOptimizerUBA->AppResumed = + std::bind(&AmsProcessOptimizerUbaModuleTest::ResumeApplication, this, std::placeholders::_1); + bool isSuccess = processOptimizerUBA->Init(); + EXPECT_TRUE(true == isSuccess); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + processOptimizerUBA->OnAppAdded(app); + app->SetState(ApplicationState::APP_STATE_BACKGROUND); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetPid(1); + priorityObject->SetVisibleStatus(false); + priorityObject->SetPerceptibleStatus(false); + + processOptimizerUBA->OnAppStateChanged(app, ApplicationState::APP_STATE_FOREGROUND); + usleep(APP_USLEEP); + auto oomAdj = priorityObject->GetCurAdj(); + EXPECT_TRUE(oomAdj == APP_OOM_ADJ_SUSPEND_MIN); + + GTEST_LOG_(INFO) << "AmsProcessOptimizerUbaModuleTest OnAppStateChanged_003 oomAdj: " << oomAdj; + + auto appState = app->GetState(); + if (appState == ApplicationState::APP_STATE_SUSPENDED) { + app->SetState(ApplicationState::APP_STATE_BACKGROUND); + processOptimizerUBA->OnAppStateChanged(app, ApplicationState::APP_STATE_SUSPENDED); + oomAdj = priorityObject->GetCurAdj(); + EXPECT_TRUE(oomAdj == APP_OOM_ADJ_BACKGROUND_MIN); + } + + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_003 end"); +} + +/* + * Feature: AMS + * Function: ProcessOptimizer + * SubFunction: OnAppRemoved + * FunctionPoints: remove application + * CaseDescription: 1. Call the OnAppStateChanged function to make the conditions meet and call the StartAppSuspendTimer + function + 2. Calling the OnAppRemoved function will call the StopAppSuspendTimer function + */ +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppRemoved_001, TestSize.Level1) +{ + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppRemoved_001 start"); + + bool isSuccess = processOptimizerUBA->Init(); + EXPECT_TRUE(true == isSuccess); + + auto appInfo = std::make_shared(); + appInfo->name = APP_RECORD_NAME; + appInfo->bundleName = APP_RECORD_NAME; // specify process condition + + auto app = std::make_shared(appInfo, AppRecordId::Create(), appInfo->bundleName); + processOptimizerUBA->OnAppAdded(app); + app->SetState(ApplicationState::APP_STATE_BACKGROUND); + auto priorityObject = app->GetPriorityObject(); + priorityObject->SetPid(1500); + priorityObject->SetVisibleStatus(false); + priorityObject->SetPerceptibleStatus(false); + + processOptimizerUBA->OnAppStateChanged(app, ApplicationState::APP_STATE_FOREGROUND); + processOptimizerUBA->OnAppRemoved(app); + + auto oomAdj = priorityObject->GetCurAdj(); + + EXPECT_TRUE(oomAdj == APP_OOM_ADJ_BACKGROUND_MIN); + + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppRemoved_001 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/test/moduletest/common/ams/service_app_spawn_client_test/BUILD.gn b/services/test/moduletest/common/ams/service_app_spawn_client_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..b81874150a2046a2d8f678bb6554d6f4f3ee1cd2 --- /dev/null +++ b/services/test/moduletest/common/ams/service_app_spawn_client_test/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsServiceAppSpawnClientModuleTest") { + module_out_path = module_output_path + + include_dirs = + [ "//base/hiviewdfx/hilog/interfaces/native/innerkits/include" ] + defines = [ "usleep(time) = MockSleep(time)" ] + + sources = [ + "//foundation/aafwk/standard/services/appmgr/src/system_environment_information.cpp", + "ams_service_app_spawn_client_module_test.cpp", + ] + + deps = [ + "${services_path}/test/moduletest/common/ams:appmgr_mst_source", + "//base/global/i18n_standard/frameworks/intl:intl_util", + ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsServiceAppSpawnClientModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..840fe9e1859653155b90a86fbc6ab4df4650181e --- /dev/null +++ b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp @@ -0,0 +1,704 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 // std::chrono::seconds +#include + +#include "securec.h" + +// redefine private and protected since testcase need to invoke and test private function +#define private public +#define protected public +#include "app_mgr_service.h" +#undef private +#undef protected + +#include "app_log_wrapper.h" +#include "mock_app_spawn_socket.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using testing::_; +using testing::AtLeast; +using testing::InSequence; +using testing::Invoke; +using testing::Return; + +namespace { +const uint32_t CYCLE_NUMBER = 10; +const int32_t PID_VALUE = 13579; +const int32_t CONNECT_RETRY_MAX_TIMES = 15; +} // namespace + +// this function is only used to mock sleep method so mst can run without delay. +int MockSleep([[maybe_unused]] uint32_t seconds) +{ + return 0; +} +namespace OHOS { +namespace AppExecFwk { +class MockedAppSpawnSocket : public AppSpawnSocket { +public: + MockedAppSpawnSocket() + {} + + ~MockedAppSpawnSocket() + {} + + int32_t OpenAppSpawnConnection() override + { + APP_LOGI("MockedAppSpawnSocket::OpenAppSpawnConnection ready to openConnection!"); + gHasConnected_ = true; + if (!gConnectSuccess_) { + APP_LOGE("MockedAppSpawnSocket::OpenAppSpawnConnection mock case failed to openConnection!"); + return ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED; + } + return ERR_OK; + } + + void CloseAppSpawnConnection() override + { + APP_LOGI("MockedAppSpawnSocket::CloseAppSpawnConnection ready to openConnection!"); + } + + int32_t WriteMessage([[maybe_unused]] const void *buf, [[maybe_unused]] int32_t len) override + { + if (!gHasConnected_) { + APP_LOGE("MockedAppSpawnSocket::WriteMessage mock case not openConnection!"); + return ERR_APPEXECFWK_BAD_APPSPAWN_SOCKET; + } + if (!gConnectSuccess_) { + APP_LOGE("MockedAppSpawnSocket::WriteMessage mock case failed to openConnection!"); + return ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED; + } + if (!gWriteMessageSuccess_) { + APP_LOGE("MockedAppSpawnSocket::WriteMessage mock case failed to writeMessage!"); + return ERR_APPEXECFWK_SOCKET_WRITE_FAILED; + } + return ERR_OK; + } + + int32_t ReadMessage(void *buf, [[maybe_unused]] int32_t len) override + { + if (!gHasConnected_) { + APP_LOGE("MockedAppSpawnSocket::ReadMessage mock case not openConnection!"); + return ERR_APPEXECFWK_BAD_APPSPAWN_SOCKET; + } + if (!gConnectSuccess_) { + APP_LOGE("MockedAppSpawnSocket::ReadMessage mock case failed to openConnection!"); + return ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED; + } + if (!gReadMessageSuccess_) { + APP_LOGE("MockedAppSpawnSocket::ReadMessage mock case failed to readMessage!"); + return ERR_APPEXECFWK_SOCKET_READ_FAILED; + } + AppSpawnPidMsg msg; + msg.pid = PID_VALUE; + if (memcpy_s(buf, sizeof(msg), msg.pidBuf, sizeof(msg)) != EOK) { + return ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED; + } + return ERR_OK; + } + + static bool gConnectSuccess_; + static bool gHasConnected_; + static bool gWriteMessageSuccess_; + static bool gReadMessageSuccess_; +}; + +bool MockedAppSpawnSocket::gHasConnected_ = false; +bool MockedAppSpawnSocket::gConnectSuccess_ = true; +bool MockedAppSpawnSocket::gWriteMessageSuccess_ = true; +bool MockedAppSpawnSocket::gReadMessageSuccess_ = true; + +class MockedAppMgrServiceInner : public AppMgrServiceInner { +public: + MockedAppMgrServiceInner() + : socket_(std::make_shared()), appSpawnClient_(std::make_unique()) + { + appSpawnClient_->SetSocket(socket_); + } + + virtual ~MockedAppMgrServiceInner() + {} + int32_t OpenAppSpawnConnection() override + { + if (appSpawnClient_.get() != nullptr) { + return appSpawnClient_->OpenConnection(); + } + return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT; + } + + SpawnConnectionState QueryAppSpawnConnectionState() const override + { + if (appSpawnClient_) { + return appSpawnClient_->QueryConnectionState(); + } + return SpawnConnectionState::STATE_NOT_CONNECT; + } + + void CloseAppSpawnConnection() const override + { + if (appSpawnClient_) { + appSpawnClient_->CloseConnection(); + } + } + +private: + std::shared_ptr socket_; + std::unique_ptr appSpawnClient_; +}; + +class AmsServiceAppSpawnClientModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsServiceAppSpawnClientModuleTest::SetUpTestCase() +{} + +void AmsServiceAppSpawnClientModuleTest::TearDownTestCase() +{} + +void AmsServiceAppSpawnClientModuleTest::SetUp() +{ + MockedAppSpawnSocket::gHasConnected_ = false; + MockedAppSpawnSocket::gConnectSuccess_ = true; + MockedAppSpawnSocket::gWriteMessageSuccess_ = true; + MockedAppSpawnSocket::gReadMessageSuccess_ = true; +} + +void AmsServiceAppSpawnClientModuleTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: Create AppSpawnClient and connect to AppSpawnDaemon + * EnvConditions: NA + * CaseDescription: Test if AppMgrService act normal when create appspawnclient and connect to AppSpawnDaemon. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_001, TestSize.Level2) +{ + APP_LOGI("ConnectAppSpawnDaemon_001 start"); + std::shared_ptr appMgrService = std::make_shared(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + std::shared_ptr amsInner = std::make_shared(); + appMgrService->SetInnerService(amsInner); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + appMgrService->OnStart(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + appMgrService->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); + } + APP_LOGI("ConnectAppSpawnDaemon_001 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: Create AppSpawnClient and connect to AppSpawnDaemon in AppMgrService_002 + * EnvConditions: NA + * CaseDescription: Test if AppMgrService act normal when create appspawnclient and failed connect to AppSpawnDaemon. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_002, TestSize.Level2) +{ + APP_LOGI("ConnectAppSpawnDaemon_002 start"); + std::shared_ptr appMgrService = std::make_shared(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + std::shared_ptr amsInner = std::make_shared(); + appMgrService->SetInnerService(amsInner); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + MockedAppSpawnSocket::gConnectSuccess_ = false; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + appMgrService->OnStart(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECT_FAILED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECT_FAILED, amsInner->QueryAppSpawnConnectionState()); + appMgrService->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); + MockedAppSpawnSocket::gConnectSuccess_ = true; + appMgrService->OnStart(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + appMgrService->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); + } + APP_LOGI("ConnectAppSpawnDaemon_002 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient connect to AppSpawnDaemon + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when connect to AppSpawnDaemon twice. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_003, TestSize.Level2) +{ + APP_LOGI("ConnectAppSpawnDaemon_003 start"); + std::shared_ptr appMgrService = std::make_shared(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + std::shared_ptr amsInner = std::make_shared(); + appMgrService->SetInnerService(amsInner); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + appMgrService->OnStart(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + appMgrService->OnStart(); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + appMgrService->OnStop(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); + } + APP_LOGI("ConnectAppSpawnDaemon_003 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient connect to AppSpawnDaemon + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when connect to AppSpawnDaemon successfully. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_004, TestSize.Level1) +{ + APP_LOGI("ConnectAppSpawnDaemon_004 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appSpawnClient->QueryConnectionState()); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + appSpawnClient->CloseConnection(); + } + APP_LOGI("ConnectAppSpawnDaemon_004 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when successfully to send normal request message. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_005, TestSize.Level1) +{ + APP_LOGI("ConnectAppSpawnDaemon_005 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + int32_t pid = PID_VALUE; + int32_t newPid = 0; + appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(pid, newPid); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + } + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ConnectAppSpawnDaemon_005 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when connect daemon successfully but failed + * to start process when try to send abnormal request message with wrong AppName. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_006, TestSize.Level1) +{ + APP_LOGI("ConnectAppSpawnDaemon_006 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + std::string illegalAppName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789012345678901234567890123456789" + "0123456789012345"; // The length is 256. + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", illegalAppName}; + int32_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED, result); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + } + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ConnectAppSpawnDaemon_006 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when connect daemon successfully but failed + * to start process when try to send abnormal request message with wrong ClsName. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_007, TestSize.Level1) +{ + APP_LOGI("ConnectAppSpawnDaemon_007 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + + std::string illegalClsName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789012345678901234567890123456789" + "0123456789012345"; // The length is 256. + appSpawnClient->SetSocket(mockedAppSpawnSocket); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", illegalClsName}; + int32_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED, result); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + } + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ConnectAppSpawnDaemon_007 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when connect daemon successfully but failed to start + * process when try to send abnormal request message with wrong FuncName. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_008, TestSize.Level1) +{ + APP_LOGI("ConnectAppSpawnDaemon_008 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + + std::string illegalFuncName = "0123456789012345678901234567890123456789012345678901234567890123456789012345678" + "0123456789012345678901234567890123456789012345678901234567890123456789012345678" + "0123456789012345678901234567890123456789012345678901234567890123456789012345678" + "0123456789012345999"; // The length is 256. + appSpawnClient->SetSocket(mockedAppSpawnSocket); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", illegalFuncName}; + int32_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED, result); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + } + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ConnectAppSpawnDaemon_008 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when connect daemon successfully but failed to start + * process when try to send abnormal request message with wrong argnum. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_009, TestSize.Level1) +{ + APP_LOGI("ConnectAppSpawnDaemon_009 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + + int32_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_OK, result); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + } + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ConnectAppSpawnDaemon_009 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: NA + * CaseDescription: Test if AppSpawnClient act normal when connect daemon successfully but failed to start + * process when try to send abnormal request message with wrong ArgName and ArgNum. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_010, TestSize.Level1) +{ + APP_LOGI("ConnectAppSpawnDaemon_010 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + EXPECT_EQ(ERR_OK, appSpawnClient->OpenConnection()); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + + int32_t newPid = 0; + ErrCode result = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_OK, result); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + } + appSpawnClient->CloseConnection(); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ConnectAppSpawnDaemon_010 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Test if AppSpawnClient act normal when failed to connect daemon at first but reconnect successfully. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ReconnectAppSpawnDaemon_001, TestSize.Level1) +{ + APP_LOGI("ReconnectAppSpawnDaemon_001 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + + int32_t pid = PID_VALUE; + int32_t newPid = 0; + + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()) + .WillOnce(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)) + .WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, ReadMessage(_, _)) + .WillRepeatedly(Invoke(mockedAppSpawnSocket.get(), &MockAppSpawnSocket::ReadImpl)); + + EXPECT_CALL(*mockedAppSpawnSocket, CloseAppSpawnConnection()).Times(1); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, mockedAppSpawnSocket->OpenAppSpawnConnection()); + mockedAppSpawnSocket->SetExpectPid(pid); + auto returnCode = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(pid, newPid); + EXPECT_EQ(ERR_OK, returnCode); + APP_LOGI("ReconnectAppSpawnDaemon_001 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Test if AppSpawnClient act normal when failed to connect daemon but the last reconnect successfully. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ReconnectAppSpawnDaemon_002, TestSize.Level1) +{ + APP_LOGI("ReconnectAppSpawnDaemon_002 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + + int32_t pid = PID_VALUE; + int32_t newPid = 0; + InSequence sequence; + + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()) + .Times(CONNECT_RETRY_MAX_TIMES) + .WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)) + .RetiresOnSaturation(); + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, ReadMessage(_, _)) + .WillRepeatedly(Invoke(mockedAppSpawnSocket.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*mockedAppSpawnSocket, CloseAppSpawnConnection()).Times(AtLeast(1)); + mockedAppSpawnSocket->SetExpectPid(pid); + auto returnCode = appSpawnClient->StartProcessImpl(params, newPid); + EXPECT_EQ(pid, newPid); + EXPECT_EQ(ERR_OK, returnCode); + APP_LOGI("ReconnectAppSpawnDaemon_002 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Test if AppSpawnClient act normal when failed to connect daemon and still fail to reconnect + * for the max times. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ReconnectAppSpawnDaemon_003, TestSize.Level1) +{ + APP_LOGI("ReconnectAppSpawnDaemon_003 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + + int32_t pid = PID_VALUE; + int32_t newPid = 0; + InSequence sequence; + + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()) + .Times(CONNECT_RETRY_MAX_TIMES + 1) + .WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)); + mockedAppSpawnSocket->SetExpectPid(pid); + auto returnCode = appSpawnClient->StartProcessImpl(params, newPid); + EXPECT_NE(pid, newPid); + EXPECT_EQ(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED, returnCode); + APP_LOGI("ReconnectAppSpawnDaemon_003 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Test if AppSpawnClient act normal when failed to start process for ReadMessage, + * but the last is successful. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ReconnectAppSpawnDaemon_004, TestSize.Level1) +{ + APP_LOGI("ReconnectAppSpawnDaemon_004 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + int32_t pid = PID_VALUE; + int32_t newPid = 0; + InSequence sequence; + + for (int32_t i = 0; i < CONNECT_RETRY_MAX_TIMES; i++) { + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, WriteMessage(_, _)) + .WillRepeatedly(Return(ERR_APPEXECFWK_SOCKET_WRITE_FAILED)) + .RetiresOnSaturation(); + EXPECT_CALL(*mockedAppSpawnSocket, ReadMessage(_, _)).WillRepeatedly(Return(ERR_OK)).RetiresOnSaturation(); + EXPECT_CALL(*mockedAppSpawnSocket, CloseAppSpawnConnection()).Times(1); + } + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, WriteMessage(_, _)).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, ReadMessage(_, _)) + .WillOnce(Invoke(mockedAppSpawnSocket.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*mockedAppSpawnSocket, CloseAppSpawnConnection()).Times(1); + + mockedAppSpawnSocket->SetExpectPid(pid); + auto returnCode = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(pid, newPid); + EXPECT_EQ(ERR_OK, returnCode); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ReconnectAppSpawnDaemon_004 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Test if AppSpawnClient act normal when failed to connect daemon for ReadMessage. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ReconnectAppSpawnDaemon_005, TestSize.Level1) +{ + APP_LOGI("ReconnectAppSpawnDaemon_005 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + int32_t newPid = 0; + + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, ReadMessage(_, _)).WillRepeatedly(Return(ERR_APPEXECFWK_SOCKET_READ_FAILED)); + EXPECT_CALL(*mockedAppSpawnSocket, CloseAppSpawnConnection()).Times(CONNECT_RETRY_MAX_TIMES + 1); + EXPECT_EQ(ERR_OK, mockedAppSpawnSocket->OpenAppSpawnConnection()); + auto returnCode = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(ERR_APPEXECFWK_SOCKET_READ_FAILED, returnCode); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ReconnectAppSpawnDaemon_005 end"); +} + +/* + * Feature: AppMgrService + * Function: AppSpawnClient + * SubFunction: NA + * FunctionPoints: AppSpawnClient request normal process + * EnvConditions: mobile that can run ohos test framework + * CaseDescription: Test if AppSpawnClient act normal when failed to connect daemon for + * ((CONNECT_RETRY_MAX_TIMES + 1) * (CONNECT_RETRY_MAX_TIMES + 1) - 1) times, + * but the last is successful. + */ +HWTEST_F(AmsServiceAppSpawnClientModuleTest, ReconnectAppSpawnDaemon_006, TestSize.Level1) +{ + APP_LOGI("ReconnectAppSpawnDaemon_006 start"); + std::shared_ptr appSpawnClient = std::make_shared(); + std::shared_ptr mockedAppSpawnSocket = std::make_shared(); + appSpawnClient->SetSocket(mockedAppSpawnSocket); + AppSpawnStartMsg params = {10001, 10001, {10001, 10002}, "processName", "soPath"}; + int32_t pid = PID_VALUE; + int32_t newPid = 0; + InSequence sequence; + + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()) + .Times((CONNECT_RETRY_MAX_TIMES + 1) * (CONNECT_RETRY_MAX_TIMES + 1) - 1) + .WillRepeatedly(Return(ERR_APPEXECFWK_CONNECT_APPSPAWN_FAILED)) + .RetiresOnSaturation(); + EXPECT_CALL(*mockedAppSpawnSocket, OpenAppSpawnConnection()).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, WriteMessage(_, _)).WillRepeatedly(Return(ERR_OK)); + EXPECT_CALL(*mockedAppSpawnSocket, ReadMessage(_, _)) + .WillRepeatedly(Invoke(mockedAppSpawnSocket.get(), &MockAppSpawnSocket::ReadImpl)); + EXPECT_CALL(*mockedAppSpawnSocket, CloseAppSpawnConnection()).Times(AtLeast(1)); + mockedAppSpawnSocket->SetExpectPid(pid); + auto returnCode = appSpawnClient->StartProcess(params, newPid); + EXPECT_EQ(pid, newPid); + EXPECT_EQ(ERR_OK, returnCode); + EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appSpawnClient->QueryConnectionState()); + APP_LOGI("ReconnectAppSpawnDaemon_006 end"); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/service_event_drive_test/BUILD.gn b/services/test/moduletest/common/ams/service_event_drive_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..42b2dec3580e9943c853ba3590d105656ab7792c --- /dev/null +++ b/services/test/moduletest/common/ams/service_event_drive_test/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsServiceEventDriveModuleTest") { + module_out_path = module_output_path + + include_dirs = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include/hilog/", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + + sources = [ + "${services_path}/appmgr/src/system_environment_information.cpp", + "ams_service_event_drive_module_test.cpp", + ] + + deps = [ + "${services_path}/test/moduletest/common/ams:appmgr_mst_source", + "//base/global/i18n_standard/frameworks/intl:intl_util", + ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsServiceEventDriveModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp b/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bddabe6789245d19a0a1389fe4ab6f26b381faa --- /dev/null +++ b/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp @@ -0,0 +1,575 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function +#define private public +#define protected public +#include "app_mgr_service.h" +#undef private +#undef protected +#include "app_log_wrapper.h" +#include "semaphore_ex.h" + +#include + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using OHOS::Semaphore; + +namespace { +const uint32_t CYCLE_NUMBER = 10000; +} +enum class AmsInnerState { + STATE_NO_OPERATION, + STATE_ABILITY_LOADED, + STATE_APPLICATION_FOREGROUNDED, + STATE_APPLICATION_BACKGROUNDED, + STATE_APPLICATION_TERMINATED, + STATE_APPLICATION_BACK_TO_FORE, + STATE_APPLICATION_FORE_TO_BACK, + STATE_APPLICATION_BACK_TO_TER, + STATE_APPLICATION_FORE_TO_TER, + STATE_APPLICATION_TER_TO_FORE, + STATE_APPLICATION_TER_TO_BACK, +}; + +class MockedAppMgrServiceInner : public AppMgrServiceInner { +public: + MockedAppMgrServiceInner() : lock_(0) + {} + ~MockedAppMgrServiceInner() + {} + + void ApplicationForegrounded([[maybe_unused]] const int32_t recordId) override + { + if (lastState_ == AmsInnerState::STATE_APPLICATION_BACKGROUNDED || + lastState_ == AmsInnerState::STATE_APPLICATION_FORE_TO_BACK || + lastState_ == AmsInnerState::STATE_APPLICATION_TER_TO_BACK) { + state_ = AmsInnerState::STATE_APPLICATION_BACK_TO_FORE; + } else if (lastState_ == AmsInnerState::STATE_APPLICATION_TERMINATED || + lastState_ == AmsInnerState::STATE_APPLICATION_BACK_TO_TER || + lastState_ == AmsInnerState::STATE_APPLICATION_FORE_TO_TER) { + state_ = AmsInnerState::STATE_APPLICATION_TER_TO_FORE; + } else { + state_ = AmsInnerState::STATE_APPLICATION_FOREGROUNDED; + } + + lastState_ = AmsInnerState::STATE_APPLICATION_FOREGROUNDED; + Post(); + } + + void ApplicationBackgrounded([[maybe_unused]] const int32_t recordId) override + { + if (lastState_ == AmsInnerState::STATE_APPLICATION_FOREGROUNDED || + lastState_ == AmsInnerState::STATE_APPLICATION_BACK_TO_FORE || + lastState_ == AmsInnerState::STATE_APPLICATION_TER_TO_FORE) { + state_ = AmsInnerState::STATE_APPLICATION_FORE_TO_BACK; + } else if (lastState_ == AmsInnerState::STATE_APPLICATION_TERMINATED || + lastState_ == AmsInnerState::STATE_APPLICATION_BACK_TO_TER || + lastState_ == AmsInnerState::STATE_APPLICATION_FORE_TO_TER) { + state_ = AmsInnerState::STATE_APPLICATION_TER_TO_BACK; + } else { + state_ = AmsInnerState::STATE_APPLICATION_BACKGROUNDED; + } + + lastState_ = AmsInnerState::STATE_APPLICATION_BACKGROUNDED; + Post(); + } + + void ApplicationTerminated([[maybe_unused]] const int32_t recordId) override + { + if (lastState_ == AmsInnerState::STATE_APPLICATION_FOREGROUNDED || + lastState_ == AmsInnerState::STATE_APPLICATION_BACK_TO_FORE || + lastState_ == AmsInnerState::STATE_APPLICATION_TER_TO_FORE) { + state_ = AmsInnerState::STATE_APPLICATION_FORE_TO_TER; + } else if (lastState_ == AmsInnerState::STATE_APPLICATION_BACKGROUNDED || + lastState_ == AmsInnerState::STATE_APPLICATION_FORE_TO_BACK || + lastState_ == AmsInnerState::STATE_APPLICATION_TER_TO_BACK) { + state_ = AmsInnerState::STATE_APPLICATION_BACK_TO_TER; + } else { + state_ = AmsInnerState::STATE_APPLICATION_TERMINATED; + } + + lastState_ = AmsInnerState::STATE_APPLICATION_TERMINATED; + Post(); + } + + void Wait() + { + lock_.Wait(); + } + + void SetWaitNum(const int waitNum) + { + count_ = waitNum; + currentCount_ = waitNum; + } + + AmsInnerState GetInnerServiceState() const + { + return state_; + } + + AmsInnerState SetInnerServiceState(const AmsInnerState &state) + { + state_ = state; + return state_; + } + + int32_t OpenAppSpawnConnection() override + { + return 0; + } + +private: + Semaphore lock_ = {0}; + int32_t count_ = 1; + int32_t currentCount_ = 1; + AmsInnerState state_ = AmsInnerState::STATE_NO_OPERATION; + AmsInnerState lastState_ = AmsInnerState::STATE_NO_OPERATION; + + void Post() + { + if (currentCount_ > 1) { + currentCount_--; + } else { + lock_.Post(); + currentCount_ = count_; + } + } +}; + +class AmsServiceEventDriveModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr appMgrService_; +}; + +void AmsServiceEventDriveModuleTest::SetUpTestCase() +{} + +void AmsServiceEventDriveModuleTest::TearDownTestCase() +{} + +void AmsServiceEventDriveModuleTest::SetUp() +{ + appMgrService_ = std::make_shared(); +} + +void AmsServiceEventDriveModuleTest::TearDown() +{ + appMgrService_.reset(); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from background to foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_001, TestSize.Level2) +{ + APP_LOGI("AmsServiceEventDrive_001 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationForegrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_BACK_TO_FORE, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_001 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from foreground to background. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_002, TestSize.Level2) +{ + APP_LOGI("AmsServiceEventDrive_002 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_FORE_TO_BACK, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_002 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from background to terminate. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_003, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_003 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_BACK_TO_TER, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_003 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from foreground to terminated. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_004, TestSize.Level2) +{ + APP_LOGI("AmsServiceEventDrive_004 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_FORE_TO_TER, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_004 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from terminate to foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_005, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_005 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationForegrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_TER_TO_FORE, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_005 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from terminate to background. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_006, TestSize.Level2) +{ + APP_LOGI("AmsServiceEventDrive_006 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_TER_TO_BACK, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_006 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application among terminate, background and foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_007, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_007 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 3 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationForegrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_BACK_TO_FORE, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_007 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application among terminate, background and foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_008, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_008 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 3 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_FORE_TO_BACK, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_008 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application among terminate, background and foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_009, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_009 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 3 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_TER_TO_BACK, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_009 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application among terminate, background and foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_010, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_010 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 3 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_BACK_TO_TER, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_010 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application among terminate, background and foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_011, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_011 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 3 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_FORE_TO_TER, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_011 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application among terminate, background and foreground. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_012, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_012 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 3 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationForegrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_TER_TO_FORE, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_012 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from terminate to terminate. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_013, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_013 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationTerminated(recordId); + appMgrService_->ApplicationTerminated(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_TERMINATED, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_013 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from backgrounded to backgrounded. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_014, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_014 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationBackgrounded(recordId); + appMgrService_->ApplicationBackgrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_BACKGROUNDED, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_014 end"); +} + +/* + * Feature: AppMgrService + * Function: EventDrive + * SubFunction: NA + * FunctionPoints: AppMgrService event drive program model + * EnvConditions: NA + * CaseDescription: Verify if post application from terminate to terminate. + */ +HWTEST_F(AmsServiceEventDriveModuleTest, AmsServiceEventDrive_015, TestSize.Level1) +{ + APP_LOGI("AmsServiceEventDrive_015 start"); + std::shared_ptr innerService = std::make_shared(); + appMgrService_->SetInnerService(innerService); + appMgrService_->OnStart(); + int32_t recordId = 0; + int32_t waitCount = 2 * CYCLE_NUMBER; + innerService->SetWaitNum(waitCount); + for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { + appMgrService_->ApplicationForegrounded(recordId); + appMgrService_->ApplicationForegrounded(recordId); + } + innerService->Wait(); + EXPECT_EQ(AmsInnerState::STATE_APPLICATION_FOREGROUNDED, innerService->GetInnerServiceState()); + APP_LOGI("AmsServiceEventDrive_015 end"); +} \ No newline at end of file diff --git a/services/test/moduletest/common/ams/service_start_process_test/BUILD.gn b/services/test/moduletest/common/ams/service_start_process_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..b66d65a9261b6223826a61c72ab85b515018683b --- /dev/null +++ b/services/test/moduletest/common/ams/service_start_process_test/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/mstappmgrservice" + +ohos_moduletest("AmsServiceStartModuleTest") { + module_out_path = module_output_path + + include_dirs = + [ "//base/hiviewdfx/hilog/interfaces/native/innerkits/include" ] + sources = [ + "${services_path}/appmgr/src/system_environment_information.cpp", + "ams_service_start_process_module_test.cpp", + ] + + deps = [ + "${services_path}/test/moduletest/common/ams:appmgr_mst_source", + "//base/global/i18n_standard/frameworks/intl:intl_util", + ] + + external_deps = [ "ipc:ipc_core" ] +} + +group("moduletest") { + testonly = true + + deps = [ ":AmsServiceStartModuleTest" ] +} diff --git a/services/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp b/services/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53e88c5284af87fd6eba22b2a82c70a980eeab17 --- /dev/null +++ b/services/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +// redefine private and protected since testcase need to invoke and test private function +#define private public +#define protected public +#include "app_mgr_service.h" +#undef private +#undef protected +#include +#include "app_log_wrapper.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +namespace { +const int CYCLE_NUMBER = 10000; +} // namespace + +class AppMgrServiceInnerMock : public AppMgrServiceInner { +public: + int32_t OpenAppSpawnConnection() override + { + return 0; + } +}; + +class AmsServiceStartModuleTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AmsServiceStartModuleTest::SetUpTestCase() +{} + +void AmsServiceStartModuleTest::TearDownTestCase() +{} + +void AmsServiceStartModuleTest::SetUp() +{} + +void AmsServiceStartModuleTest::TearDown() +{} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: NA + * FunctionPoints: AppMgrService startup + * EnvConditions: NA + * CaseDescription: Verify if AppMgrService startup 10000 times. + */ +HWTEST_F(AmsServiceStartModuleTest, AmsStartupMoretimes_001, TestSize.Level1) +{ + APP_LOGI("AmsStartupMoretimes_001 start"); + std::shared_ptr appMgrService = std::make_shared(); + EXPECT_TRUE(appMgrService.get() != nullptr); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + + for (int i = 0; i < CYCLE_NUMBER; i++) { + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + } + + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + APP_LOGI("AmsStartupMoretimes_001 end"); +} + +/* + * Feature: AppMgrService + * Function: Service + * SubFunction: NA + * FunctionPoints: AppMgrService startup + * EnvConditions: NA + * CaseDescription: Verify if AppMgrService stop 10000 times. + */ +HWTEST_F(AmsServiceStartModuleTest, AmsStartupMoretimes_002, TestSize.Level1) +{ + APP_LOGI("AmsStartupMoretimes_002 start"); + std::shared_ptr appMgrService = std::make_shared(); + EXPECT_TRUE(appMgrService.get() != nullptr); + std::shared_ptr innerService = std::make_shared(); + appMgrService->SetInnerService(innerService); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + + for (int i = 0; i < CYCLE_NUMBER; i++) { + appMgrService->OnStop(); + EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); + } + + appMgrService->OnStart(); + EXPECT_EQ(ServiceRunningState::STATE_RUNNING, appMgrService->QueryServiceState().serviceRunningState); + APP_LOGI("AmsStartupMoretimes_002 end"); +} diff --git a/services/test/moduletest/dump_module_test/BUILD.gn b/services/test/moduletest/dump_module_test/BUILD.gn old mode 100644 new mode 100755 index 264dc4050016263e4f81748793d46072deec4ed4..2a3b91a067aa9b677a406c705c2a9201c193128a --- a/services/test/moduletest/dump_module_test/BUILD.gn +++ b/services/test/moduletest/dump_module_test/BUILD.gn @@ -13,7 +13,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" ohos_moduletest("dump_module_test") { module_out_path = module_output_path @@ -57,11 +57,13 @@ ohos_moduletest("dump_module_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] external_deps = [ "bytrace_standard:bytrace_core", + "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/test/moduletest/dump_module_test/dump_module_test.cpp b/services/test/moduletest/dump_module_test/dump_module_test.cpp index 96601afe88bdafe7c56ee047c1965b70d940d399..68943019cac041436adca66c4d22ecc655faad5f 100644 --- a/services/test/moduletest/dump_module_test/dump_module_test.cpp +++ b/services/test/moduletest/dump_module_test/dump_module_test.cpp @@ -118,9 +118,9 @@ void DumpModuleTest::OnStartAms() if (g_abilityMs->state_ == ServiceRunningState::STATE_RUNNING) { return; } - + g_abilityMs->state_ = ServiceRunningState::STATE_RUNNING; - + g_abilityMs->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(g_abilityMs->eventLoop_); @@ -135,9 +135,9 @@ void DumpModuleTest::OnStartAms() g_abilityMs->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(g_abilityMs->pendingWantManager_); - + int userId = g_abilityMs->GetUserId(); - g_abilityMs->SetStackManager(userId); + g_abilityMs->SetStackManager(userId, true); g_abilityMs->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(g_abilityMs->systemAppManager_); diff --git a/services/test/moduletest/ipc_ability_connect_test/BUILD.gn b/services/test/moduletest/ipc_ability_connect_test/BUILD.gn index 4b226686fbd6413373f3a72119fb415a783291c1..639d6687c5d46874922124609c73234134597465 100644 --- a/services/test/moduletest/ipc_ability_connect_test/BUILD.gn +++ b/services/test/moduletest/ipc_ability_connect_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" ohos_moduletest("IpcAbilityConnectModuleTest") { module_out_path = module_output_path @@ -34,6 +34,7 @@ ohos_moduletest("IpcAbilityConnectModuleTest") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", "//utils/native/base:utilsbase", ] diff --git a/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn b/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn index a07b9f281d4f3eae1b2655c7d2129e32db9204f0..56cbc7392031bb22705464a29d95945f25c2b826 100644 --- a/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn +++ b/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" ohos_moduletest("IpcAbilityMgrServiceModuleTest") { module_out_path = module_output_path @@ -24,13 +24,14 @@ ohos_moduletest("IpcAbilityMgrServiceModuleTest") { configs = [ "${services_path}/test:aafwk_module_test_config", "//foundation/appexecfwk/standard/common:appexecfwk_common_config", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appmgr_sdk_config", + "${aafwk_path}/interfaces/innerkits/app_manager:appmgr_sdk_config", ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${innerkits_path}/want:want", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", @@ -39,6 +40,7 @@ ohos_moduletest("IpcAbilityMgrServiceModuleTest") { "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//third_party/jsoncpp:jsoncpp", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] diff --git a/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp b/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp index 69b19815e655d0dd547fffbe1847da2130b71755..fde03e58f83ff571eaeed57a5050f29b9a513ed5 100644 --- a/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp +++ b/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp @@ -99,10 +99,10 @@ HWTEST_F(IpcAbilityMgrModuleTest, AbilityMgrService_IPC_001, TestSize.Level1) sptr abilityMgrClient = iface_cast(mockAbilityMgr); const Want want; - EXPECT_CALL(*mockAbilityMgr, StartAbility(_, _)) + EXPECT_CALL(*mockAbilityMgr, StartAbility(_, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(mockAbilityMgr.GetRefPtr(), &MockAbilityMgrService::Post)); - abilityMgrClient->StartAbility(want, 0); + abilityMgrClient->StartAbility(want, -1, 0); mockAbilityMgr->Wait(); } @@ -230,10 +230,10 @@ HWTEST_F(IpcAbilityMgrModuleTest, AbilityMgrService_IPC_006, TestSize.Level1) sptr abilityMgrClient = iface_cast(mockAbilityMgr); Want want; - EXPECT_CALL(*mockAbilityMgr, ConnectAbility(_, _, _)) + EXPECT_CALL(*mockAbilityMgr, ConnectAbility(_, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(mockAbilityMgr.GetRefPtr(), &MockAbilityMgrService::Post)); - abilityMgrClient->ConnectAbility(want, nullptr, nullptr); + abilityMgrClient->ConnectAbility(want, nullptr, nullptr, -1); mockAbilityMgr->Wait(); } @@ -427,10 +427,10 @@ HWTEST_F(IpcAbilityMgrModuleTest, AbilityMgrService_IPC_013, TestSize.Level1) sptr abilityMgrClient = iface_cast(mockAbilityMgr); const Want want; - EXPECT_CALL(*mockAbilityMgr, StopServiceAbility(_)) + EXPECT_CALL(*mockAbilityMgr, StopServiceAbility(_, _)) .Times(1) .WillOnce(InvokeWithoutArgs(mockAbilityMgr.GetRefPtr(), &MockAbilityMgrService::Post)); - abilityMgrClient->StopServiceAbility(want); + abilityMgrClient->StopServiceAbility(want, -1); mockAbilityMgr->Wait(); } diff --git a/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn b/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn index 568dec71797392027c1271c4b85fe910d8b849a3..4d0ca27ff790f0eb7d518b31f22aa2f8c194a381 100644 --- a/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn +++ b/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" ohos_moduletest("IpcAbilitySchedulerModuleTest") { module_out_path = module_output_path @@ -48,6 +48,7 @@ ohos_moduletest("IpcAbilitySchedulerModuleTest") { "${innerkits_path}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", @@ -55,6 +56,7 @@ ohos_moduletest("IpcAbilitySchedulerModuleTest") { "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//third_party/jsoncpp:jsoncpp", + "//third_party/libpng:libpng", "//utils/native/base:utilsbase", ] diff --git a/services/test/moduletest/module_test_dump_util/BUILD.gn b/services/test/moduletest/module_test_dump_util/BUILD.gn index 974a65c3c91d90a7c10c6c651e921f1ddb94756e..2a055106932f42d971d54a36e4da518bd2a307f2 100644 --- a/services/test/moduletest/module_test_dump_util/BUILD.gn +++ b/services/test/moduletest/module_test_dump_util/BUILD.gn @@ -33,5 +33,5 @@ ohos_shared_library("module_test_dump_util_lib") { external_deps = [ "hiviewdfx_hilog_native:libhilog" ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_runtime" } diff --git a/services/test/moduletest/panding_want_manager_test/BUILD.gn b/services/test/moduletest/panding_want_manager_test/BUILD.gn old mode 100644 new mode 100755 index 36928d3e212e23b322af12170fc953e014337374..db815d1f40732f900e5a6141951a108dea8abd8b --- a/services/test/moduletest/panding_want_manager_test/BUILD.gn +++ b/services/test/moduletest/panding_want_manager_test/BUILD.gn @@ -15,18 +15,20 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") import("//foundation/aafwk/standard/services/abilitymgr/abilitymgr.gni") -module_output_path = "aafwk_standard/mstabilitymgrservice" +module_output_path = "ability_runtime/mstabilitymgrservice" ohos_moduletest("PandingWantMgrTest") { module_out_path = module_output_path include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", "//foundation/aafwk/standard/services/test/mock/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmg", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", "//third_party/jsoncpp/include", + "//base/hiviewdfx/hicollie/interfaces/native/innerkits/include/xcollie", ] sources = abilityms_files @@ -48,11 +50,15 @@ ohos_moduletest("PandingWantMgrTest") { deps = [ "${innerkits_path}/base:base", "${innerkits_path}/want:want", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/hiviewdfx/hiview/adapter/utility:hiview_adapter_utility", "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", @@ -63,6 +69,7 @@ ohos_moduletest("PandingWantMgrTest") { "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//third_party/jsoncpp:jsoncpp", + "//third_party/libpng:libpng", "//utils/native/base:utils", ] @@ -70,7 +77,9 @@ ohos_moduletest("PandingWantMgrTest") { "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", + "device_manager_base:devicemanagersdk", "dsoftbus_standard:softbus_client", + "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", diff --git a/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp b/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp index b4732de8c8850fae73e3f6a6e938280e71ae4391..2b20747fefcf69ec6925492ed13e4833e6ae840c 100644 --- a/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp +++ b/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp @@ -26,6 +26,7 @@ #undef private #undef protected +#include "context/context.h" #include "system_ability_definition.h" #include "mock_ability_scheduler.h" #include "mock_app_mgr_client.h" @@ -35,6 +36,7 @@ #include "ability_context.h" #include "mock_compled_callback.h" #include "mock_ability_mgr_service.h" +#include "os_account_manager.h" using namespace OHOS::Notification::WantAgent; using namespace OHOS::AppExecFwk; @@ -73,7 +75,7 @@ public: public: MockWantReceiver *receiver = new MockWantReceiver(); inline static MockAppMgrClient *appClient = nullptr; - inline static std::shared_ptr ams = nullptr; + inline static std::shared_ptr abilityManager = nullptr; MockAbilityMgrService *amsSerice = new MockAbilityMgrService(); }; @@ -83,8 +85,8 @@ void PandingWantManagerTest::SetUpTestCase(void) OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new (std::nothrow) BundleMgrService()); - ams = OHOS::DelayedSingleton::GetInstance(); - ams->OnStart(); + abilityManager = OHOS::DelayedSingleton::GetInstance(); + abilityManager->OnStart(); auto appScheduler = DelayedSingleton::GetInstance(); appClient = new MockAppMgrClient(); @@ -268,18 +270,18 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_001, TestSize.Level1) wants.push_back(abilityWant); WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); // proxy start auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_ABILITY); - return ams->GetWantSender(wantSenderInfo, callerToken); + return abilityManager->GetWantSender(wantSenderInfo, callerToken); }; EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return ams->SendWantSender(target, senderInfo); + return abilityManager->SendWantSender(target, senderInfo); }; EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); @@ -291,7 +293,7 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_001, TestSize.Level1) auto pandingWant = wantAgent->GetPendingWant(); EXPECT_NE(pandingWant, nullptr); - // ams mock + // abilityManager mock EXPECT_CALL(*appClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::shared_ptr callback; @@ -301,10 +303,10 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_001, TestSize.Level1) TriggerInfo paramsInfo("", nullptr, abilityWant, 11); EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - WantAgentHelper::TriggerWantAgent(context, wantAgent, callback, paramsInfo); + WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); // An ability should be activated - auto stackMgr = ams->GetStackManager(); + auto stackMgr = abilityManager->GetStackManager(); EXPECT_NE(stackMgr, nullptr); auto topAbility = stackMgr->GetCurrentTopAbility(); EXPECT_NE(topAbility, nullptr); @@ -340,18 +342,18 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_002, TestSize.Level1) wants.push_back(abilityWant1); WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); // proxy start auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_ABILITIES); - return ams->GetWantSender(wantSenderInfo, callerToken); + return abilityManager->GetWantSender(wantSenderInfo, callerToken); }; EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return ams->SendWantSender(target, senderInfo); + return abilityManager->SendWantSender(target, senderInfo); }; EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); @@ -371,13 +373,13 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_002, TestSize.Level1) EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - auto stackMgr = ams->GetStackManager(); + auto stackMgr = abilityManager->GetStackManager(); EXPECT_NE(stackMgr, nullptr); auto topAbility = stackMgr->GetCurrentTopAbility(); EXPECT_NE(topAbility, nullptr); topAbility->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - WantAgentHelper::TriggerWantAgent(context, wantAgent, callback, paramsInfo); + WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); } /* @@ -401,18 +403,18 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_003, TestSize.Level1) wants.push_back(abilityWant); WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); // proxy start auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_SERVICE); - return ams->GetWantSender(wantSenderInfo, callerToken); + return abilityManager->GetWantSender(wantSenderInfo, callerToken); }; EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return ams->SendWantSender(target, senderInfo); + return abilityManager->SendWantSender(target, senderInfo); }; EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); @@ -424,7 +426,7 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_003, TestSize.Level1) auto pandingWant = wantAgent->GetPendingWant(); EXPECT_NE(pandingWant, nullptr); - // ams mock + // abilityManager mock EXPECT_CALL(*appClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::shared_ptr callback; @@ -434,10 +436,11 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_003, TestSize.Level1) TriggerInfo paramsInfo("", nullptr, abilityWant, 11); EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - WantAgentHelper::TriggerWantAgent(context, wantAgent, callback, paramsInfo); + WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); // An ability should be activated - auto serviceRecord = ams->connectManager_->GetServiceRecordByElementName(abilityWant->GetElement().GetURI()); + auto serviceRecord = + abilityManager->connectManager_->GetServiceRecordByElementName(abilityWant->GetElement().GetURI()); EXPECT_TRUE(serviceRecord); Want serviceWant = serviceRecord->GetWant(); ElementName element = serviceWant.GetElement(); @@ -467,18 +470,18 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_004, TestSize.Level1) wants.push_back(abilityWant); WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); // proxy start auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_FOREGROUND_SERVICE); - return ams->GetWantSender(wantSenderInfo, callerToken); + return abilityManager->GetWantSender(wantSenderInfo, callerToken); }; EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return ams->SendWantSender(target, senderInfo); + return abilityManager->SendWantSender(target, senderInfo); }; EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); @@ -490,7 +493,7 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_004, TestSize.Level1) auto pandingWant = wantAgent->GetPendingWant(); EXPECT_NE(pandingWant, nullptr); - // ams mock + // abilityManager mock EXPECT_CALL(*appClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::shared_ptr callback; @@ -500,10 +503,11 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_004, TestSize.Level1) TriggerInfo paramsInfo("", nullptr, abilityWant, 11); EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - WantAgentHelper::TriggerWantAgent(context, wantAgent, callback, paramsInfo); + WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); // An ability should be activated - auto serviceRecord = ams->connectManager_->GetServiceRecordByElementName(abilityWant->GetElement().GetURI()); + auto serviceRecord = + abilityManager->connectManager_->GetServiceRecordByElementName(abilityWant->GetElement().GetURI()); EXPECT_TRUE(serviceRecord); Want serviceWant = serviceRecord->GetWant(); ElementName element = serviceWant.GetElement(); @@ -532,18 +536,18 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_005, TestSize.Level1) wants.push_back(abilityWant); WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); // proxy start auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::SEND_COMMON_EVENT); - return ams->GetWantSender(wantSenderInfo, callerToken); + return abilityManager->GetWantSender(wantSenderInfo, callerToken); }; EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return ams->SendWantSender(target, senderInfo); + return abilityManager->SendWantSender(target, senderInfo); }; EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); @@ -562,7 +566,7 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_005, TestSize.Level1) TriggerInfo paramsInfo("", nullptr, abilityWant, 11); EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - WantAgentHelper::TriggerWantAgent(context, wantAgent, callback, paramsInfo); + WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); } /* @@ -586,28 +590,31 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_006, TestSize.Level1) wants.push_back(abilityWant); WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); // proxy start auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_ABILITY); - return ams->GetWantSender(wantSenderInfo, callerToken); + return abilityManager->GetWantSender(wantSenderInfo, callerToken); }; EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); - auto amsProxyGetPendingWantType = [&](const sptr &target) { return ams->GetPendingWantType(target); }; + auto amsProxyGetPendingWantType = + [&](const sptr &target) { return abilityManager->GetPendingWantType(target); }; EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Invoke(amsProxyGetPendingWantType)); - auto amsProxyGetPendingWantCode = [&](const sptr &target) { return ams->GetPendingWantCode(target); }; + auto amsProxyGetPendingWantCode = + [&](const sptr &target) { return abilityManager->GetPendingWantCode(target); }; EXPECT_CALL(*amsSerice, GetPendingWantCode(_)).Times(1).WillOnce(Invoke(amsProxyGetPendingWantCode)); auto amsProxyRegisterCancelListener = [&](const sptr &sender, const sptr &recevier) { - return ams->RegisterCancelListener(sender, recevier); + return abilityManager->RegisterCancelListener(sender, recevier); }; EXPECT_CALL(*amsSerice, RegisterCancelListener(_, _)).Times(1).WillOnce(Invoke(amsProxyRegisterCancelListener)); - auto amsProxyCancelWantSender = [&](const sptr &sender) { return ams->CancelWantSender(sender); }; + auto amsProxyCancelWantSender = + [&](const sptr &sender) { return abilityManager->CancelWantSender(sender); }; EXPECT_CALL(*amsSerice, CancelWantSender(_)).Times(1).WillOnce(Invoke(amsProxyCancelWantSender)); // proxy end @@ -653,13 +660,13 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_007, TestSize.Level1) wants.push_back(abilityWant); WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); // proxy start auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_ABILITY); - return ams->GetWantSender(wantSenderInfo, callerToken); + return abilityManager->GetWantSender(wantSenderInfo, callerToken); }; EXPECT_CALL(*amsSerice, GetWantSender(_, _)) .Times(4) @@ -669,7 +676,7 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_007, TestSize.Level1) .WillOnce(Invoke(amsProxyGetWantSenderReturn)); auto amsProxyRegisterCancelListener = [&](const sptr &sender, const sptr &recevier) { - return ams->RegisterCancelListener(sender, recevier); + return abilityManager->RegisterCancelListener(sender, recevier); }; EXPECT_CALL(*amsSerice, RegisterCancelListener(_, _)).Times(1).WillOnce(Invoke(amsProxyRegisterCancelListener)); // proxy end diff --git a/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestA.hap b/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestA.hap new file mode 100644 index 0000000000000000000000000000000000000000..5c07f9aa9567a79b96eb711b04818bd9676c9d35 Binary files /dev/null and b/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestA.hap differ diff --git a/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestB.hap b/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestB.hap new file mode 100644 index 0000000000000000000000000000000000000000..d9608931c12953f66bbcde4618c3e59a3e89a561 Binary files /dev/null and b/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestB.hap differ diff --git a/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestC.hap b/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestC.hap new file mode 100644 index 0000000000000000000000000000000000000000..9677cfb2307e4f0c0a3f584def2ac38c272573e5 Binary files /dev/null and b/test/resource/ams/ams_data_ability_bundle/amsDataSystemTestC.hap differ diff --git a/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestA.hap b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestA.hap new file mode 100644 index 0000000000000000000000000000000000000000..716671f28014e164447510e5c1de8f523da15534 Binary files /dev/null and b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestA.hap differ diff --git a/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestB.hap b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestB.hap new file mode 100644 index 0000000000000000000000000000000000000000..ba932df15389cb5a9612925ac66799cfe81d6d46 Binary files /dev/null and b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestB.hap differ diff --git a/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestDataA.hap b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestDataA.hap new file mode 100644 index 0000000000000000000000000000000000000000..c737d812bb1a539d7c0611cf051632a457b138db Binary files /dev/null and b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestDataA.hap differ diff --git a/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestDataB.hap b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestDataB.hap new file mode 100644 index 0000000000000000000000000000000000000000..3447e6a45c2aff9c90bc824d5b2e8c21f4a045c9 Binary files /dev/null and b/test/resource/ams/ams_data_ability_bundle/amsKitSystemTestDataB.hap differ diff --git a/test/resource/ams/ams_data_ability_bundle/test.txt b/test/resource/ams/ams_data_ability_bundle/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..b0f6d94e939d2ec0db6e489aa9fc4854664ef923 --- /dev/null +++ b/test/resource/ams/ams_data_ability_bundle/test.txt @@ -0,0 +1 @@ +4444 diff --git a/test/resource/ams/ams_page_ability_bundle/amsAbilityAppendTestA.hap b/test/resource/ams/ams_page_ability_bundle/amsAbilityAppendTestA.hap new file mode 100644 index 0000000000000000000000000000000000000000..88bf3787910b1d31aad16eebcba6109362aee3a7 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsAbilityAppendTestA.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsAbilityAppendTestB.hap b/test/resource/ams/ams_page_ability_bundle/amsAbilityAppendTestB.hap new file mode 100644 index 0000000000000000000000000000000000000000..06445c342e50cf51c472828b5f5a2dcf6816abd2 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsAbilityAppendTestB.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestPageA.hap b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestPageA.hap new file mode 100644 index 0000000000000000000000000000000000000000..27e8d584812c6d20a90d3bd75ddfd22605a70834 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestPageA.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestServiceB.hap b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestServiceB.hap new file mode 100644 index 0000000000000000000000000000000000000000..b75c6edc69c13456dd523e5cb7cfd86fd1f1a45e Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestServiceB.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsConfigurationUpdatedSingletonTest.hap b/test/resource/ams/ams_page_ability_bundle/amsConfigurationUpdatedSingletonTest.hap new file mode 100755 index 0000000000000000000000000000000000000000..9ffb062af200d3c8163a8e0d4f99fb438af88c18 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsConfigurationUpdatedSingletonTest.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsConfigurationUpdatedTest.hap b/test/resource/ams/ams_page_ability_bundle/amsConfigurationUpdatedTest.hap new file mode 100755 index 0000000000000000000000000000000000000000..8fff7b58979f897306a04e4a61bb4ea178bc00d9 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsConfigurationUpdatedTest.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManager.hap b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManager.hap new file mode 100644 index 0000000000000000000000000000000000000000..0bf8de2ea0ff39d268aa9304a7da9a157fd59ee3 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManager.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManagerFirst.hap b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManagerFirst.hap new file mode 100644 index 0000000000000000000000000000000000000000..3b8a1f456ed17018aafe1f200d9a12d0caf12687 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManagerFirst.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsKitSystemTest.hap b/test/resource/ams/ams_page_ability_bundle/amsKitSystemTest.hap new file mode 100644 index 0000000000000000000000000000000000000000..6b54f28348ddb64cf1ad6bb8acdf7f3ba3a0fc49 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsKitSystemTest.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsKitSystemTestPageA.hap b/test/resource/ams/ams_page_ability_bundle/amsKitSystemTestPageA.hap new file mode 100644 index 0000000000000000000000000000000000000000..5df1c50acdee1458d2d883130a8f14c84ac33c30 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsKitSystemTestPageA.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsKitSystemTestService.hap b/test/resource/ams/ams_page_ability_bundle/amsKitSystemTestService.hap new file mode 100644 index 0000000000000000000000000000000000000000..26509bdf3c0ea6fe538d5a37f5bebba32b28fe47 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsKitSystemTestService.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsMissionStackTest.hap b/test/resource/ams/ams_page_ability_bundle/amsMissionStackTest.hap new file mode 100644 index 0000000000000000000000000000000000000000..956ebdc636e7a70bcf4c310cae8328bfbc7884ac Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsMissionStackTest.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsMissionStackTestSubsidiary.hap b/test/resource/ams/ams_page_ability_bundle/amsMissionStackTestSubsidiary.hap new file mode 100644 index 0000000000000000000000000000000000000000..fdd0af4b505edb1ed7e31b9dfd0e9cb857586235 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsMissionStackTestSubsidiary.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestA.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestA.hap new file mode 100644 index 0000000000000000000000000000000000000000..41b137b2d7038c080edb9f22447caf02f4c59cd2 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestA.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestB.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestB.hap new file mode 100644 index 0000000000000000000000000000000000000000..35bfd2a485091fbc7527f9079134250eec5e2327 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestB.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestC.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestC.hap new file mode 100644 index 0000000000000000000000000000000000000000..c7ed748028050b11402c81c1c30bb1574eddc9d6 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestC.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestD.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestD.hap new file mode 100644 index 0000000000000000000000000000000000000000..fe4e4aed2c0ce674aa6744fe60463c139698a37d Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestD.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestDFX.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestDFX.hap new file mode 100644 index 0000000000000000000000000000000000000000..2f5bdb61fee80cb122fe7d257735791729d0e59f Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestDFX.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestE.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestE.hap new file mode 100644 index 0000000000000000000000000000000000000000..31fbba14433b9bf0e784564ed8c08dfae538f53e Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestE.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestErrorK.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestErrorK.hap new file mode 100644 index 0000000000000000000000000000000000000000..f30d8b118293b580df1bb82659cfb1c09604a80b Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestErrorK.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestErrorL.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestErrorL.hap new file mode 100644 index 0000000000000000000000000000000000000000..5dd2d4aa9e1a40f2f775f4ba4c7611c2b4cce470 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestErrorL.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestF.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestF.hap new file mode 100644 index 0000000000000000000000000000000000000000..77ebdb3b73811725cd1930845a1a45d0576ecc3e Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestF.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestG.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestG.hap new file mode 100644 index 0000000000000000000000000000000000000000..8431b22338612edbcde0da020ca55b24c30e4cc5 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestG.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestH.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestH.hap new file mode 100644 index 0000000000000000000000000000000000000000..5d07a6821b34977ae4377a64a4898dc3a892b6f6 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestH.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestI.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestI.hap new file mode 100644 index 0000000000000000000000000000000000000000..06ab1bee119f528db495fbf21417c97b72d6efc3 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestI.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestM.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestM.hap new file mode 100644 index 0000000000000000000000000000000000000000..90c39ca539f2197982b10ec02a51b59151545f42 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestM.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestN.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestN.hap new file mode 100644 index 0000000000000000000000000000000000000000..99998bd52dba5c9ac094c6cdc86bba5d5e8e350a Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestN.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestO.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestO.hap new file mode 100644 index 0000000000000000000000000000000000000000..92e9588baf0de32a3f3655ca82fb2e41a4b2de16 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestO.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestP.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestP.hap new file mode 100644 index 0000000000000000000000000000000000000000..9bb6a9a40a8fd9a6f1e13daab658fe8f4f3c6751 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestP.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestQ.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestQ.hap new file mode 100644 index 0000000000000000000000000000000000000000..c8a3943c064934527b155f2dac786e3c242602a5 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestQ.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestR.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestR.hap new file mode 100644 index 0000000000000000000000000000000000000000..3235f0eab3ae3881aeb04c93775832382b71b890 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestR.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceA.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceA.hap new file mode 100644 index 0000000000000000000000000000000000000000..cf939a7dc42e0cb97e1a0c07df3a84175986b849 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceA.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceB.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceB.hap new file mode 100644 index 0000000000000000000000000000000000000000..f6923321ef853cc808001334f34f36b025973f28 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceB.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceC.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceC.hap new file mode 100644 index 0000000000000000000000000000000000000000..a858ec8c5b086cb1975f2403c5b2cef353138070 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceC.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceD.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceD.hap new file mode 100644 index 0000000000000000000000000000000000000000..abf21e53e3d4a92ff09804cc34177e58210b316f Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceD.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceE.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceE.hap new file mode 100644 index 0000000000000000000000000000000000000000..5e7f1dfa2e281abfa6e882a20d2c435b5e7b9a74 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceE.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceF.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceF.hap new file mode 100644 index 0000000000000000000000000000000000000000..d31657d96434646676c31082bbf0278c4a4c8e9e Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceF.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceG.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceG.hap new file mode 100644 index 0000000000000000000000000000000000000000..85df366ba2f761e69cc10e156f56b0ba48c9ad44 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceG.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceH.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceH.hap new file mode 100644 index 0000000000000000000000000000000000000000..2fb65d9db5ad678ca8a473c40fa95584717e4b73 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestServiceH.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/fwkAbilityState.hap b/test/resource/ams/ams_page_ability_bundle/fwkAbilityState.hap new file mode 100755 index 0000000000000000000000000000000000000000..65fce9502459e7d7b6205ad44769d9a1a3de82bb Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/fwkAbilityState.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/taskDispatcherTestA.hap b/test/resource/ams/ams_page_ability_bundle/taskDispatcherTestA.hap new file mode 100644 index 0000000000000000000000000000000000000000..56736ad0b06319ad6ef2fcdcd3659f72b2833b0d Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/taskDispatcherTestA.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/taskDispatcherTestB.hap b/test/resource/ams/ams_page_ability_bundle/taskDispatcherTestB.hap new file mode 100644 index 0000000000000000000000000000000000000000..c8c4ad08be60d6cb0a0ca337aa57bb0ae8abcdf0 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/taskDispatcherTestB.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsKitSystemTest.hap b/test/resource/ams/ams_page_ability_bunle/amsKitSystemTest.hap new file mode 100644 index 0000000000000000000000000000000000000000..6b54f28348ddb64cf1ad6bb8acdf7f3ba3a0fc49 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsKitSystemTest.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestA.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestA.hap new file mode 100644 index 0000000000000000000000000000000000000000..5e118fb7dfcfa6fd33879dd87cf664c182b9568b Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestA.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestB.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestB.hap new file mode 100644 index 0000000000000000000000000000000000000000..1cdbb79ce3e6612c1a6c904266ee7b15c95b4d5c Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestB.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestC.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestC.hap new file mode 100644 index 0000000000000000000000000000000000000000..991bb736f9bac65734e9c6c3b2a0b2e7929a715e Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestC.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestD.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestD.hap new file mode 100644 index 0000000000000000000000000000000000000000..df06dccb3009d7d46799a1f2256a67a25e127244 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestD.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestDFX.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestDFX.hap new file mode 100644 index 0000000000000000000000000000000000000000..70a3ed697b0a60b356b1d0e5364733102c5552a9 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestDFX.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestE.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestE.hap new file mode 100644 index 0000000000000000000000000000000000000000..07e589abb65513e1ee7d8c764f32334edcf84074 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestE.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestF.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestF.hap new file mode 100644 index 0000000000000000000000000000000000000000..3eb04e0bb454f71e34572aaa202002a8267c097f Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestF.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestG.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestG.hap new file mode 100644 index 0000000000000000000000000000000000000000..1734b8a84ff499a29c25d1bd6d7ee91dfb9de6e5 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestG.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestH.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestH.hap new file mode 100644 index 0000000000000000000000000000000000000000..d367a6f7857d924696b1c9a113d3a5b8b65c57ec Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestH.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestI.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestI.hap new file mode 100644 index 0000000000000000000000000000000000000000..f3e6f8396e24880697d6b36c4614e044b76e83fa Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestI.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestM.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestM.hap new file mode 100644 index 0000000000000000000000000000000000000000..7bec2d91a537b4ebd0dd5c34954e957d563ad6e3 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestM.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestN.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestN.hap new file mode 100644 index 0000000000000000000000000000000000000000..750a90ae192f81979536ed350681f567432fa713 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestN.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestO.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestO.hap new file mode 100644 index 0000000000000000000000000000000000000000..23b9db13e9c6edd3c4a6429ddd26e7e4b5bdb9ed Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestO.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestP.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestP.hap new file mode 100644 index 0000000000000000000000000000000000000000..09da1c78fafac6f8b65825f3816b0911772611f4 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestP.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestQ.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestQ.hap new file mode 100644 index 0000000000000000000000000000000000000000..5df75c263d3168c5f67d15fee8280291158a7f9c Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestQ.hap differ diff --git a/test/resource/ams/ams_page_ability_bunle/amsSystemTestR.hap b/test/resource/ams/ams_page_ability_bunle/amsSystemTestR.hap new file mode 100644 index 0000000000000000000000000000000000000000..7bc40a98a813427e175df9376c403be0850804c7 Binary files /dev/null and b/test/resource/ams/ams_page_ability_bunle/amsSystemTestR.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsKitSystemTestPageA.hap b/test/resource/ams/ams_service_ability_bundle/amsKitSystemTestPageA.hap new file mode 100644 index 0000000000000000000000000000000000000000..b89fdf0670eb6795fb52961b13ae2f45c0cb0a40 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsKitSystemTestPageA.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsKitSystemTestService.hap b/test/resource/ams/ams_service_ability_bundle/amsKitSystemTestService.hap new file mode 100644 index 0000000000000000000000000000000000000000..27248cf039becac6f46852187f33afe767c2736f Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsKitSystemTestService.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceA.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceA.hap new file mode 100644 index 0000000000000000000000000000000000000000..7ed1e10f96668e3b16b83c00b8bba9c0ad3cfd0a Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceA.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceB.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceB.hap new file mode 100644 index 0000000000000000000000000000000000000000..68eb61814b6554f18c408d743dca1a799e3111f0 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceB.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceC.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceC.hap new file mode 100644 index 0000000000000000000000000000000000000000..eab91c381011718f809bc5313521f7502b9b1461 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceC.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceD.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceD.hap new file mode 100644 index 0000000000000000000000000000000000000000..416a52e6256664f8b5e62da083900f60e2ee1793 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceD.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceE.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceE.hap new file mode 100644 index 0000000000000000000000000000000000000000..4dc37d997469ae7bfdc99251911ea3153185bfb9 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceE.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceF.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceF.hap new file mode 100644 index 0000000000000000000000000000000000000000..4096baccdf47295dfa2d82da5398e76213d33a72 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceF.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceG.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceG.hap new file mode 100644 index 0000000000000000000000000000000000000000..f69488b346a464295916a96e2a31d51c60239b26 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceG.hap differ diff --git a/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceH.hap b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceH.hap new file mode 100644 index 0000000000000000000000000000000000000000..140415bd85f98baa333872b459f94b407137be20 Binary files /dev/null and b/test/resource/ams/ams_service_ability_bundle/amsSystemTestServiceH.hap differ diff --git a/test/resource/ams/ohos_test.xml b/test/resource/ams/ohos_test.xml new file mode 100644 index 0000000000000000000000000000000000000000..0b7c3c5cfa65526c656bc9eb99d2753576a122c8 --- /dev/null +++ b/test/resource/ams/ohos_test.xml @@ -0,0 +1,204 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/resource/ams/task_dispatcher_test/taskDispatcherTestA.hap b/test/resource/ams/task_dispatcher_test/taskDispatcherTestA.hap new file mode 100644 index 0000000000000000000000000000000000000000..21ef8b8aafd4377602e82345964c2e33b4a4ea74 Binary files /dev/null and b/test/resource/ams/task_dispatcher_test/taskDispatcherTestA.hap differ diff --git a/test/resource/ams/task_dispatcher_test/taskDispatcherTestB.hap b/test/resource/ams/task_dispatcher_test/taskDispatcherTestB.hap new file mode 100644 index 0000000000000000000000000000000000000000..fae2e9cce4935058176b3575ebe55b668928f8bf Binary files /dev/null and b/test/resource/ams/task_dispatcher_test/taskDispatcherTestB.hap differ diff --git a/test/resource/amssystemtestability/abilitySrc/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..149d3a04e453ed467a7ea4b1d6d19f51c40a904e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. + +group("ams_system_test_app") { + deps = [ + "amsAbilityAppendTestA:amsAbilityAppendTestA", + "amsAbilityAppendTestB:amsAbilityAppendTestB", + "amsAbilityVisibleTestPageA:amsAbilityVisibleTestPageA", + "amsAbilityVisibleTestServiceB:amsAbilityVisibleTestServiceB", + "amsConfigurationUpdatedSingletonTest:amsConfigurationUpdatedSingletonTest", + "amsConfigurationUpdatedTest:amsConfigurationUpdatedTest", + "amsDataSystemTestA:amsDataSystemTestA", + "amsDataSystemTestB:amsDataSystemTestB", + "amsDataSystemTestC:amsDataSystemTestC", + "amsKitSTAbilityManager:amsKitSTAbilityManager", + "amsKitSTAbilityManagerFirst:amsKitSTAbilityManagerFirst", + "amsKitSystemTest:amsKitSystemTest", + "amsKitSystemTestA:amsKitSystemTestA", + "amsKitSystemTestB:amsKitSystemTestB", + "amsKitSystemTestDataA:amsKitSystemTestDataA", + "amsKitSystemTestDataB:amsKitSystemTestDataB", + "amsKitSystemTestPageA:amsKitSystemTestPageA", + "amsKitSystemTestService:amsKitSystemTestService", + "amsMissionStackTest:amsMissionStackTest", + "amsMissionStackTestSubsidiary:amsMissionStackTestSubsidiary", + "amsStDataAbility:amsStDataAbility", + "amsSystemTestA:amsSystemTestA", + "amsSystemTestB:amsSystemTestB", + "amsSystemTestC:amsSystemTestC", + "amsSystemTestD:amsSystemTestD", + "amsSystemTestDFX:amsSystemTestDFX", + "amsSystemTestE:amsSystemTestE", + "amsSystemTestErrorK:amsSystemTestErrorK", + "amsSystemTestErrorL:amsSystemTestErrorL", + "amsSystemTestF:amsSystemTestF", + "amsSystemTestG:amsSystemTestG", + "amsSystemTestH:amsSystemTestH", + "amsSystemTestI:amsSystemTestI", + "amsSystemTestM:amsSystemTestM", + "amsSystemTestN:amsSystemTestN", + "amsSystemTestO:amsSystemTestO", + "amsSystemTestP:amsSystemTestP", + "amsSystemTestQ:amsSystemTestQ", + "amsSystemTestR:amsSystemTestR", + "amsSystemTestServiceA:amsSystemTestServiceA", + "amsSystemTestServiceB:amsSystemTestServiceB", + "amsSystemTestServiceC:amsSystemTestServiceC", + "amsSystemTestServiceD:amsSystemTestServiceD", + "amsSystemTestServiceE:amsSystemTestServiceE", + "amsSystemTestServiceF:amsSystemTestServiceF", + "amsSystemTestServiceG:amsSystemTestServiceG", + "amsSystemTestServiceH:amsSystemTestServiceH", + "fwkAbilityState:fwkAbilityState", + "serviceAbilityA:serviceAbilityA", + "taskDispatcherTestA:taskDispatcherTestA", + "taskDispatcherTestB:taskDispatcherTestB", + + # "launcherAbility:launcher_ability_native", + ] +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..a2a784790d0f17aa08a92ce05d069312e156b7c0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsAbilityAppendTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsAbilityAppendTestA\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsAbilityAppendTestA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + ] + configs = [ ":amsAbilityAppendTestAConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/config.json b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c1db086c95c8892177bbd95ff11766956f1827b0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/config.json @@ -0,0 +1,53 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppAppendA", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.AppAppendA.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Second Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..fcbe2e0786af1dc0e02fe931e9f03b3027d7bc15 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void OnSetCallerCase1(int code); + void TerminateAndRemoveMissonCase1(int code); + void TerminateAbilityResultCase1(int code); + void GetDispalyOrientationCase1(int code); + void GetPreferencesDirCase1(int code); + void StartAbilitiesCase1(int code); + void GetColorModeCase1(int code); + void SetColorModeCase1(int code); + void IsFirstInMissionCase1(int code); + + MainAbility() + { + mapCase_ = { + {(int)AppendApi::OnSetCaller, + { + [this](int code) { OnSetCallerCase1(code); }, + }}, + {(int)AppendApi::TerminateAndRemoveMisson, + { + [this](int code) { TerminateAndRemoveMissonCase1(code); }, + }}, + {(int)AppendApi::TerminateAbilityResult, + { + [this](int code) { TerminateAbilityResultCase1(code); }, + }}, + {(int)AppendApi::GetDispalyOrientation, + { + [this](int code) { GetDispalyOrientationCase1(code); }, + }}, + {(int)AppendApi::GetPreferencesDir, + { + [this](int code) { GetPreferencesDirCase1(code); }, + }}, + {(int)AppendApi::StartAbilities, + { + [this](int code) { StartAbilitiesCase1(code); }, + }}, + {(int)AppendApi::GetColorMode, + { + [this](int code) { GetColorModeCase1(code); }, + }}, + {(int)AppendApi::SetColorMode, + { + [this](int code) { SetColorModeCase1(code); }, + }}, + {(int)AppendApi::IsFirstInMission, + { + [this](int code) { IsFirstInMissionCase1(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual Uri OnSetCaller() override; + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Ability", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..f459dffbff7e34b5ee1c960eb7b334d67efdb717 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/second_ability.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + void TerminateAbilityResultCase1(int code); + + SecondAbility() + { + mapCase_ = { + {(int)AppendApi::TerminateAbilityResult, + { + [this](int code) { TerminateAbilityResultCase1(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + std::shared_ptr subscriber_; +}; +class SecondEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Ability", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~SecondEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea3ddd7cd76d3ef694d02045403240a70742e5ed --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MAIN_ABILITY_A_CODE, "onStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MAIN_ABILITY_A_CODE, "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MAIN_ABILITY_A_CODE, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MAIN_ABILITY_A_CODE, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MAIN_ABILITY_A_CODE, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MAIN_ABILITY_A_CODE, "OnForeground"); +} + +Uri MainAbility::OnSetCaller() +{ + APP_LOGI("MainAbility::OnSetCaller"); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MAIN_ABILITY_A_CODE, "OnSetCaller"); + return Ability::OnSetCaller(); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIRST, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void MainAbility::OnSetCallerCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::TerminateAndRemoveMissonCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); + TerminateAndRemoveMission(); +} + +void MainAbility::TerminateAbilityResultCase1(int code) +{ + bool result = TerminateAbilityResult(1); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::GetDispalyOrientationCase1(int code) +{ + bool result = true; + int orientation = GetDisplayOrientation(); + result = orientation == static_cast(DisplayOrientation::UNSPECIFIED); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::GetPreferencesDirCase1(int code) +{ + bool result = true; + string preferencesDir = GetPreferencesDir(); + result = !preferencesDir.empty(); + result = result && (bool)preferencesDir.find(this->GetBundleName()); + result = result && (bool)preferencesDir.find("com.ohos.amsst.AppAppendA/files/MainAbility/preferences"); + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::StartAbilitiesCase1(int code) +{ + bool result = true; + std::map params; + Want want1 = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.AppAppendA", params); + Want want2 = TestUtils::MakeWant("", "MainAbility", "com.ohos.amsst.AppAppendB", params); + std::vector wants = {want1, want2}; + AbilityContext::StartAbilities(wants); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::GetColorModeCase1(int code) +{ + int colormode = GetColorMode(); + bool result = colormode == static_cast(ModuleColorMode::AUTO); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::SetColorModeCase1(int code) +{ + SetColorMode((int)ModuleColorMode::DARK); + int colormode = GetColorMode(); + bool result = colormode == static_cast(ModuleColorMode::DARK); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::IsFirstInMissionCase1(int code) +{ + bool result = IsFirstInMission(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe9672953a61ce1e390c2f9282df22bbbbd2a829 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "onStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnStop"); +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnActive"); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnForeground"); +} + +void SecondAbility::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityA1::OnCommand"); + + Ability::OnCommand(want, restart, startId); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnActive"); +} + +sptr SecondAbility::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnConnect"); + + sptr ret = Ability::OnConnect(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnActive"); + return ret; +} +void SecondAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnDisconnect"); + + Ability::OnDisconnect(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_A_CODE, "OnDisconnect"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::TerminateAbilityResultCase1(int code) +{ + bool result = TerminateAbilityResult(1); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..0d9c6c48351c9c772ff8bbb3dd9960b048f06312 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsAbilityAppendTestBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsAbilityAppendTestB\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsAbilityAppendTestB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + ] + configs = [ ":amsAbilityAppendTestBConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/config.json b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7cd59f68a620655e30f64b43364f6eb72bc6715a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/config.json @@ -0,0 +1,43 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppAppendB", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.AppAppendB.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..7435e87ef3697deabad105b543479ac06584e68b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/include/main_ability.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_APPEND_TEST_B_MAIN_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_B_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + MainAbility() + { + mapCase_ = {}; + } + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + ~MainAbility(); + std::unordered_map>> mapCase_; + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Ability", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_B_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3f873ca15ace697bd64fd032ccc0e683819b5c0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MAIN_ABILITY_B_CODE, "onStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MAIN_ABILITY_B_CODE, "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MAIN_ABILITY_B_CODE, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MAIN_ABILITY_B_CODE, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MAIN_ABILITY_B_CODE, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MAIN_ABILITY_B_CODE, "OnForeground"); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIRSTB, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRSTB.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4223d110212f9225ea6390aa1f0f340c98d3fa2c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsAbilityVisibleTestPageAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsAbilityVisibleTestPageA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsAbilityVisibleTestPageA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea3.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea4.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsAbilityVisibleTestPageAConfig" ] + deps = [ + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/config.json b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..1f0cae84de7a6e746015c30127363e79891620d9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/config.json @@ -0,0 +1,70 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appAbilityVisiblePageA", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestR.src", + "name":"AmsSystemTestR", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsAbilityVisibleTestPageA1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestPageA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestPageA2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestPageA2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsAbilityVisibleTestPageA3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestPageA3 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestPageA4", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestPageA4 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page" + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea1.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea1.h new file mode 100644 index 0000000000000000000000000000000000000000..b80ae5f178ecd9b19c554ef76dda65543110093e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea1.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBLE_TEST_PAGE_A1 +#define AMS_ABILITY_VISIBLE_TEST_PAGE_A1 +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageA1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBLE_TEST_PAGE_A1 \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h new file mode 100644 index 0000000000000000000000000000000000000000..488d0ff67d07e528eeecb412eba09dc2e00c95ce --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBLE_TEST_PAGE_A2 +#define AMS_ABILITY_VISIBLE_TEST_PAGE_A2 +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" +#include "want_agent_helper.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; +using namespace OHOS::Notification::WantAgent; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class PendingWantCallback : public CompletedCallback { +private: + /* data */ +public: + PendingWantCallback() = default; + ~PendingWantCallback() = default; + + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override + { + STPageAbilityEvent::PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_triggerWantAgentState); + } +}; + +class AmsAbilityVisibleTestPageA2 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void GetAndTriggerWantAgent(std::string type, Want want, WantAgentConstant::OperationType operationType); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBLE_TEST_PAGE_A2 \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea3.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea3.h new file mode 100644 index 0000000000000000000000000000000000000000..adb17b5f672ace7359cd87843acc2dd7810290b5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea3.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBLE_TEST_PAGE_A3 +#define AMS_ABILITY_VISIBLE_TEST_PAGE_A3 +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageA3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBLE_TEST_PAGE_A3 \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea4.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea4.h new file mode 100644 index 0000000000000000000000000000000000000000..2b88f5aaf5c16663745b563921ecbd59b6ff412c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea4.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBLE_TEST_PAGE_A4 +#define AMS_ABILITY_VISIBLE_TEST_PAGE_A4 +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageA4 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBLE_TEST_PAGE_A4 \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c0e041b426fa9634a1ee7baf65b51dd4302e683 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestpagea1.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::NativeRdb; +void AmsAbilityVisibleTestPageA1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::Init"); + Ability::Init(abilityInfo, application, handler, token); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); +} + +void AmsAbilityVisibleTestPageA1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageA1::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want, 1); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA1::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a3ac9fbffa296da579d36a75482e6637414fdf6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestpagea2.h" +#include "context/context.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageA2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::Init"); + Ability::Init(abilityInfo, application, handler, token); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); +} + +void AmsAbilityVisibleTestPageA2::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageA2::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + if (startAbilityType == "TriggerWantAgentPageAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_ABILITY); + } + if (startAbilityType == "TriggerWantAgentServiceAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_SERVICE); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA2::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA2::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void AmsAbilityVisibleTestPageA2::GetAndTriggerWantAgent( + std::string type, Want want, WantAgentConstant::OperationType operationType) +{ + std::vector> vec; + std::shared_ptr wantParameter = std::make_shared(want); + vec.push_back(wantParameter); + WantAgentInfo info(0, operationType, WantAgentConstant::Flags::UPDATE_PRESENT_FLAG, vec, nullptr); + APP_LOGI("AmsAbilityVisibleTestPageA2::StartOtherAbility()"); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + std::shared_ptr agent = WantAgentHelper::GetWantAgent(context, info); + if (agent == nullptr) { + pageAbilityEvent.PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_getWantAgentState); + APP_LOGI("AmsAbilityVisibleTestPageA2::StartOtherAbility():GetWantAgent is nullptr."); + return; + } + TriggerInfo paramsInfo; + std::shared_ptr callback = std::make_shared(); + WantAgentHelper::TriggerWantAgent(agent, callback, paramsInfo); + APP_LOGI("AmsAbilityVisibleTestPageA2::StartOtherAbility():WantAgentHelper::TriggerWantAgent end."); +} + +REGISTER_AA(AmsAbilityVisibleTestPageA2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..779118fd81402325ea2cf1d97908435f9bbbd7dc --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestpagea3.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageA3::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageA3::onStart"); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA3::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA3::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageA3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed29b774552e4e8948afaa2908472321481c3bbb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestpagea4.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageA4::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsAbilityVisibleTestPageA4::onStart"); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA4::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA4::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageA4); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..93d3c6355624ac1dc241c2f2307863625f02521f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsAbilityVisibleTestServiceBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsAbilityVisibleTestServiceB\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsAbilityVisibleTestServiceB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestdata.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpageb1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpageb2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestservice.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestservicea1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsAbilityVisibleTestServiceBConfig" ] + deps = [ + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/config.json b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..97e89f8659da7e09c478b89c412fe65f3fb0d98c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/config.json @@ -0,0 +1,82 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appAbilityVisibleServiceB", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestR.src", + "name":"AmsSystemTestR", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsAbilityVisibleTestPageB1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestPageB1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestPageB2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestPageB2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsAbilityVisibleTestData", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestData Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "data", + "visible": false, + "uri":"dataability://com.ohos.amsst.appAbilityVisibleServiceB.AmsAbilityVisibleTestData" + }, + { + "name": "AmsAbilityVisibleTestService", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestService Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestServiceA1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsAbilityVisibleTestServiceA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": false + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestdata.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestdata.h new file mode 100644 index 0000000000000000000000000000000000000000..7b41ade64f7cec4b18c5d51560801678e4479259 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestdata.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBALE_TEST_DATA +#define AMS_ABILITY_VISIBALE_TEST_DATA +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsAbilityVisibleTestData : public Ability { +public: + ~AmsAbilityVisibleTestData(); + +protected: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query(const Uri &uri, + const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBALE_TEST_DATA \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb1.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb1.h new file mode 100644 index 0000000000000000000000000000000000000000..6bf338ec017b8e52b89f253388efc7fdc51ae66c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb1.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBLE_TEST_PAGE_B1 +#define AMS_ABILITY_VISIBLE_TEST_PAGE_B1 +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageB1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBLE_TEST_PAGE_B1 \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h new file mode 100644 index 0000000000000000000000000000000000000000..f22426fc5f3c1ebc16bd2957006b4624d37177f9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBLE_TEST_PAGE_B2 +#define AMS_ABILITY_VISIBLE_TEST_PAGE_B2 +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "completed_callback.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" +#include "want_agent_helper.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; +using CompletedCallback = OHOS::Notification::WantAgent::CompletedCallback; +using namespace OHOS::Notification::WantAgent; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class PendingWantCallback : public CompletedCallback { +private: + /* data */ +public: + PendingWantCallback() = default; + ~PendingWantCallback() = default; + + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override + { + STPageAbilityEvent::PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_triggerWantAgentState); + } +}; + +class AmsAbilityVisibleTestPageB2 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void GetAndTriggerWantAgent(std::string type, Want want, WantAgentConstant::OperationType operationType); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBLE_TEST_PAGE_B2 \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservice.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservice.h new file mode 100644 index 0000000000000000000000000000000000000000..e58eaf7002b837c7bf766dc7cd168d79f863520c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservice.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBALE_TEST_SERVICE +#define AMS_ABILITY_VISIBALE_TEST_SERVICE +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestService : public Ability { +public: + ~AmsAbilityVisibleTestService(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBALE_TEST_SERVICE \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservicea1.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservicea1.h new file mode 100644 index 0000000000000000000000000000000000000000..1d0f1ed417474bc8a99cfb9a4c75af329599decd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservicea1.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_VISIBALE_TEST_SERVICE_A1 +#define AMS_ABILITY_VISIBALE_TEST_SERVICE_A1 +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestServiceA1 : public Ability { +public: + ~AmsAbilityVisibleTestServiceA1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_VISIBALE_TEST_SERVICE_A1 \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestdata.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestdata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbc9174abc7f80bcf4c7b27d922ca126b54bb640 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestdata.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestdata.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +const static int defenvntCode = 1; + +AmsAbilityVisibleTestData::~AmsAbilityVisibleTestData() +{} + +void AmsAbilityVisibleTestData::OnStart(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestData::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +int AmsAbilityVisibleTestData::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsAbilityVisibleTestData::Insert"); + int result = Ability::Insert(uri, value); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInsert; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +int AmsAbilityVisibleTestData::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsAbilityVisibleTestData::Delete"); + int result = Ability::Delete(uri, predicates); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateDelete; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +int AmsAbilityVisibleTestData::Update( + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsAbilityVisibleTestData::Update"); + int result = Ability::Update(uri, value, predicates); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateUpdate; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +std::shared_ptr AmsAbilityVisibleTestData::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsAbilityVisibleTestData::Query"); + std::shared_ptr result = Ability::Query(uri, columns, predicates); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateQuery; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +std::vector AmsAbilityVisibleTestData::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsAbilityVisibleTestData::GetFileTypes"); + std::vector result = Ability::GetFileTypes(uri, mimeTypeFilter); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateGetFileTypes; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +int AmsAbilityVisibleTestData::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsAbilityVisibleTestData::OpenFile"); + int result = Ability::OpenFile(uri, mode); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOpenFile; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestData); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..acb02c342a123d2bc39ff61222a256a163f013f0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestpageb1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageB1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::Init"); + Ability::Init(abilityInfo, application, handler, token); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); +} + +void AmsAbilityVisibleTestPageB1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageB1::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageB1::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageB1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageB1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..10dd093e963c5e0a871be76a92ea96ffe6664f28 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestpageb2.h" +#include "context/context.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageB2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::Init"); + Ability::Init(abilityInfo, application, handler, token); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); +} + +void AmsAbilityVisibleTestPageB2::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageB2::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnActive"); + Ability::OnActive(); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data" || startAbilityType == "DataRelease") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + if (startAbilityType == "DataRelease") { + helper->Release(); + } + } + if (startAbilityType == "TriggerWantAgentPageAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_ABILITY); + } + if (startAbilityType == "TriggerWantAgentServiceAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_SERVICE); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageB2::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageB2::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void AmsAbilityVisibleTestPageB2::GetAndTriggerWantAgent( + std::string type, Want want, WantAgentConstant::OperationType operationType) +{ + std::vector> vec; + std::shared_ptr wantParameter = std::make_shared(want); + vec.push_back(wantParameter); + WantAgentInfo info(0, operationType, WantAgentConstant::Flags::UPDATE_PRESENT_FLAG, vec, nullptr); + APP_LOGI("AmsAbilityVisibleTestPageB2::StartOtherAbility()"); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + std::shared_ptr agent = WantAgentHelper::GetWantAgent(context, info); + if (agent == nullptr) { + pageAbilityEvent.PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_getWantAgentState); + APP_LOGI("AmsAbilityVisibleTestPageB2::StartOtherAbility():GetWantAgent is nullptr."); + return; + } + TriggerInfo paramsInfo; + std::shared_ptr callback = std::make_shared(); + WantAgentHelper::TriggerWantAgent(agent, callback, paramsInfo); + APP_LOGI("AmsAbilityVisibleTestPageB2::StartOtherAbility():WantAgentHelper::TriggerWantAgent end."); +} + +REGISTER_AA(AmsAbilityVisibleTestPageB2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14d341e787950f896423bcb6b3a677a118a204b1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestservice.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +AmsAbilityVisibleTestService::~AmsAbilityVisibleTestService() +{} + +void AmsAbilityVisibleTestService::OnStart(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnCommand"); + + Ability::OnCommand(want, restart, startId); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnNewWant"); + + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnStop"); + + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnActive"); + + Ability::OnActive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnInactive"); + + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnBackground"); + + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +sptr AmsAbilityVisibleTestService::OnConnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnConnect"); + + sptr ret = Ability::OnConnect(want); + GetWantInfo(want); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want wantOther; + wantOther.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + wantOther.SetParam("targetBundle", targetBundle_); + wantOther.SetParam("targetAbility", targetAbility_); + wantOther.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(wantOther); + } + if (startAbilityType == "Service") { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + ConnectAbility(wantOther, stub); + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnConnectCount(), eventData); + return ret; +} + +void AmsAbilityVisibleTestService::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnDisconnect"); + + Ability::OnDisconnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnDisconnectCount(), eventData); +} + +void AmsAbilityVisibleTestService::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestService::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestService::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestService); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bbf48e9647907f68f9bfe1d17c630a6c42f610f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsabilityvisibletestservicea1.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +AmsAbilityVisibleTestServiceA1::~AmsAbilityVisibleTestServiceA1() +{} + +void AmsAbilityVisibleTestServiceA1::OnStart(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnCommand"); + + Ability::OnCommand(want, restart, startId); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnNewWant"); + + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnStop"); + + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnActive"); + + Ability::OnActive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnInactive"); + + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnBackground"); + + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +sptr AmsAbilityVisibleTestServiceA1::OnConnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnConnect"); + + sptr ret = Ability::OnConnect(want); + GetWantInfo(want); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want wantOther; + wantOther.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + wantOther.SetParam("targetBundle", targetBundle_); + wantOther.SetParam("targetAbility", targetAbility_); + wantOther.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(wantOther); + } + if (startAbilityType == "Service") { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + ConnectAbility(wantOther, stub); + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + NativeRdb::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnConnectCount(), eventData); + return ret; +} + +void AmsAbilityVisibleTestServiceA1::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnDisconnect"); + + Ability::OnDisconnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnDisconnectCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestServiceA1::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestServiceA1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestServiceA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..7165180427b44ee15da3bf29686623a6f3e3abcd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsConfigurationUpdatedSingletonTestConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsConfigurationUpdatedSingletonTest\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsConfigurationUpdatedSingletonTest") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + ] + configs = [ ":amsConfigurationUpdatedSingletonTestConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/config.json b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/config.json new file mode 100755 index 0000000000000000000000000000000000000000..b09c9e71c657b926479e6f1b9658f92e33e2090e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/config.json @@ -0,0 +1,44 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.ConfigurationUpdatedSingleton", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.ConfigurationUpdatedSingleton.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "MainAbility label", + "launchType": "singleton", + "configChanges": ["orientation"], + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/include/main_ability.h new file mode 100755 index 0000000000000000000000000000000000000000..673733b01124d62ace4e3a64d760b034741ef91a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/include/main_ability.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class MainAbilityEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + MainAbility() + { + mapCase_ = {}; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + std::string callbackSeq; + std::string callbackUpdated; +}; +class MainAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit MainAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = {}; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~MainAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/include/test_utils.h new file mode 100755 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/src/main_ability.cpp new file mode 100755 index 0000000000000000000000000000000000000000..794b3ce180d8deaf9ded3d599168621b82352621 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/src/main_ability.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, "OnStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; // OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; // OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + std::string languageValue; + std::string orientationValue; + + APP_LOGI("MainAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + languageValue = configuration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE); + orientationValue = configuration.GetItem(GlobalConfigurationKey::SYSTEM_ORIENTATION); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, languageValue); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, orientationValue); + callbackUpdated += "Updated"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, callbackUpdated); + callbackUpdated = ""; +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, THIRD_ABILITY_CODE, "OnForeground"); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_MAIN, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void MainAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/src/test_utils.cpp new file mode 100755 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedSingletonTest/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..caf004688a2c0f030208d02e2f8676b5269c1ae2 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsConfigurationUpdatedTestConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsConfigurationUpdatedTest\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsConfigurationUpdatedTest") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + ] + configs = [ ":amsConfigurationUpdatedTestConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/config.json b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/config.json new file mode 100755 index 0000000000000000000000000000000000000000..5dd4a6c641ae55614eacee0b7a22dbd19aefd1e5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/config.json @@ -0,0 +1,57 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.ConfigurationUpdated", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.ConfigurationUpdated.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "MainAbility label", + "launchType": "standard", + "configChanges": ["orientation"], + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "SecondAbility label", + "launchType": "standard", + "configChanges": ["orientation"], + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/main_ability.h new file mode 100755 index 0000000000000000000000000000000000000000..bcbf0cf2800136d01e84a32a8c940f0e899cde9d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/main_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class MainAbilityEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void StartNext(std::string action, int code); + void StartNextWithBlock(std::string action, int code); + void OnBlockProcess(bool &bIsBlockFlag); + + MainAbility() + { + mapCase_ = {}; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + std::string callbackSeq; + std::string callbackUpdated; + bool bIsBlockUpdate; +}; +class MainAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit MainAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"StartNextAbility", + [this](std::string action, int code) { StartNext(action, code); }}, + {"StartNextAbilityWithBlockFlag", + [this](std::string action, int code) { StartNextWithBlock(action, code); }}, + }; + mainAbility = nullptr; + } + + void StartNext(std::string action, int code) + { + mainAbility->StartNext(action, code); + } + + void StartNextWithBlock(std::string action, int code) + { + mainAbility->StartNextWithBlock(action, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~MainAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/second_ability.h new file mode 100755 index 0000000000000000000000000000000000000000..2116a0494cfbf0938c8525ec5baab5efa0ed97ac --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/second_ability.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_CONFIGURATION_UPDATED_TEST_SECOND_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondAbilityEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + SecondAbility() + { + mapCase_ = {}; + } + + std::unordered_map>> mapCase_; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + std::string callbackSeq; + std::string callbackUpdated; +}; +class SecondAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = {}; + secondAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + secondAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *secondAbility; + std::unordered_map> mapTestFunc_; + ~SecondAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/test_utils.h new file mode 100755 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/main_ability.cpp new file mode 100755 index 0000000000000000000000000000000000000000..6d2e68bd0401e6390fdfdaaef404fe484900d0e1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/main_ability.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +constexpr int iBlockTime = 5; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + bIsBlockUpdate = false; + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; // OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; // OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnBlockProcess(bool &bIsBlockFlag) +{ + int i = iBlockTime; + + if (bIsBlockFlag) { + while (i-- > 0) { + APP_LOGI("MainAbility::OnBlockProcess time left %{public}d", i); + sleep(1); + } + bIsBlockFlag = false; + } +} + +void MainAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + std::string languageValue; + std::string orientationValue; + + APP_LOGI("MainAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + OnBlockProcess(bIsBlockUpdate); + languageValue = configuration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE); + orientationValue = configuration.GetItem(GlobalConfigurationKey::SYSTEM_ORIENTATION); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, languageValue); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, orientationValue); + callbackUpdated += "Updated"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, callbackUpdated); + callbackUpdated = ""; +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnForeground"); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_MAIN, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void MainAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (strcmp(eventName.c_str(), g_EVENT_REQU_MAIN.c_str()) == 0) { + auto target = data.GetData(); + if (mapTestFunc_.find(target) != mapTestFunc_.end()) { + mapTestFunc_[target](target, data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::StartNext(std::string action, int code) +{ + std::string targetBundle = "com.ohos.amsst.ConfigurationUpdated"; + std::string targetAbility = "SecondAbility"; + Want want; + + APP_LOGI("MainAbility::StartNext"); + want.SetElementName(targetBundle, targetAbility); + StartAbility(want); +} + +void MainAbility::StartNextWithBlock(std::string action, int code) +{ + bIsBlockUpdate = true; + StartNext(action, code); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/second_ability.cpp new file mode 100755 index 0000000000000000000000000000000000000000..97968a0a2a78f5c58e8b0351b0623fa28a7e1190 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/second_ability.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, "OnStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; // OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; // OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + std::string languageValue; + std::string orientationValue; + + APP_LOGI("SecondAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + + languageValue = configuration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE); + orientationValue = configuration.GetItem(GlobalConfigurationKey::SYSTEM_ORIENTATION); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, languageValue); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, orientationValue); + callbackUpdated += "Updated"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, callbackUpdated); + callbackUpdated = ""; +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, SECOND_ABILITY_CODE, "OnForeground"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_MAIN, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->secondAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/test_utils.cpp new file mode 100755 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..664cf5c3136a7cedefb811ef27060106496aa60b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsDataSystemTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsDataSystemTestA\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsDataSystemTestA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/ams_st_data_ability_data_a.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_data_ability_page_a.cpp", + "${SUBST_TOOLS_DIR}/src/event.cpp", + "${SUBST_TOOLS_DIR}/src/stoperator.cpp", + ] + configs = [ ":amsDataSystemTestAConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/config.json b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b93f1bcbe6a55d8c11e16a01d49aa9ead124e8f7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/config.json @@ -0,0 +1,52 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppDataA", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.amsst.AppDataA.src", + "name":"AmsSystemTestDataA", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStDataAbilityPageA", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "PageA Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStDataAbilityDataA", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "DataA Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppDataA.AmsStDataAbilityDataA" + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h new file mode 100644 index 0000000000000000000000000000000000000000..d64782dde9b8ba54e7a6291411b9cfcad9d69f1f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_DATA_ABILITY_DATA_A_H +#define AMS_ST_DATA_ABILITY_DATA_A_H +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class DataTestDataAEventSubscriber; +class AmsStDataAbilityDataA : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + FILE *file = nullptr; + int fd = -1; + ~AmsStDataAbilityDataA(); + +protected: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class DataTestDataAEventSubscriber : public CommonEventSubscriber { +public: + DataTestDataAEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStDataAbilityDataA *ability) + : CommonEventSubscriber(sp) + { + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStDataAbilityDataA *mainAbility_; + ~DataTestDataAEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_DATA_ABILITY_DATA_A_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_page_a.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_page_a.h new file mode 100644 index 0000000000000000000000000000000000000000..1cd0cbbc7189a3c182f6eb2ccc5b3fdda8993c3d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_page_a.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_DATA_ABILITY_PAGE_A_H +#define AMS_ST_DATA_ABILITY_PAGE_A_H +#include +#include + +#include "ability.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class DataTestPageAEventSubscriber; + +class AmsStDataAbilityPageA : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + ~AmsStDataAbilityPageA(); + +private: + void GetWantInfo(const Want &want); + + Want originWant_; + std::shared_ptr subscriber_; +}; + +class AmsStDataAbilityPageALifecycleObserver : public ILifecycleObserver { +public: + AmsStDataAbilityPageALifecycleObserver() = default; + virtual ~AmsStDataAbilityPageALifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; +}; + +class DataTestPageAEventSubscriber : public CommonEventSubscriber { +public: + DataTestPageAEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStDataAbilityPageA *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"OnStart", [this]() { TestPost("OnStart"); }}, + {"OnStop", [this]() { TestPost("OnStop"); }}, + {"OnActive", [this]() { TestPost("OnActive"); }}, + {"OnInactive", [this]() { TestPost("OnInactive"); }}, + {"OnBackground", [this]() { TestPost("OnBackground"); }}, + }; + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName); + std::vector vectorOperator_; + AmsStDataAbilityPageA *mainAbility_; + std::unordered_map> mapTestFunc_; + ~DataTestPageAEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_DATA_ABILITY_PAGE_A_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5728bb8710b3d43cb0eb91af9d15e127b4e5280f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_data_ability_data_a.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" +#include "file_ex.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_A_CODE = 210; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_SERVICE = "1"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +bool AmsStDataAbilityDataA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void DataTestDataAEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("DataTestDataAEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("DataTestDataAEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("DataTestDataAEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_A_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_A_CODE); + } +} + +AmsStDataAbilityDataA::~AmsStDataAbilityDataA() +{ + if (file != nullptr) { + fclose(file); + file = nullptr; + fd = -1; + } + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataA::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataA::OnStart(const Want &want) +{ + APP_LOGI("AmsStDataAbilityDataA OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "OnStart"); +} + +int AmsStDataAbilityDataA::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStDataAbilityDataA <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "Insert"); + if (fd <= 0) { + APP_LOGI("AmsStDataAbilityDataA <<<>>> file fd <= 0"); + return DEFAULT_INSERT_RESULT; + } + int dupFd = dup(fd); + FILE *file = fdopen(dupFd, "r"); + if (file == nullptr) { + APP_LOGI("AmsStDataAbilityDataA <<<>>> file == nullptr"); + } else { + APP_LOGI("AmsStDataAbilityDataA <<<>>> file != nullptr"); + fclose(file); + file = nullptr; + } + return DEFAULT_INSERT_RESULT; +} + +int AmsStDataAbilityDataA::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataA <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStDataAbilityDataA::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataA <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStDataAbilityDataA::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStDataAbilityDataA <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_A_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + if (resultValue == nullptr) { + APP_LOGE("AmsStDataAbilityDataA <<<>>> make_shared return nullptr"); + return nullptr; + } + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock == nullptr) { + APP_LOGE("AmsStDataAbilityDataA <<<>>> GetBlock return nullptr"); + return nullptr; + } + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + return resultValue; +} + +std::vector AmsStDataAbilityDataA::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStDataAbilityDataA <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "GetFileTypes"); + std::vector fileType { + "filetypes", + }; + return fileType; +} + +int AmsStDataAbilityDataA::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStDataAbilityDataA <<<>>>"); + + if (file != nullptr) { + fclose(file); + file = nullptr; + fd = -1; + } + file = fopen("/system/vendor/test.txt", "r"); + if (file == nullptr) { + APP_LOGI("AmsStDataAbilityDataA <<<>>> fdr == nullptr"); + return -1; + } + fd = fileno(file); + APP_LOGI("AmsStDataAbilityDataA fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "OpenFile"); + return fd; +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } +} + +void DataTestDataAEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("DataTestDataAEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("---------data--------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("---------data--------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("---------data--------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("---------data--------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("---------data--------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStDataAbilityDataA); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45b30019c357a404e727d199d4b857f0bc4e7456 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_data_ability_page_a.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_PAGE_A_CODE = 110; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +constexpr int charCnt = 5; +} + +bool AmsStDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void DataTestPageAEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare("event_data_test_action") == 0 && ABILITY_PAGE_A_CODE == data.GetCode()) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +AmsStDataAbilityPageA::~AmsStDataAbilityPageA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityPageA::SubscribeEvent(const Want &want) +{ + Want mwant {want}; + std::vector eventList = { + "event_data_test_action", + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + subscriber_->vectorOperator_ = mwant.GetStringArrayParam("operator"); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityPageA::OnStart(const Want &want) +{ + APP_LOGI("AmsStDataAbilityPageA::onStart"); + originWant_ = want; + SubscribeEvent(want); + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_PAGE_A_CODE, "onStart"); +} + +void AmsStDataAbilityPageA::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStDataAbilityPageA::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); +} + +void AmsStDataAbilityPageA::OnStop() +{ + APP_LOGI("AmsStDataAbilityPageA::onStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_PAGE_A_CODE, "OnStop"); +} + +void AmsStDataAbilityPageA::OnActive() +{ + APP_LOGI("AmsStDataAbilityPageA::OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_PAGE_A_CODE, "OnActive"); +} + +void AmsStDataAbilityPageA::OnInactive() +{ + APP_LOGI("AmsStDataAbilityPageA::OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_PAGE_A_CODE, "OnInactive"); +} + +void AmsStDataAbilityPageA::OnBackground() +{ + APP_LOGI("AmsStDataAbilityPageA::OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_PAGE_A_CODE, "OnBackground"); +} + +void AmsStDataAbilityPageA::GetWantInfo(const Want &want) +{ + Want mWant(want); + STtools::StOperator allOperator {}; + std::vector vectorOperator = mWant.GetStringArrayParam("operator"); + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); + + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + APP_LOGI("---------------------------DataTestPageAEventSubscriber::fd < 0"); + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + APP_LOGI("---------------------------DataTestPageAEventSubscriber::file == nullptr"); + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } +} + +void DataTestPageAEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("DataTestPageAEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == "2") { + APP_LOGI("---------------------targetAbility_--------------targetAbility:%{public}s", + child->GetAbilityName().c_str()); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + APP_LOGI("---------------------targetAbility_--------------operatorName:%{public}s", + child->GetOperatorName().c_str()); + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_A_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == "0") { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_A_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStDataAbilityPageA); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..cdfce918f374ebebd7575e11644fff4981c69604 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsDataSystemTestBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsDataSystemTestB\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsDataSystemTestB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/ams_st_data_ability_data_b.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_data_ability_page_b.cpp", + "${SUBST_TOOLS_DIR}/src/event.cpp", + "${SUBST_TOOLS_DIR}/src/stoperator.cpp", + ] + configs = [ ":amsDataSystemTestBConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/config.json b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3b94f8634a1dd712f8d81c33e7b13757c5e305a7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/config.json @@ -0,0 +1,52 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppDataB", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.amsst.AppDataB.src", + "name":"AmsSystemTestDataB", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStDataAbilityPageB", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "PageB Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStDataAbilityDataB", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "DataB Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppDataB.AmsStDataAbilityDataB" + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_data_b.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_data_b.h new file mode 100644 index 0000000000000000000000000000000000000000..a3ef18cfd43af7177bd2d9ba6dd9ad7fd9e83df8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_data_b.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_DATA_ABILITY_DATA_B_H +#define AMS_ST_DATA_ABILITY_DATA_B_H +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class DataTestDataBEventSubscriber; +class AmsStDataAbilityDataB : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + ~AmsStDataAbilityDataB(); + +protected: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class DataTestDataBEventSubscriber : public CommonEventSubscriber { +public: + DataTestDataBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStDataAbilityDataB *ability) + : CommonEventSubscriber(sp) + { + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStDataAbilityDataB *mainAbility_; + ~DataTestDataBEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_DATA_ABILITY_DATA_B_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_page_b.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_page_b.h new file mode 100644 index 0000000000000000000000000000000000000000..fdc490b54e7c8b3401e233075f1592fcf55cbc0e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_page_b.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_DATA_ABILITY_PAGE_B_H +#define AMS_ST_DATA_ABILITY_PAGE_B_H +#include +#include + +#include "ability.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class DataTestPageBEventSubscriber; + +class AmsStDataAbilityPageB : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + ~AmsStDataAbilityPageB(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + +private: + void GetWantInfo(const Want &want); + + Want originWant_; + std::shared_ptr subscriber_; +}; + +class AmsStDataAbilityPageBLifecycleObserver : public ILifecycleObserver { +public: + AmsStDataAbilityPageBLifecycleObserver() = default; + virtual ~AmsStDataAbilityPageBLifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; +}; + +class DataTestPageBEventSubscriber : public CommonEventSubscriber { +public: + DataTestPageBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStDataAbilityPageB *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"OnStart", [this]() { TestPost("OnStart"); }}, + {"OnStop", [this]() { TestPost("OnStop"); }}, + {"OnActive", [this]() { TestPost("OnActive"); }}, + {"OnInactive", [this]() { TestPost("OnInactive"); }}, + {"OnBackground", [this]() { TestPost("OnBackground"); }}, + }; + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName); + std::vector vectorOperator_; + AmsStDataAbilityPageB *mainAbility_; + std::unordered_map> mapTestFunc_; + ~DataTestPageBEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_DATA_ABILITY_PAGE_B_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c99e80d262ed1b22fee99b02ffdf0d5a95db9caf --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_data_ability_data_b.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_B_CODE = 220; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_SERVICE = "1"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +bool AmsStDataAbilityDataB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void DataTestDataBEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("DataTestDataBEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("DataTestDataBEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("DataTestDataBEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_B_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_B_CODE); + } +} + +AmsStDataAbilityDataB::~AmsStDataAbilityDataB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataB::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataB::OnStart(const Want &want) +{ + APP_LOGI("AmsStDataAbilityDataB OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "OnStart"); +} + +int AmsStDataAbilityDataB::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "Insert"); + return DEFAULT_INSERT_RESULT; +} + +int AmsStDataAbilityDataB::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStDataAbilityDataB::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStDataAbilityDataB::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_B_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock) { + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + } + return resultValue; +} + +std::vector AmsStDataAbilityDataB::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "GetFileTypes"); + std::vector fileType {"filetypes"}; + return fileType; +} + +int AmsStDataAbilityDataB::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStDataAbilityDataB <<<>>>"); + FILE *fd1 = fopen("/system/app/test.txt", "r"); + if (fd1 == nullptr) + return -1; + int fd = fileno(fd1); + APP_LOGI("AmsStDataAbilityDataB fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "OpenFile"); + fclose(fd1); + return fd; +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } +} + +void DataTestDataBEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("DataTestDataBEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + } + } +} +REGISTER_AA(AmsStDataAbilityDataB); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd43df46c684975fe1e178bca96670f81ac65b26 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_data_ability_page_b.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_PAGE_B_CODE = 120; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +constexpr int charCnt = 5; +} + +bool AmsStDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void DataTestPageBEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("DataTestPageBEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("DataTestPageBEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("DataTestPageBEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare("event_data_test_action") == 0 && ABILITY_PAGE_B_CODE == data.GetCode()) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +AmsStDataAbilityPageB::~AmsStDataAbilityPageB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityPageB::SubscribeEvent(const Want &want) +{ + Want mwant {want}; + std::vector eventList = { + "event_data_test_action", + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + subscriber_->vectorOperator_ = mwant.GetStringArrayParam("operator"); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityPageB::OnStart(const Want &want) +{ + APP_LOGI("AmsStDataAbilityPageB::onStart"); + originWant_ = want; + SubscribeEvent(want); + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, "onStart"); +} + +void AmsStDataAbilityPageB::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStDataAbilityPageB::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); +} + +void AmsStDataAbilityPageB::OnStop() +{ + APP_LOGI("AmsStDataAbilityPageB::onStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, "OnStop"); +} + +void AmsStDataAbilityPageB::OnActive() +{ + APP_LOGI("AmsStDataAbilityPageB::OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, "OnActive"); + GetWantInfo(originWant_); + PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, "OnActive Done"); +} + +void AmsStDataAbilityPageB::OnInactive() +{ + APP_LOGI("AmsStDataAbilityPageB::OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, "OnInactive"); +} + +void AmsStDataAbilityPageB::OnBackground() +{ + APP_LOGI("AmsStDataAbilityPageB::OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, "OnBackground"); +} + +void AmsStDataAbilityPageB::GetWantInfo(const Want &want) +{ + Want mWant(want); + STtools::StOperator allOperator {}; + std::vector vectorOperator = mWant.GetStringArrayParam("operator"); + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); + + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } +} + +void DataTestPageBEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("DataTestPageBEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == "2") { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == "0") { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_B_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStDataAbilityPageB); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..37c318b7a7739e97777d8ad0da02ad0d9db608b2 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsDataSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsDataSystemTestC\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsDataSystemTestC") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/ams_st_data_ability_data_c1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_data_ability_data_c2.cpp", + "${SUBST_TOOLS_DIR}/src/event.cpp", + "${SUBST_TOOLS_DIR}/src/stoperator.cpp", + ] + configs = [ ":amsDataSystemTestCConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/config.json b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b62f442b2f4be9230d3c2f99663e6606b6d8ed4a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/config.json @@ -0,0 +1,53 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppDataC", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.amsst.AppDataC.src", + "name":"AmsSystemTestDataB", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStDataAbilityDataC1", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "PageB Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppDataC.AmsStDataAbilityDataC1" + }, + { + "name": "AmsStDataAbilityDataC2", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "DataB Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppDataC.AmsStDataAbilityDataC2" + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c1.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c1.h new file mode 100644 index 0000000000000000000000000000000000000000..243c40b2e505c9f979bbbecd7103a99a969bd992 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c1.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_DATA_ABILITY_DATA_C1_H +#define AMS_ST_DATA_ABILITY_DATA_C1_H +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class DataTestDataC1EventSubscriber; +class AmsStDataAbilityDataC1 : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + int fd; + ~AmsStDataAbilityDataC1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + friend class DataTestDataC1EventSubscriber; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class DataTestDataC1EventSubscriber : public CommonEventSubscriber { +public: + DataTestDataC1EventSubscriber(const CommonEventSubscribeInfo &sp, AmsStDataAbilityDataC1 *ability) + : CommonEventSubscriber(sp) + { + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void GetResultBySelf(std::shared_ptr child, AmsStDataAbilityDataC1 *mainAbility, + Uri dataAbilityUri, string &result); + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStDataAbilityDataC1 *mainAbility_; + ~DataTestDataC1EventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_DATA_ABILITY_DATA_C1_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c2.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c2.h new file mode 100644 index 0000000000000000000000000000000000000000..186130a4993873b97427fb47e816c5a3a48dc1a1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c2.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_DATA_ABILITY_DATA_C2_H +#define AMS_ST_DATA_ABILITY_DATA_C2_H +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class DataTestDataC2EventSubscriber; +class AmsStDataAbilityDataC2 : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + ~AmsStDataAbilityDataC2(); + +protected: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class DataTestDataC2EventSubscriber : public CommonEventSubscriber { +public: + DataTestDataC2EventSubscriber(const CommonEventSubscribeInfo &sp, AmsStDataAbilityDataC2 *ability) + : CommonEventSubscriber(sp) + { + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStDataAbilityDataC2 *mainAbility_; + ~DataTestDataC2EventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_DATA_ABILITY_DATA_C2_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f57ea3870a06dc64b07bf10a09d54c2ccc3a3d9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_data_ability_data_c1.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_C1_CODE = 230; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_SERVICE = "1"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +bool AmsStDataAbilityDataC1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void DataTestDataC1EventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("DataTestDataC1EventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("DataTestDataC1EventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("DataTestDataC1EventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_C1_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_C1_CODE); + } +} + +AmsStDataAbilityDataC1::~AmsStDataAbilityDataC1() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataC1::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataC1::OnStart(const Want &want) +{ + APP_LOGI("AmsStDataAbilityDataC1 OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OnStart"); +} + +int AmsStDataAbilityDataC1::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "Insert"); + if (fd <= 0) { + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> file fd <= 0"); + return DEFAULT_INSERT_RESULT; + } + int dupFd = dup(fd); + FILE *file = fdopen(dupFd, "r"); + if (file == nullptr) { + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> file == nullptr"); + } else { + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> file != nullptr"); + fclose(file); + file = nullptr; + } + return DEFAULT_INSERT_RESULT; +} + +int AmsStDataAbilityDataC1::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStDataAbilityDataC1::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStDataAbilityDataC1::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_C1_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock) { + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + } + return resultValue; +} + +std::vector AmsStDataAbilityDataC1::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "GetFileTypes"); + std::vector fileType {"filetypes"}; + return fileType; +} + +int AmsStDataAbilityDataC1::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); + + FILE *fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 == nullptr) { + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> fdr == nullptr"); + return -1; + } + fd = fileno(fd1); + APP_LOGI("AmsStDataAbilityDataC1 fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); + return fd; +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) + fgets(str, charCnt, file); + result = str; + fclose(file); + } +} + +void DataTestDataC1EventSubscriber::GetResultBySelf( + std::shared_ptr child, AmsStDataAbilityDataC1 *mainAbility, Uri dataAbilityUri, string &result) +{ + if (child->GetOperatorName() == OPERATOR_INSERT) { + APP_LOGI("---------------------Insert--------------------"); + NativeRdb::ValuesBucket bucket; + result = std::to_string(mainAbility->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + APP_LOGI("---------------------Delete--------------------"); + NativeRdb::DataAbilityPredicates predicates; + result = std::to_string(mainAbility->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + APP_LOGI("---------------------Update--------------------"); + NativeRdb::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + result = std::to_string(mainAbility->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + APP_LOGI("---------------------Query--------------------"); + std::vector columns = STtools::SerializationStOperatorToVector(*child); + NativeRdb::DataAbilityPredicates predicates; + std::shared_ptr resultValue = mainAbility->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + APP_LOGI("---------------------GetFileTypes--------------------"); + std::vector types = mainAbility->GetFileTypes(dataAbilityUri, child->GetMessage()); + if (types.size() > 0) { + result = types[0]; + } else { + result = "failed"; + } + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + APP_LOGI("---------------------OpenFile--------------------"); + FILE *file = fopen("/system/vendor/test.txt", "r"); + if (file == nullptr) { + return; + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); + + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } +} + +void DataTestDataC1EventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("DataTestDataC1EventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + std::string result; + /// data ability + if (child->GetAbilityType() == allOperator.GetAbilityType() && + child->GetAbilityName() == allOperator.GetAbilityName()) { + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + GetResultBySelf(child, mainAbility_, dataAbilityUri, result); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + } + } +} +REGISTER_AA(AmsStDataAbilityDataC1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1eccfa26298a75322c5b65757026486c07669811 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_data_ability_data_c2.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_C2_CODE = 240; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_SERVICE = "1"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +bool AmsStDataAbilityDataC2::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void DataTestDataC2EventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("DataTestDataC2EventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("DataTestDataC2EventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("DataTestDataC2EventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_C2_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_C2_CODE); + } +} + +AmsStDataAbilityDataC2::~AmsStDataAbilityDataC2() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataC2::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStDataAbilityDataC2::OnStart(const Want &want) +{ + APP_LOGI("AmsStDataAbilityDataC2 OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "OnStart"); +} + +int AmsStDataAbilityDataC2::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "Insert"); + return DEFAULT_INSERT_RESULT; +} + +int AmsStDataAbilityDataC2::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStDataAbilityDataC2::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStDataAbilityDataC2::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_C2_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock) { + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + } + return resultValue; +} + +std::vector AmsStDataAbilityDataC2::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "GetFileTypes"); + std::vector fileType {"filetypes"}; + return fileType; +} + +int AmsStDataAbilityDataC2::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); + FILE *fd1 = fopen("/system/app/test.txt", "r"); + if (fd1 == nullptr) + return -1; + int fd = fileno(fd1); + APP_LOGI("AmsStDataAbilityDataC2 fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "OpenFile"); + fclose(fd1); + return fd; +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } +} + +void DataTestDataC2EventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("DataTestDataC2EventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + } + } +} +REGISTER_AA(AmsStDataAbilityDataC2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8008ae0a787a659e513590533a14a75c4b8a0abb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("amsKitSTAbilityManagerConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + ] + defines = [ + "APP_LOG_TAG = \"amsKitSTAbilityManager\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsKitSTAbilityManager") { + sources = [ "src/kit_test_ability_manager_second.cpp" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":amsKitSTAbilityManagerConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d7853f23f31d0076250f525d084d3f7a4d1cbeaf --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKitAbilityManager", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.KitAbilityManager.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "KitTestAbilityManagerSecond", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Kittest Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h new file mode 100644 index 0000000000000000000000000000000000000000..f6b888f665709c0fe09fe584605dcf8cd82e9420 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _KIT_TEST_ABILITY_MANAGER_SECOND_H_ +#define _KIT_TEST_ABILITY_MANAGER_SECOND_H_ +#include +#include "ability_loader.h" +#include "running_process_info.h" +#include "ability_manager.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" + +namespace OHOS { +namespace AppExecFwk { +using vector_str = std::vector; +using vector_conststr = std::vector; +using vector_func = std::vector>; +class KitTestManagerSecondEventSubscriber; + +class KitTestAbilityManagerSecond : public Ability { +public: + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void SubscribeEvent(const vector_conststr &eventList); + void AbilityManagerStByCode(int apiIndex, int caseIndex, int code); + void CompareProcessName(std::vector &info, const std::string &expectedName, int code); + void CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code); + void ProcessStateNotEqual( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code); + void GetAllStackInfo(AAFwk::MissionStackInfo &missionStackInfo, int stackID); + + // GetAllRunningProcesses ST kit case + void AbilityManagerGetAllRunningProcessesCase1(int code); + void AbilityManagerGetAllRunningProcessesCase2(int code); + void AbilityManagerGetAllRunningProcessesCase3(int code); + void AbilityManagerGetAllRunningProcessesCase4(int code); + void AbilityManagerGetAllRunningProcessesCase5(int code); + void AbilityManagerGetAllRunningProcessesCase6(int code); + + // GetAllStackInfo ST kit case + void AbilityManagerGetAllStackInfoCase1(int code); + void AbilityManagerGetAllStackInfoCase2(int code); + void AbilityManagerGetAllStackInfoCase3(int code); + void AbilityManagerGetAllStackInfoCase4(int code); + void AbilityManagerGetAllStackInfoCase5(int code); + + // QueryRecentAbilityMissionInfo ST kit case + void AbilityManagerQueryRecentAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase3(int code); + + // QueryRunningAbilityMissionInfo ST kit case + void AbilityManagerQueryRunningAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase3(int code); + + // MoveMissionToTop ST kit case + void AbilityManagerMoveMissionToTopCase1(int code); + + // ClearUpApplicationData ST kit case + void AbilityManagerClearUpApplicationDataCase1(int code); + + std::shared_ptr subscriber; + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + std::unordered_map mapStKitFunc_ = { + {static_cast(AbilityManagerApi::GetAllRunningProcesses), + {{[this](int code) { AbilityManagerGetAllRunningProcessesCase1(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase2(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase3(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase4(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase5(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase6(code); }}}}, + {static_cast(AbilityManagerApi::GetAllStackInfo), + {{[this](int code) { AbilityManagerGetAllStackInfoCase1(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase2(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase3(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase4(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase5(code); }}}}, + {static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase3(code); }}}}, + {static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase3(code); }}}}, + {static_cast(AbilityManagerApi::MoveMissionToTop), + {{[this](int code) { AbilityManagerMoveMissionToTopCase1(code); }}}}, + {static_cast(AbilityManagerApi::ClearUpApplicationData), + {{[this](int code) { AbilityManagerClearUpApplicationDataCase1(code); }}}}, + }; + + void Clear(); + void GetWantInfo(const Want &want); + std::string strapiIndex_; + std::string strcaseIndex_; + std::string strcode_; +}; + +// KitTestManagerSecondEventSubscriber Class +class KitTestManagerSecondEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + KitTestManagerSecondEventSubscriber( + const EventFwk::CommonEventSubscribeInfo &sp, KitTestAbilityManagerSecond *ability) + : CommonEventSubscriber(sp) + { + kitTestAbility_ = ability; + } + + ~KitTestManagerSecondEventSubscriber() + { + kitTestAbility_ = nullptr; + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + KitTestAbilityManagerSecond *kitTestAbility_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _KIT_TEST_ABILITY_MANAGER_SECOND_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp new file mode 100644 index 0000000000000000000000000000000000000000..901cc5f8f035446330d4156e1ff066e94dafb21b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp @@ -0,0 +1,452 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "kit_test_ability_manager_second.h" +#include +#include +#include +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +namespace { +const std::string currentAbilityName = "KitTestAbilityManagerSecond"; +const std::string topAbilityName = "KitTestAbilityManager"; +const std::string launchAbilityName = "com.ohos.launcher.MainAbility"; +const std::string bundleName = "com.ohos.amsst.AppKitAbilityManagerFirst"; +const std::string topProcessInfo = "com.ohos.amsst.AppKitAbilityManagerFirst"; +const std::string currentProcessInfo = "com.ohos.amsst.AppKitAbilityManager"; +const std::string launchProcessInfo = "com.ohos.launcher"; +bool isMoveMissionToTop = false; +int moveMissionToTopCode = -1; +bool isClearUpApplicationData = false; +int clearUpApplicationDataCode = -1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} // namespace + +bool KitTestAbilityManagerSecond::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestAbilityManagerSecond::SubscribeEvent(const vector_conststr &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void KitTestAbilityManagerSecond::AbilityManagerStByCode(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerStByCode"); + if (mapStKitFunc_.find(apiIndex) != mapStKitFunc_.end() && + static_cast(mapStKitFunc_[apiIndex].size()) > caseIndex) { + mapStKitFunc_[apiIndex][caseIndex](code); + } else { + APP_LOGI("AbilityManagerStByCode error"); + } +} + +void KitTestAbilityManagerSecond::CompareProcessName( + std::vector &info, const std::string &expectedName, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == expectedName) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == processName && processInfo.state_ == expectedState) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::ProcessStateNotEqual( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == processName && processInfo.state_ != expectedState) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::GetAllStackInfo(MissionStackInfo &missionStackInfo, int stackID) +{ + StackInfo stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); + for (const auto &stackInfo : stackInfo.missionStackInfos) { + if (stackInfo.id == stackID) { + missionStackInfo = stackInfo; + break; + } + } +} + +// GetAllRunningProcesses ST kit case +void KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase1(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase1"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, currentProcessInfo, code); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase2(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase2"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, topProcessInfo, code); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase3(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase3"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, launchProcessInfo, code); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase4(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase4"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessState(info, launchProcessInfo, AppProcessState::APP_STATE_BACKGROUND, code); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase5(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase5"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessState(info, currentProcessInfo, AppProcessState::APP_STATE_FOREGROUND, code); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase6(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllRunningProcessesCase6"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + bool result = false; + for (auto runProcessInfo : info) { + if (runProcessInfo.processName_ == currentProcessInfo && processInfo->GetPid() == runProcessInfo.pid_) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +// GetAllStackInfo ST kit case +void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase1"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + bool result = (missionStackInfo.missionRecords.size() == 1); + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase2"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool result = (abilityInfos[0].mainName.compare(launchAbilityName) == 0); + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase3"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + bool result = (missionStackInfo.missionRecords.size() == 1); + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase4"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + bool result = false; + if (missionStackInfo.missionRecords.size() == 1) { + result = (missionStackInfo.missionRecords[0].abilityRecordInfos.size() == numTwo); + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase5"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool currentResult = (abilityInfos[0].mainName.compare(currentAbilityName) == 0); + bool topResult = (abilityInfos[1].mainName.compare(topAbilityName) == 0); + bool result = (currentResult && topResult); + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +// QueryRecentAbilityMissionInfo ST kit case +void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase1"); + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + bool result = false; + if (info.size() == 1 && info[0].size == numTwo) { + if (info[0].baseAbility.GetBundleName() == bundleName) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase2"); + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + bool result = false; + if (info.size() == 1 && info[0].size == numTwo) { + result = true; + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase3"); + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + bool result = false; + if (info.size() == 1 && info[0].size == numTwo) { + if (info[0].baseAbility.GetBundleName() == bundleName && + info[0].baseAbility.GetAbilityName() == topAbilityName) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +// QueryRunningAbilityMissionInfo ST kit case +void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase1"); + std::vector info; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); + bool result = false; + if (info.size() == 1 && info[0].size == numTwo) { + if (info[0].baseAbility.GetBundleName() == bundleName) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase2"); + std::vector info; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); + bool result = false; + if (info.size() == 1 && info[0].size == numTwo) { + result = true; + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase3"); + std::vector info; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); + bool result = false; + if (info.size() == 1 && info[0].size == numTwo) { + if (info[0].baseAbility.GetBundleName() == bundleName && + info[0].baseAbility.GetAbilityName() == topAbilityName) { + result = true; + } + } + PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManagerSecond::AbilityManagerMoveMissionToTopCase1(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerMoveMissionToTopCase1"); + moveMissionToTopCode = code; + isMoveMissionToTop = true; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + StartAbility(wantEntity); +} + +void KitTestAbilityManagerSecond::AbilityManagerClearUpApplicationDataCase1(int code) +{ + APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerClearUpApplicationDataCase1"); + isClearUpApplicationData = true; + clearUpApplicationDataCode = code; +} + +void KitTestAbilityManagerSecond::OnStart(const Want &want) +{ + APP_LOGI("KitTestAbilityManagerSecond::onStart"); + Ability::OnStart(want); + SubscribeEvent(g_requPageManagerSecondAbilitySTVector); + GetWantInfo(want); + std::string eventData = GetAbilityName() + g_abilityStateOnStart; + PublishEvent(g_respPageManagerSecondAbilityST, 0, eventData); +} + +void KitTestAbilityManagerSecond::OnStop() +{ + APP_LOGI("KitTestAbilityManagerSecond::onStop"); + Ability::OnStop(); + if (isClearUpApplicationData != false) { + PublishEvent(g_respPageManagerAbilityST, clearUpApplicationDataCode, "1"); + isClearUpApplicationData = -1; + clearUpApplicationDataCode = false; + } + CommonEventManager::UnSubscribeCommonEvent(subscriber); + std::string eventData = GetAbilityName() + g_abilityStateOnStop; + PublishEvent(g_respPageManagerSecondAbilityST, 0, eventData); +} + +void KitTestAbilityManagerSecond::OnActive() +{ + APP_LOGI("KitTestAbilityManagerSecond::OnActive"); + Ability::OnActive(); + if (isMoveMissionToTop == true) { + PublishEvent(g_respPageManagerAbilityST, moveMissionToTopCode, "1"); + isMoveMissionToTop = false; + moveMissionToTopCode = -1; + } + int apiIndex_i = std::atoi(strapiIndex_.c_str()); + int codeIndex_i = std::atoi(strcaseIndex_.c_str()); + int code_i = std::atoi(strcode_.c_str()); + Clear(); + AbilityManagerStByCode(apiIndex_i, codeIndex_i, code_i); + std::string eventData = GetAbilityName() + g_abilityStateOnActive; + PublishEvent(g_respPageManagerSecondAbilityST, 0, eventData); +} + +void KitTestAbilityManagerSecond::OnInactive() +{ + APP_LOGI("KitTestAbilityManagerSecond::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + g_abilityStateOnInactive; + PublishEvent(g_respPageManagerSecondAbilityST, 0, eventData); +} + +void KitTestAbilityManagerSecond::OnBackground() +{ + APP_LOGI("KitTestAbilityManagerSecond::OnBackground"); + Ability::OnBackground(); + if (isMoveMissionToTop == true) { + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == numTwo) { + GetAbilityManager()->MoveMissionToTop(info[0].id); + APP_LOGI("GetAbilityManager()->MoveMissionToTop(info[0].id);%{public}d", static_cast(info[0].id)); + } + } + std::string eventData = GetAbilityName() + g_abilityStateOnBackground; + PublishEvent(g_respPageManagerSecondAbilityST, 0, eventData); +} + +void KitTestAbilityManagerSecond::OnForeground(const Want &want) +{ + APP_LOGI("KitTestAbilityManagerSecond::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + g_abilityStateOnForeground; + PublishEvent(g_respPageManagerSecondAbilityST, 0, eventData); +} + +void KitTestAbilityManagerSecond::OnNewWant(const Want &want) +{ + APP_LOGI("KitTestAbilityManagerSecond::OnNewWant"); + Ability::OnNewWant(want); + GetWantInfo(want); + std::string eventData = GetAbilityName() + g_abilityStateOnNewWant; + PublishEvent(g_respPageManagerSecondAbilityST, 0, eventData); +} + +void KitTestAbilityManagerSecond::Clear() +{ + strapiIndex_ = ""; + strcaseIndex_ = ""; + strcode_ = ""; +} + +void KitTestAbilityManagerSecond::GetWantInfo(const Want &want) +{ + Want mWant(want); + strapiIndex_ = mWant.GetStringParam("apiIndex"); + strcaseIndex_ = mWant.GetStringParam("caseIndex"); + strcode_ = mWant.GetStringParam("code"); +} + +// KitTestManagerSecondEventSubscriber Class +void KitTestManagerSecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (g_requPageManagerSecondAbilityST == eventName) { + auto target = data.GetData(); + if (target == "TerminateAbility") { + KitTerminateAbility(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void KitTestManagerSecondEventSubscriber::KitTerminateAbility() +{ + if (kitTestAbility_ != nullptr) { + kitTestAbility_->TerminateAbility(); + } +} + +REGISTER_AA(KitTestAbilityManagerSecond) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0c85c4396aea7bf22b07bbe8a40c3bd24c474b54 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("amsKitSTAbilityManagerConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitSTAbilityManagerFirst\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsKitSTAbilityManagerFirst") { + sources = [ + "src/kit_test_ability_manager.cpp", + "src/test_utils.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":amsKitSTAbilityManagerConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f5e648ed0b6a3cf10ba5e0f74459a648d2fdceca --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKitAbilityManagerFirst", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.KitAbilityManagerFirst.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "KitTestAbilityManager", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Kittest Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/kit_test_ability_manager.h b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/kit_test_ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..1bc3c529ed1d2eec1a368058024516d4802b4e4b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/kit_test_ability_manager.h @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _KIT_TEST_ABILITY_MANAGER_H_ +#define _KIT_TEST_ABILITY_MANAGER_H_ +#include +#include "ability_loader.h" +#include "running_process_info.h" +#include "ability_manager.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using vector_str = std::vector; +using vector_conststr = std::vector; +using vector_func = std::vector>; +using MAP_STR_STR = std::map; +class KitTestManagerEventSubscriber; +class KitTestAbilityManager : public Ability { +public: + void SubscribeEvent(const vector_conststr &eventList); + void AbilityManagerStByCode(int apiIndex, int caseIndex, int code); + void CompareProcessName(std::vector &info, const std::string &expectedName, int code); + void CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code); + void StartAbilitySelf( + const std::string &bundleName, const std::string &abilityNmae, AbilityManagerApi api, int codeIndex, int code); + void GetAllStackInfo(AAFwk::MissionStackInfo &missionStackInfo, int stackID); + + // GetAllRunningProcesses ST kit case + void AbilityManagerGetAllRunningProcessesCase1(int code); + void AbilityManagerGetAllRunningProcessesCase2(int code); + void AbilityManagerGetAllRunningProcessesCase3(int code); + void AbilityManagerGetAllRunningProcessesCase4(int code); + void AbilityManagerGetAllRunningProcessesCase5(int code); + void AbilityManagerGetAllRunningProcessesCase6(int code); + void AbilityManagerGetAllRunningProcessesCase7(int code); + void AbilityManagerGetAllRunningProcessesCase8(int code); + void AbilityManagerGetAllRunningProcessesCase9(int code); + void AbilityManagerGetAllRunningProcessesCase10(int code); + + // GetAllStackInfo ST kit case + void AbilityManagerGetAllStackInfoCase1(int code); + void AbilityManagerGetAllStackInfoCase2(int code); + void AbilityManagerGetAllStackInfoCase3(int code); + void AbilityManagerGetAllStackInfoCase4(int code); + void AbilityManagerGetAllStackInfoCase5(int code); + void AbilityManagerGetAllStackInfoCase6(int code); + void AbilityManagerGetAllStackInfoCase7(int code); + void AbilityManagerGetAllStackInfoCase8(int code); + void AbilityManagerGetAllStackInfoCase9(int code); + + // QueryRecentAbilityMissionInfo ST kit case + void QueryRecentAbilityMissionInfoParam(int numMax, int code, std::size_t size, int flags); + void AbilityManagerQueryRecentAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase3(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase4(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase5(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase6(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase7(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase8(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase9(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase10(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase11(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase12(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase13(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase14(int code); + + // QueryRunningAbilityMissionInfo ST kit case + void QueryRunningAbilityMissionInfoParam(int numMax, int code, std::size_t size); + void AbilityManagerQueryRunningAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase3(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase4(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase5(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase6(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase7(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase8(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase9(int code); + + // MoveMissionToTop ST kit case + void AbilityManagerMoveMissionToTopCase1(int code); + void AbilityManagerMoveMissionToTopCase2(int code); + + // ClearUpApplicationData ST kit case + void AbilityManagerClearUpApplicationDataCase1(int code); + std::shared_ptr subscriber; + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + std::unordered_map mapStKitFunc_{ + {static_cast(AbilityManagerApi::GetAllRunningProcesses), + {{[this](int code) { AbilityManagerGetAllRunningProcessesCase1(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase2(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase3(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase4(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase5(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase6(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase7(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase8(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase9(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase10(code); }}}}, + {static_cast(AbilityManagerApi::GetAllStackInfo), + {{[this](int code) { AbilityManagerGetAllStackInfoCase1(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase2(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase3(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase4(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase5(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase6(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase7(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase8(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase9(code); }}}}, + {static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase3(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase4(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase5(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase6(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase7(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase8(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase9(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase10(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase11(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase12(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase13(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase14(code); }}}}, + {static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase3(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase4(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase5(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase6(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase7(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase8(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase9(code); }}}}, + {static_cast(AbilityManagerApi::MoveMissionToTop), + {{[this](int code) { AbilityManagerMoveMissionToTopCase1(code); }}, + {[this](int code) { AbilityManagerMoveMissionToTopCase2(code); }}}}, + {static_cast(AbilityManagerApi::ClearUpApplicationData), + {{[this](int code) { AbilityManagerClearUpApplicationDataCase1(code); }}}}}; +}; + +// KitTestManagerEventSubscriber Class +class KitTestManagerEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + KitTestManagerEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, KitTestAbilityManager *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = {{"AbilityManagerApi", + [this](int apiIndex, int caseIndex, int code) { AbilityManagerStByCode(apiIndex, caseIndex, code); }}}; + kitTestAbility_ = ability; + } + ~KitTestManagerEventSubscriber() + { + kitTestAbility_ = nullptr; + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void AbilityManagerStByCode(int apiIndex, int caseIndex, int code); + void KitTerminateAbility(); + +private: + std::unordered_map> mapTestFunc_; + KitTestAbilityManager *kitTestAbility_; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif //_KIT_TEST_ABILITY_MANAGER_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0af55daf4ded4319a4da63849373fcf9ba3d4b03 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _TEST_UTILS_H_ +#define _TEST_UTILS_H_ +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _TEST_UTILS_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/kit_test_ability_manager.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/kit_test_ability_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50307f3f9e9cd53f7373ac16e4d8cd30d9a07384 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/kit_test_ability_manager.cpp @@ -0,0 +1,611 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "kit_test_ability_manager.h" +#include +#include +#include +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +namespace { +const std::string bundleName = "com.ohos.amsst.AppKitAbilityManager"; +const std::string abilityName = "KitTestAbilityManagerSecond"; +const std::string currentAbilityName = "KitTestAbilityManager"; +const std::string currentProcessInfo = "com.ohos.amsst.AppKitAbilityManagerFirst"; +const std::string launchAbilityName = "com.ohos.launcher.MainAbility"; +const std::string launchProcessInfo = "com.ohos.launcher"; +bool isMoveMissionToTop = false; +int moveMissionToTopCode = -1; +int isClearUpApplicationData = false; +int numThree = 3; +} // namespace + +void KitTestAbilityManager::SubscribeEvent(const vector_conststr &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void KitTestAbilityManager::AbilityManagerStByCode(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerStByCode"); + if (mapStKitFunc_.find(apiIndex) != mapStKitFunc_.end() && + static_cast(mapStKitFunc_[apiIndex].size()) > caseIndex) { + mapStKitFunc_[apiIndex][caseIndex](code); + } else { + APP_LOGI("AbilityManagerStByCode error"); + } +} + +void KitTestAbilityManager::CompareProcessName( + std::vector &info, const std::string &expectedName, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == expectedName) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == processName && processInfo.state_ == expectedState) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::StartAbilitySelf( + const std::string &bundleName, const std::string &abilityNmae, AbilityManagerApi api, int codeIndex, int code) +{ + MAP_STR_STR params; + params["apiIndex"] = std::to_string(static_cast(api)); + params["caseIndex"] = std::to_string(codeIndex); + params["code"] = std::to_string(code); + Want want = TestUtils::MakeWant("", abilityNmae, bundleName, params); + StartAbility(want); +} + +void KitTestAbilityManager::GetAllStackInfo(MissionStackInfo &missionStackInfo, int stackID) +{ + StackInfo stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); + for (const auto &missionInfo : stackInfo.missionStackInfos) { + if (missionInfo.id == stackID) { + missionStackInfo = missionInfo; + break; + } + } +} + +// GetAllRunningProcesses ST kit case +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase1"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, currentProcessInfo, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase2"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, launchProcessInfo, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase3"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + bool result = false; + for (auto runProcessInfo : info) { + if (runProcessInfo.processName_ == currentProcessInfo && processInfo->GetPid() == runProcessInfo.pid_) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase4"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessState(info, currentProcessInfo, AppProcessState::APP_STATE_FOREGROUND, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase8"); + auto index = 3; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase9"); + auto index = 4; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase10(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase10"); + auto index = 5; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +// GetAllStackInfo ST kit case +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase1"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + bool result = (missionStackInfo.missionRecords.size() == 1); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase2"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool result = (abilityInfos[0].mainName.compare(currentAbilityName) == 0); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase3"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + bool result = (missionStackInfo.missionRecords.size() == 1); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase4"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool result = (abilityInfos[0].mainName.compare(launchAbilityName) == 0); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase8"); + auto index = 3; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase9"); + auto index = 4; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +// QueryRecentAbilityMissionInfo ST kit case +void KitTestAbilityManager::QueryRecentAbilityMissionInfoParam(int numMax, int code, std::size_t size, int flags) +{ + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numMax, flags); + bool result = (info.size() == size); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase1"); + auto num = -1; + auto size = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_IGNORE_UNAVAILABLE); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase2"); + auto num = 3; + auto size = 0; + auto flag = -1; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase3"); + auto num = 3; + auto size = 0; + auto flag = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase4"); + auto num = 3; + auto size = 0; + auto flag = 3; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase5"); + auto num = 3; + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase6"); + auto num = 3; + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_IGNORE_UNAVAILABLE); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase7"); + std::vector info; + auto num = 3; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(num, RECENT_WITH_EXCLUDED); + bool result = false; + if (info.size() == 1 && info[0].size == 1) { + result = true; + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase8"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase9"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase10(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase10"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase11(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase11"); + auto num = std::numeric_limits::min(); + auto size = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase12(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase12"); + auto num = std::numeric_limits::max(); + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase13(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase13"); + auto num = 3; + auto size = 0; + auto flag = std::numeric_limits::min(); + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase14(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase14"); + auto num = 3; + auto size = 0; + auto flag = std::numeric_limits::max(); + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +// QueryRunningAbilityMissionInfo ST kit case +void KitTestAbilityManager::QueryRunningAbilityMissionInfoParam(int numMax, int code, std::size_t size) +{ + std::vector info; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numMax); + bool result = (info.size() == size); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase1"); + auto num = -1; + auto flag = 0; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase2"); + auto num = 0; + auto flag = 0; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase3"); + auto num = 3; + auto flag = 1; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase4"); + std::vector info; + auto num = 3; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(num); + bool result = false; + if (info.size() == 1 && info[0].size == 1) { + result = true; + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase8"); + QueryRunningAbilityMissionInfoParam(std::numeric_limits::min(), code, 0); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase9"); + QueryRunningAbilityMissionInfoParam(std::numeric_limits::max(), code, 1); +} + +// MoveMissionToTop ST kit case +void KitTestAbilityManager::AbilityManagerMoveMissionToTopCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerMoveMissionToTopCase1"); + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::MoveMissionToTop, 0, code); +} + +void KitTestAbilityManager::AbilityManagerMoveMissionToTopCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerMoveMissionToTopCase2"); + moveMissionToTopCode = code; + isMoveMissionToTop = true; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + StartAbility(wantEntity); +} + +// ClearUpApplicationData ST kit case +void KitTestAbilityManager::AbilityManagerClearUpApplicationDataCase1(int code) +{ + isClearUpApplicationData = true; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::ClearUpApplicationData, 0, code); +} + +void KitTestAbilityManager::OnStart(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::onStart"); + Ability::OnStart(want); + SubscribeEvent(g_requPageManagerAbilitySTVector); + std::string eventData = GetAbilityName() + g_abilityStateOnStart; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnStop() +{ + APP_LOGI("KitTestAbilityManager::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + std::string eventData = GetAbilityName() + g_abilityStateOnStop; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnActive() +{ + APP_LOGI("KitTestAbilityManager::OnActive"); + Ability::OnActive(); + if (isMoveMissionToTop) { + TestUtils::PublishEvent(g_respPageManagerAbilityST, moveMissionToTopCode, "1"); + isMoveMissionToTop = false; + moveMissionToTopCode = -1; + } + std::string eventData = GetAbilityName() + g_abilityStateOnActive; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnInactive() +{ + APP_LOGI("KitTestAbilityManager::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + g_abilityStateOnInactive; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnBackground() +{ + APP_LOGI("KitTestAbilityManager::OnBackground"); + Ability::OnBackground(); + if (isMoveMissionToTop) { + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == 1) { + GetAbilityManager()->MoveMissionToTop(info[0].id); + } + } + if (isClearUpApplicationData != false) { + AbilityManager::GetInstance().ClearUpApplicationData(currentProcessInfo); + isClearUpApplicationData = false; + } + std::string eventData = GetAbilityName() + g_abilityStateOnBackground; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnForeground(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + g_abilityStateOnForeground; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnNewWant(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + g_abilityStateOnNewWant; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +// KitTestManagerEventSubscriber Class +void KitTestManagerEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (g_requPageManagerAbilityST == eventName) { + auto target = data.GetData(); + auto handle = 0; + auto api = 1; + auto code = 2; + auto paramMinSize = 3; + vector_str splitResult = TestUtils::split(target, "_"); + auto keyMap = splitResult.at(handle); + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && + splitResult.size() >= static_cast(paramMinSize)) { + auto apiIndex = atoi(splitResult.at(api).c_str()); + auto caseIndex = atoi(splitResult.at(code).c_str()); + mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); + } else { + if (keyMap == "TerminateAbility") { + KitTerminateAbility(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } + } +} + +void KitTestManagerEventSubscriber::AbilityManagerStByCode(int apiIndex, int caseIndex, int code) +{ + if (kitTestAbility_ != nullptr) { + kitTestAbility_->AbilityManagerStByCode(apiIndex, caseIndex, code); + } +} + +void KitTestManagerEventSubscriber::KitTerminateAbility() +{ + if (kitTestAbility_ != nullptr) { + kitTestAbility_->TerminateAbility(); + } +} + +REGISTER_AA(KitTestAbilityManager) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f7fa556737647aecddbe3a8190286ad772fbb23 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/test_utils.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg(delim); + std::vector res = { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; + return res; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..0c9376ffecb715247cd6e3532ea9284392687aa3 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("amsKitSystemTestconfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitSystemTest\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsKitSystemTest") { + sources = [ + "src/fifth_ability.cpp", + "src/fourth_ability.cpp", + "src/kit_test_ability_manager.cpp", + "src/main_ability.cpp", + "src/second_ability.cpp", + "src/sixth_ability.cpp", + "src/test_utils.cpp", + "src/third_ability.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":amsKitSystemTestconfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..cebf56794b1dcf2c81466dc2a2d5ea65e80d833c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/config.json @@ -0,0 +1,112 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKit", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.AmsKitSystemTest.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Second Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ThirdAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Third Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "FourthAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Fourth Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "SixthAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Sixth Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "KitTestAbilityManager", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Kittest Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "FifthAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Fifth Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..45ee85ed58563188e40a036a6e23baece5649037 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _SECOND_ABILITY_H_ +#define _SECOND_ABILITY_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" +namespace OHOS { +namespace AppExecFwk { +class FifthEventSubscriber; +class FifthAbility : public Ability { +public: + FifthAbility() + { + InsertSetParamApi(); + InsertHasParamApi(); + InsertIsEmptyApi(); + InsertMarshallingApi(); + InsertSizeApi(); + InsertKeySetApi(); + InsertWantParamsCopyApi(); + InsertRemoveApi(); + } + + void InsertSetParamApi() + { + std::vector> funs = { + [this](int code) { WantParamsSetParamCase1(code); }, + [this](int code) { WantParamsSetParamCase2(code); }, + [this](int code) { WantParamsSetParamCase3(code); }, + [this](int code) { WantParamsSetParamCase4(code); }, + [this](int code) { WantParamsSetParamCase5(code); }, + [this](int code) { WantParamsSetParamCase6(code); }, + [this](int code) { WantParamsSetParamCase7(code); }, + [this](int code) { WantParamsSetParamCase8(code); }, + [this](int code) { WantParamsSetParamCase9(code); }, + [this](int code) { WantParamsSetParamCase10(code); }, + [this](int code) { WantParamsSetParamCase11(code); }, + [this](int code) { WantParamsSetParamCase12(code); }, + [this](int code) { WantParamsSetParamCase13(code); }, + [this](int code) { WantParamsSetParamCase14(code); }, + [this](int code) { WantParamsSetParamCase15(code); }, + [this](int code) { WantParamsSetParamCase16(code); }, + [this](int code) { WantParamsSetParamCase17(code); }, + [this](int code) { WantParamsSetParamCase18(code); }, + }; + mapCase_[(int)WantParamsApi::SetParam] = funs; + } + + void InsertHasParamApi() + { + std::vector> funs = { + [this](int code) { WantParamsHasParamCase1(code); }, + [this](int code) { WantParamsHasParamCase2(code); }, + [this](int code) { WantParamsHasParamCase3(code); }, + [this](int code) { WantParamsHasParamCase4(code); }, + [this](int code) { WantParamsHasParamCase5(code); }, + }; + mapCase_[(int)WantParamsApi::HasParam] = funs; + } + + void InsertIsEmptyApi() + { + std::vector> funs = { + [this](int code) { WantParamsIsEmptyCase1(code); }, + [this](int code) { WantParamsIsEmptyCase2(code); }, + }; + mapCase_[(int)WantParamsApi::IsEmpty] = funs; + } + + void InsertMarshallingApi() + { + std::vector> funs = { + [this](int code) { WantParamsMarshallingCase1(code); }, + [this](int code) { WantParamsMarshallingCase2(code); }, + [this](int code) { WantParamsMarshallingCase3(code); }, + [this](int code) { WantParamsMarshallingCase4(code); }, + [this](int code) { WantParamsMarshallingCase5(code); }, + [this](int code) { WantParamsMarshallingCase6(code); }, + [this](int code) { WantParamsMarshallingCase7(code); }, + [this](int code) { WantParamsMarshallingCase8(code); }, + [this](int code) { WantParamsMarshallingCase9(code); }, + [this](int code) { WantParamsMarshallingCase10(code); }, + [this](int code) { WantParamsMarshallingCase11(code); }, + [this](int code) { WantParamsMarshallingCase12(code); }, + [this](int code) { WantParamsMarshallingCase13(code); }, + [this](int code) { WantParamsMarshallingCase14(code); }, + [this](int code) { WantParamsMarshallingCase15(code); }, + [this](int code) { WantParamsMarshallingCase16(code); }, + [this](int code) { WantParamsMarshallingCase17(code); }, + [this](int code) { WantParamsMarshallingCase18(code); }, + }; + mapCase_[(int)WantParamsApi::Marshalling] = funs; + } + + void InsertSizeApi() + { + std::vector> funs = { + [this](int code) { WantParamsSizeCase1(code); }, + [this](int code) { WantParamsSizeCase2(code); }, + [this](int code) { WantParamsSizeCase3(code); }, + }; + mapCase_[(int)WantParamsApi::Size] = funs; + } + + void InsertKeySetApi() + { + std::vector> funs = { + [this](int code) { WantParamsKeySetCase1(code); }, + [this](int code) { WantParamsKeySetCase2(code); }, + }; + mapCase_[(int)WantParamsApi::KeySet] = funs; + } + + void InsertWantParamsCopyApi() + { + std::vector> funs = { + [this](int code) { WantParamsCopyCase1(code); }, + [this](int code) { WantParamsCopyCase2(code); }, + }; + mapCase_[(int)WantParamsApi::WantParamsCopy] = funs; + } + + void InsertRemoveApi() + { + std::vector> funs = { + [this](int code) { WantParamsRemoveCase1(code); }, + [this](int code) { WantParamsRemoveCase2(code); }, + }; + mapCase_[(int)WantParamsApi::Remove] = funs; + } + + virtual ~FifthAbility() = default; + void SubscribeEvent(); + void TestWantParams(int apiIndex, int caseIndex, int code); + void WantParamsSetParamCase1(int code); + void WantParamsSetParamCase2(int code); + void WantParamsSetParamCase3(int code); + void WantParamsSetParamCase4(int code); + void WantParamsSetParamCase5(int code); + void WantParamsSetParamCase6(int code); + void WantParamsSetParamCase7(int code); + void WantParamsSetParamCase8(int code); + void WantParamsSetParamCase9(int code); + void WantParamsSetParamCase10(int code); + void WantParamsSetParamCase11(int code); + void WantParamsSetParamCase12(int code); + void WantParamsSetParamCase13(int code); + void WantParamsSetParamCase14(int code); + void WantParamsSetParamCase15(int code); + void WantParamsSetParamCase16(int code); + void WantParamsSetParamCase17(int code); + void WantParamsSetParamCase18(int code); + void WantParamsHasParamCase1(int code); + void WantParamsHasParamCase2(int code); + void WantParamsHasParamCase3(int code); + void WantParamsHasParamCase4(int code); + void WantParamsHasParamCase5(int code); + void WantParamsIsEmptyCase1(int code); + void WantParamsIsEmptyCase2(int code); + void WantParamsMarshallingCase1(int code); + void WantParamsMarshallingCase2(int code); + void WantParamsMarshallingCase3(int code); + void WantParamsMarshallingCase4(int code); + void WantParamsMarshallingCase5(int code); + void WantParamsMarshallingCase6(int code); + void WantParamsMarshallingCase7(int code); + void WantParamsMarshallingCase8(int code); + void WantParamsMarshallingCase9(int code); + void WantParamsMarshallingCase10(int code); + void WantParamsMarshallingCase11(int code); + void WantParamsMarshallingCase12(int code); + void WantParamsMarshallingCase13(int code); + void WantParamsMarshallingCase14(int code); + void WantParamsMarshallingCase15(int code); + void WantParamsMarshallingCase16(int code); + void WantParamsMarshallingCase17(int code); + void WantParamsMarshallingCase18(int code); + void WantParamsSizeCase1(int code); + void WantParamsSizeCase2(int code); + void WantParamsSizeCase3(int code); + void WantParamsKeySetCase1(int code); + void WantParamsKeySetCase2(int code); + void WantParamsCopyCase1(int code); + void WantParamsCopyCase2(int code); + void WantParamsRemoveCase1(int code); + void WantParamsRemoveCase2(int code); + + std::unordered_map>> mapCase_; + std::shared_ptr subscriber; + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + virtual void OnBackPressed() override; + virtual void OnNewWant(const Want &want) override; +}; + +class FifthEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { +public: + FifthEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &sp, FifthAbility *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"WantParams", + [this](int apiIndex, int caseIndex, int code) { TestWantParams(apiIndex, caseIndex, code); }}, + }; + fifthAbility = ability; + } + ~FifthEventSubscriber() = default; + + void TestWantParams(int apiIndex, int caseIndex, int code) + { + fifthAbility->TestWantParams(apiIndex, caseIndex, code); + } + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data); + + FifthAbility *fifthAbility; + std::unordered_map> mapTestFunc_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _SECOND_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..0b4dcddcd4a3fe94d578c6ccb74b69614795f4db --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h @@ -0,0 +1,783 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _THIRD_ABILITY_H_ +#define _THIRD_ABILITY_H_ +#include +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" +#include "skills.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using vector_str = std::vector; +using vector_conststr = std::vector; +using vector_func = std::vector>; +class KitTestFourthEventSubscriber; + +class FourthAbility : public Ability { +public: + void SubscribeEvent(const vector_conststr &eventList); + void SkillsApiStByCode(int apiIndex, int caseIndex, int code); + bool CompareEntity(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareAction(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareAuthority(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareScheme(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareSPath(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareSsp(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareType(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareWantParams(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + bool CompareSkills(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); + template + void SkillsGetWantParams(M params, int code) + { + AAFwk::Skills skill; + AAFwk::WantParams wantParams; + std::string keyStr = "ParamsKey"; + M value = params; + wantParams.SetParam(keyStr, T::Box(value)); + skill.SetWantParams(wantParams); + bool result = (value == T::Unbox(IT::Query(skill.GetWantParams().GetParam(keyStr)))); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); + } + + // AddAction and CountActions ST kit Case + void SkillsAddActionAndCountActionsCase1(int code); + void SkillsAddActionAndCountActionsCase2(int code); + void SkillsAddActionAndCountActionsCase3(int code); + // AddAction and GetAction ST kit Case + void SkillsAddActionAndGetActionCase1(int code); + void SkillsAddActionAndGetActionCase2(int code); + void SkillsAddActionAndGetActionCase3(int code); + void SkillsAddActionAndGetActionCase4(int code); + void SkillsAddActionAndGetActionCase5(int code); + void SkillsAddActionAndGetActionCase6(int code); + void SkillsAddActionAndGetActionCase7(int code); + // AddAction and HasAction ST kit Case + void SkillsAddActionAndHasActionCase1(int code); + void SkillsAddActionAndHasActionCase2(int code); + void SkillsAddActionAndHasActionCase3(int code); + // AddAction,RemoveAction,CountActions and HasAction ST kit Case + void SkillsAddActionAndRemoveActionCase1(int code); + void SkillsAddActionAndRemoveActionCase2(int code); + void SkillsAddActionAndRemoveActionCase3(int code); + void SkillsAddActionAndRemoveActionCase4(int code); + void SkillsAddActionAndRemoveActionCase5(int code); + void SkillsAddActionAndRemoveActionCase6(int code); + void SkillsAddActionAndRemoveActionCase7(int code); + void SkillsAddActionAndRemoveActionCase8(int code); + void SkillsAddActionAndRemoveActionCase9(int code); + + // AddEntity and CountEntities ST kit Case + void SkillsAddEntityAndCountEntitiesCase1(int code); + void SkillsAddEntityAndCountEntitiesCase2(int code); + void SkillsAddEntityAndCountEntitiesCase3(int code); + // AddEntity and GetEntity ST kit Case + void SkillsAddEntityAndGetEntityCase1(int code); + void SkillsAddEntityAndGetEntityCase2(int code); + void SkillsAddEntityAndGetEntityCase3(int code); + void SkillsAddEntityAndGetEntityCase4(int code); + void SkillsAddEntityAndGetEntityCase5(int code); + void SkillsAddEntityAndGetEntityCase6(int code); + void SkillsAddEntityAndGetEntityCase7(int code); + // AddEntity and HasEntity ST kit Case + void SkillsAddEntityAndHasEntityCase1(int code); + void SkillsAddEntityAndHasEntityCase2(int code); + void SkillsAddEntityAndHasEntityCase3(int code); + // AddEntity,RemoveEntity,CountEntities and HasEntity ST kit Case + void SkillsAddEntityAndRemoveEntityCase1(int code); + void SkillsAddEntityAndRemoveEntityCase2(int code); + void SkillsAddEntityAndRemoveEntityCase3(int code); + void SkillsAddEntityAndRemoveEntityCase4(int code); + void SkillsAddEntityAndRemoveEntityCase5(int code); + void SkillsAddEntityAndRemoveEntityCase6(int code); + void SkillsAddEntityAndRemoveEntityCase7(int code); + void SkillsAddEntityAndRemoveEntityCase8(int code); + void SkillsAddEntityAndRemoveEntityCase9(int code); + + // AddAuthority and CountAuthorities ST kit Case + void SkillsAddAuthorityAndCountAuthoritiesCase1(int code); + void SkillsAddAuthorityAndCountAuthoritiesCase2(int code); + void SkillsAddAuthorityAndCountAuthoritiesCase3(int code); + // AddAuthority and GetAuthority ST kit Case + void SkillsAddAuthorityAndGetAuthorityCase1(int code); + void SkillsAddAuthorityAndGetAuthorityCase2(int code); + void SkillsAddAuthorityAndGetAuthorityCase3(int code); + void SkillsAddAuthorityAndGetAuthorityCase4(int code); + void SkillsAddAuthorityAndGetAuthorityCase5(int code); + void SkillsAddAuthorityAndGetAuthorityCase6(int code); + void SkillsAddAuthorityAndGetAuthorityCase7(int code); + // AddAuthority and HasAuthority ST kit Case + void SkillsAddAuthorityAndHasAuthorityCase1(int code); + void SkillsAddAuthorityAndHasAuthorityCase2(int code); + void SkillsAddAuthorityAndHasAuthorityCase3(int code); + // AddAuthority,RemoveAuthority,CountAuthorities and HasAuthority ST kit Case + void SkillsAddAuthorityAndRemoveAuthorityCase1(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase2(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase3(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase4(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase5(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase6(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase7(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase8(int code); + void SkillsAddAuthorityAndRemoveAuthorityCase9(int code); + + // AddScheme and CountSchemes ST kit Case + void SkillsAddSchemeAndCountSchemesCase1(int code); + void SkillsAddSchemeAndCountSchemesCase2(int code); + void SkillsAddSchemeAndCountSchemesCase3(int code); + // AddScheme and GetScheme ST kit Case + void SkillsAddSchemeAndGetSchemeCase1(int code); + void SkillsAddSchemeAndGetSchemeCase2(int code); + void SkillsAddSchemeAndGetSchemeCase3(int code); + void SkillsAddSchemeAndGetSchemeCase4(int code); + void SkillsAddSchemeAndGetSchemeCase5(int code); + void SkillsAddSchemeAndGetSchemeCase6(int code); + void SkillsAddSchemeAndGetSchemeCase7(int code); + // AddScheme and HasScheme ST kit Case + void SkillsAddSchemeAndHasSchemeCase1(int code); + void SkillsAddSchemeAndHasSchemeCase2(int code); + void SkillsAddSchemeAndHasSchemeCase3(int code); + // AddScheme,RemoveScheme,CountSchemes and HasScheme ST kit Case + void SkillsAddSchemeAndRemoveSchemeCase1(int code); + void SkillsAddSchemeAndRemoveSchemeCase2(int code); + void SkillsAddSchemeAndRemoveSchemeCase3(int code); + void SkillsAddSchemeAndRemoveSchemeCase4(int code); + void SkillsAddSchemeAndRemoveSchemeCase5(int code); + void SkillsAddSchemeAndRemoveSchemeCase6(int code); + void SkillsAddSchemeAndRemoveSchemeCase7(int code); + void SkillsAddSchemeAndRemoveSchemeCase8(int code); + void SkillsAddSchemeAndRemoveSchemeCase9(int code); + + // AddSchemeSpecificPart and CountSchemeSpecificParts ST kit Case + void SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase1(int code); + void SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase2(int code); + void SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase3(int code); + // AddSchemeSpecificPart and GetSchemeSpecificPart ST kit Case + void SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase1(int code); + void SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase2(int code); + void SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase3(int code); + void SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase4(int code); + void SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase5(int code); + void SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase6(int code); + void SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase7(int code); + // AddSchemeSpecificPart and HasSchemeSpecificPart ST kit Case + void SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase1(int code); + void SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase2(int code); + void SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase3(int code); + // AddSchemeSpecificPart,RemoveSchemeSpecificPart,CountSchemeSpecificParts and HasSchemeSpecificPart ST kit Case + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase1(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase2(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase3(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase4(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase5(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase6(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase7(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase8(int code); + void SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase9(int code); + + // AddPath_String and CountPaths ST kit Case + void SkillsAddPathStringAndCountPathsCase1(int code); + void SkillsAddPathStringAndCountPathsCase2(int code); + // AddPath_String_MatchType and CountPaths ST kit Case + void SkillsAddPathStringMatchTypeAndCountPathsCase1(int code); + void SkillsAddPathStringMatchTypeAndCountPathsCase2(int code); + // AddPath_PatternMatcher and CountPaths ST kit Case + void SkillsAddPathPatternAndCountPathsCase1(int code); + void SkillsAddPathPatternAndCountPathsCase2(int code); + // CountPaths ST kit Case + void SkillsCountPathsCase1(int code); + // AddPath_String and GetPath ST kit Case + void SkillsAddPathStringAndGetPathCase1(int code); + void SkillsAddPathStringAndGetPathCase2(int code); + void SkillsAddPathStringAndGetPathCase3(int code); + void SkillsAddPathStringAndGetPathCase4(int code); + void SkillsAddPathStringAndGetPathCase5(int code); + void SkillsAddPathStringAndGetPathCase6(int code); + // AddPath_String_MatchType and GetPath ST kit Case + void SkillsAddPathStringMatchTypeAndGetPathCase1(int code); + void SkillsAddPathStringMatchTypeAndGetPathCase2(int code); + void SkillsAddPathStringMatchTypeAndGetPathCase3(int code); + void SkillsAddPathStringMatchTypeAndGetPathCase4(int code); + void SkillsAddPathStringMatchTypeAndGetPathCase5(int code); + void SkillsAddPathStringMatchTypeAndGetPathCase6(int code); + // AddPath_PatternMatcher and GetPath ST kit Case + void SkillsAddPathPatternAndGetPathCase1(int code); + void SkillsAddPathPatternAndGetPathCase2(int code); + void SkillsAddPathPatternAndGetPathCase3(int code); + void SkillsAddPathPatternAndGetPathCase4(int code); + void SkillsAddPathPatternAndGetPathCase5(int code); + void SkillsAddPathPatternAndGetPathCase6(int code); + // GetPath ST kit Case + void SkillsGetPathCase1(int code); + // AddPath_String and HasPath ST kit Case + void SkillsAddPathStringAndHasPathCase1(int code); + void SkillsAddPathStringAndHasPathCase2(int code); + // AddPath_String_MatchType and HasPath ST kit Case + void SkillsAddPathStringMatchTypeAndHasPathCase1(int code); + void SkillsAddPathStringMatchTypeAndHasPathCase2(int code); + // AddPath_PatternMatcher and HasPath ST kit Case + void SkillsAddPathPatternAndHasPathCase1(int code); + void SkillsAddPathPatternAndHasPathCase2(int code); + // HasPath ST kit Case + void SkillsHasPathCase1(int code); + // AddPath_String and RemovePath ST kit Case + void SkillsAddPathStringAndRemovePathStringCase1(int code); + void SkillsAddPathStringAndRemovePathStringCase2(int code); + void SkillsAddPathStringAndRemovePathStringCase3(int code); + void SkillsAddPathStringAndRemovePathStringCase4(int code); + void SkillsAddPathStringAndRemovePathStringCase5(int code); + void SkillsAddPathStringAndRemovePathStringCase6(int code); + void SkillsAddPathStringAndRemovePathStringCase7(int code); + void SkillsAddPathStringAndRemovePathStringCase8(int code); + void SkillsAddPathStringAndRemovePathStringCase9(int code); + // AddPath_String_MatchType and RemovePathStringMatchType ST kit Case + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase1(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase2(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase3(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase4(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase5(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase6(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase7(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase8(int code); + void SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase9(int code); + // AddPath_PatternMatcher and RemovePathPatternMatcher ST kit Case + void SkillsAddPathPatternAndRemovePathPatternMatcherCase1(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase2(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase3(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase4(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase5(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase6(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase7(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase8(int code); + void SkillsAddPathPatternAndRemovePathPatternMatcherCase9(int code); + // AddPath and RemovePath ST kit Case + void SkillsAddPathPatternAndRemovePathCase1(int code); + void SkillsAddPathPatternAndRemovePathCase2(int code); + void SkillsAddPathPatternAndRemovePathCase3(int code); + + // AddType_String and CountTypes ST kit Case + void SkillsAddTypeStringAndCountTypesCase1(int code); + void SkillsAddTypeStringAndCountTypesCase2(int code); + // AddType_String_MatchType and CountTypes ST kit Case + void SkillsAddTypeStringMatchTypeAndCountTypesCase1(int code); + void SkillsAddTypeStringMatchTypeAndCountTypesCase2(int code); + // AddType_PatternMatcher and CountTypes ST kit Case + void SkillsAddTypePatternAndCountTypesCase1(int code); + void SkillsAddTypePatternAndCountTypesCase2(int code); + // CountTypes ST kit Case + void SkillsCountTypesCase1(int code); + // AddType_String and GetType ST kit Case + void SkillsAddTypeStringAndGetTypeCase1(int code); + void SkillsAddTypeStringAndGetTypeCase2(int code); + void SkillsAddTypeStringAndGetTypeCase3(int code); + void SkillsAddTypeStringAndGetTypeCase4(int code); + void SkillsAddTypeStringAndGetTypeCase5(int code); + void SkillsAddTypeStringAndGetTypeCase6(int code); + // AddType_String_MatchType and GetType ST kit Case + void SkillsAddTypeStringMatchTypeAndGetTypeCase1(int code); + void SkillsAddTypeStringMatchTypeAndGetTypeCase2(int code); + void SkillsAddTypeStringMatchTypeAndGetTypeCase3(int code); + void SkillsAddTypeStringMatchTypeAndGetTypeCase4(int code); + void SkillsAddTypeStringMatchTypeAndGetTypeCase5(int code); + void SkillsAddTypeStringMatchTypeAndGetTypeCase6(int code); + // AddType_PatternMatcher and GetType ST kit Case + void SkillsAddTypePatternAndGetTypeCase1(int code); + void SkillsAddTypePatternAndGetTypeCase2(int code); + void SkillsAddTypePatternAndGetTypeCase3(int code); + void SkillsAddTypePatternAndGetTypeCase4(int code); + void SkillsAddTypePatternAndGetTypeCase5(int code); + void SkillsAddTypePatternAndGetTypeCase6(int code); + // GetType ST kit Case + void SkillsGetTypeCase1(int code); + // AddType_String and HasType ST kit Case + void SkillsAddTypeStringAndHasTypeCase1(int code); + void SkillsAddTypeStringAndHasTypeCase2(int code); + // AddType_String_MatchType and HasType ST kit Case + void SkillsAddTypeStringMatchTypeAndHasTypeCase1(int code); + void SkillsAddTypeStringMatchTypeAndHasTypeCase2(int code); + // AddType_PatternMatcher and HasType ST kit Case + void SkillsAddTypePatternAndHasTypeCase1(int code); + void SkillsAddTypePatternAndHasTypeCase2(int code); + // HasType ST kit Case + void SkillsHasTypeCase1(int code); + // AddType_String and RemoveType ST kit Case + void SkillsAddTypeStringAndRemoveTypeStringCase1(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase2(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase3(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase4(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase5(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase6(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase7(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase8(int code); + void SkillsAddTypeStringAndRemoveTypeStringCase9(int code); + // AddType_String_MatchType and RemoveTypeStringMatchType ST kit Case + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase1(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase2(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase3(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase4(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase5(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase6(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase7(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase8(int code); + void SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase9(int code); + // AddType_PatternMatcher and RemoveTypePatternMatcher ST kit Case + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase1(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase2(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase3(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase4(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase5(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase6(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase7(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase8(int code); + void SkillsAddTypePatternAndRemoveTypePatternMatcherCase9(int code); + // AddType and RemoveType ST kit Case + void SkillsAddTypePatternAndRemoveTypeCase1(int code); + void SkillsAddTypePatternAndRemoveTypeCase2(int code); + void SkillsAddTypePatternAndRemoveTypeCase3(int code); + void SkillsAddTypePatternAndRemoveTypeCase4(int code); + void SkillsAddTypePatternAndRemoveTypeCase5(int code); + void SkillsAddTypePatternAndRemoveTypeCase6(int code); + void SkillsAddTypePatternAndRemoveTypeCase7(int code); + void SkillsAddTypePatternAndRemoveTypeCase8(int code); + void SkillsAddTypePatternAndRemoveTypeCase9(int code); + + // AddEntity and GetEntities ST kit Case + void SkillAddEntityAndGetEntitiesCase1(int code); + void SkillAddEntityAndGetEntitiesCase2(int code); + void SkillAddEntityAndGetEntitiesCase3(int code); + void SkillAddEntityAndGetEntitiesCase4(int code); + void SkillAddEntityAndGetEntitiesCase5(int code); + + // SetWantParams and GetWantParams ST kit Case + void SkillSetAndGetWantParamsCase1(int code); + void SkillSetAndGetWantParamsCase2(int code); + void SkillSetAndGetWantParamsCase3(int code); + void SkillSetAndGetWantParamsCase4(int code); + void SkillSetAndGetWantParamsCase5(int code); + + // Match ST kit Case + void SkillMatchCase1(int code); + void SkillMatchCase2(int cade); + void SkillMatchCase3(int code); + void SkillMatchCase4(int cade); + void SkillMatchCase5(int code); + void SkillMatchCase6(int cade); + + // Unmarshalling And Marshalling ST kit Case + void SkillUnmarshallingCase1(int code); + void SkillUnmarshallingCase2(int code); + void SkillUnmarshallingCase3(int code); + void SkillUnmarshallingCase4(int code); + + // Skills ST kit Case + void SkillSkillsCase1(int code); + void SkillSkillsCase2(int code); + void SkillSkillsCase3(int code); + void SkillSkillsCase4(int code); + + // Skills_Skills ST kit Case + void SkillSkillsSkillsCase1(int code); + void SkillSkillsSkillsCase2(int code); + void SkillSkillsSkillsCase3(int code); + void SkillSkillsSkillsCase4(int code); + + // Skills AddAction ST kit Case + void SkillAddActionCase1(int code); + + // Skills AddEntity ST kit Case + void SkillAddEntityCase1(int code); + + // Skills AddAuthority ST kit Case + void SkillAddAuthorityCase1(int code); + + // Skills AddScheme ST kit Case + void SkillAddSchemeCase1(int code); + + // Skills AddSchemeSpecificPart ST kit Case + void SkillAddSchemeSpecificPartCase1(int code); + + std::shared_ptr subscriber; + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + std::unordered_map mapStKitFunc_ = { + {static_cast(SkillsApi::CountActions), + {{[this](int code) { SkillsAddActionAndCountActionsCase1(code); }}, + {[this](int code) { SkillsAddActionAndCountActionsCase2(code); }}, + {[this](int code) { SkillsAddActionAndCountActionsCase3(code); }}}}, + {static_cast(SkillsApi::GetAction), + {{[this](int code) { SkillsAddActionAndGetActionCase1(code); }}, + {[this](int code) { SkillsAddActionAndGetActionCase2(code); }}, + {[this](int code) { SkillsAddActionAndGetActionCase3(code); }}, + {[this](int code) { SkillsAddActionAndGetActionCase4(code); }}, + {[this](int code) { SkillsAddActionAndGetActionCase5(code); }}, + {[this](int code) { SkillsAddActionAndGetActionCase6(code); }}, + {[this](int code) { SkillsAddActionAndGetActionCase7(code); }}}}, + {static_cast(SkillsApi::HasAction), + {{[this](int code) { SkillsAddActionAndHasActionCase1(code); }}, + {[this](int code) { SkillsAddActionAndHasActionCase2(code); }}, + {[this](int code) { SkillsAddActionAndHasActionCase3(code); }}}}, + {static_cast(SkillsApi::RemoveAction), + {{[this](int code) { SkillsAddActionAndRemoveActionCase1(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase2(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase3(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase4(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase5(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase6(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase7(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase8(code); }}, + {[this](int code) { SkillsAddActionAndRemoveActionCase9(code); }}}}, + {static_cast(SkillsApi::CountEntities), + {{[this](int code) { SkillsAddEntityAndCountEntitiesCase1(code); }}, + {[this](int code) { SkillsAddEntityAndCountEntitiesCase2(code); }}, + {[this](int code) { SkillsAddEntityAndCountEntitiesCase3(code); }}}}, + {static_cast(SkillsApi::GetEntity), + {{[this](int code) { SkillsAddEntityAndGetEntityCase1(code); }}, + {[this](int code) { SkillsAddEntityAndGetEntityCase2(code); }}, + {[this](int code) { SkillsAddEntityAndGetEntityCase3(code); }}, + {[this](int code) { SkillsAddEntityAndGetEntityCase4(code); }}, + {[this](int code) { SkillsAddEntityAndGetEntityCase5(code); }}, + {[this](int code) { SkillsAddEntityAndGetEntityCase6(code); }}, + {[this](int code) { SkillsAddEntityAndGetEntityCase7(code); }}}}, + {static_cast(SkillsApi::HasEntity), + {{[this](int code) { SkillsAddEntityAndHasEntityCase1(code); }}, + {[this](int code) { SkillsAddEntityAndHasEntityCase2(code); }}, + {[this](int code) { SkillsAddEntityAndHasEntityCase3(code); }}}}, + {static_cast(SkillsApi::RemoveEntity), + {{[this](int code) { SkillsAddEntityAndRemoveEntityCase1(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase2(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase3(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase4(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase5(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase6(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase7(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase8(code); }}, + {[this](int code) { SkillsAddEntityAndRemoveEntityCase9(code); }}}}, + {static_cast(SkillsApi::CountAuthorities), + {{[this](int code) { SkillsAddAuthorityAndCountAuthoritiesCase1(code); }}, + {[this](int code) { SkillsAddAuthorityAndCountAuthoritiesCase2(code); }}, + {[this](int code) { SkillsAddAuthorityAndCountAuthoritiesCase3(code); }}}}, + {static_cast(SkillsApi::GetAuthority), + {{[this](int code) { SkillsAddAuthorityAndGetAuthorityCase1(code); }}, + {[this](int code) { SkillsAddAuthorityAndGetAuthorityCase2(code); }}, + {[this](int code) { SkillsAddAuthorityAndGetAuthorityCase3(code); }}, + {[this](int code) { SkillsAddAuthorityAndGetAuthorityCase4(code); }}, + {[this](int code) { SkillsAddAuthorityAndGetAuthorityCase5(code); }}, + {[this](int code) { SkillsAddAuthorityAndGetAuthorityCase6(code); }}, + {[this](int code) { SkillsAddAuthorityAndGetAuthorityCase7(code); }}}}, + {static_cast(SkillsApi::HasAuthority), + {{[this](int code) { SkillsAddAuthorityAndHasAuthorityCase1(code); }}, + {[this](int code) { SkillsAddAuthorityAndHasAuthorityCase2(code); }}, + {[this](int code) { SkillsAddAuthorityAndHasAuthorityCase3(code); }}}}, + {static_cast(SkillsApi::RemoveAuthority), + {{[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase1(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase2(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase3(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase4(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase5(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase6(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase7(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase8(code); }}, + {[this](int code) { SkillsAddAuthorityAndRemoveAuthorityCase9(code); }}}}, + {static_cast(SkillsApi::CountSchemes), + {{[this](int code) { SkillsAddSchemeAndCountSchemesCase1(code); }}, + {[this](int code) { SkillsAddSchemeAndCountSchemesCase2(code); }}, + {[this](int code) { SkillsAddSchemeAndCountSchemesCase3(code); }}}}, + {static_cast(SkillsApi::GetScheme), + {{[this](int code) { SkillsAddSchemeAndGetSchemeCase1(code); }}, + {[this](int code) { SkillsAddSchemeAndGetSchemeCase2(code); }}, + {[this](int code) { SkillsAddSchemeAndGetSchemeCase3(code); }}, + {[this](int code) { SkillsAddSchemeAndGetSchemeCase4(code); }}, + {[this](int code) { SkillsAddSchemeAndGetSchemeCase5(code); }}, + {[this](int code) { SkillsAddSchemeAndGetSchemeCase6(code); }}, + {[this](int code) { SkillsAddSchemeAndGetSchemeCase7(code); }}}}, + {static_cast(SkillsApi::HasScheme), + {{[this](int code) { SkillsAddSchemeAndHasSchemeCase1(code); }}, + {[this](int code) { SkillsAddSchemeAndHasSchemeCase2(code); }}, + {[this](int code) { SkillsAddSchemeAndHasSchemeCase3(code); }}}}, + {static_cast(SkillsApi::RemoveScheme), + {{[this](int code) { SkillsAddSchemeAndRemoveSchemeCase1(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase2(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase3(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase4(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase5(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase6(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase7(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase8(code); }}, + {[this](int code) { SkillsAddSchemeAndRemoveSchemeCase9(code); }}}}, + {static_cast(SkillsApi::CountSchemeSpecificParts), + {{[this](int code) { SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase1(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase2(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase3(code); }}}}, + {static_cast(SkillsApi::GetSchemeSpecificPart), + {{[this](int code) { SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase1(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase2(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase3(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase4(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase5(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase6(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase7(code); }}}}, + {static_cast(SkillsApi::HasSchemeSpecificPart), + {{[this](int code) { SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase1(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase2(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase3(code); }}}}, + {static_cast(SkillsApi::RemoveSchemeSpecificPart), + {{[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase1(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase2(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase3(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase4(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase5(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase6(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase7(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase8(code); }}, + {[this](int code) { SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase9(code); }}}}, + {static_cast(SkillsApi::AddPath_String_CountPaths), + {{[this](int code) { SkillsAddPathStringAndCountPathsCase1(code); }}, + {[this](int code) { SkillsAddPathStringAndCountPathsCase2(code); }}}}, + {static_cast(SkillsApi::AddPath_String_MatchType_CountPaths), + {{[this](int code) { SkillsAddPathStringMatchTypeAndCountPathsCase1(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndCountPathsCase2(code); }}}}, + {static_cast(SkillsApi::AddPath_PatternMatcher_CountPaths), + {{[this](int code) { SkillsAddPathPatternAndCountPathsCase1(code); }}, + {[this](int code) { SkillsAddPathPatternAndCountPathsCase2(code); }}}}, + {static_cast(SkillsApi::CountPaths), {{[this](int code) { SkillsCountPathsCase1(code); }}}}, + {static_cast(SkillsApi::AddPath_String_GetPath), + {{[this](int code) { SkillsAddPathStringAndGetPathCase1(code); }}, + {[this](int code) { SkillsAddPathStringAndGetPathCase2(code); }}, + {[this](int code) { SkillsAddPathStringAndGetPathCase3(code); }}, + {[this](int code) { SkillsAddPathStringAndGetPathCase4(code); }}, + {[this](int code) { SkillsAddPathStringAndGetPathCase5(code); }}, + {[this](int code) { SkillsAddPathStringAndGetPathCase6(code); }}}}, + {static_cast(SkillsApi::AddPath_String_MatchType_GetPath), + {{[this](int code) { SkillsAddPathStringMatchTypeAndGetPathCase1(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndGetPathCase2(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndGetPathCase3(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndGetPathCase4(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndGetPathCase5(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndGetPathCase6(code); }}}}, + {static_cast(SkillsApi::AddPath_PatternMatcher_GetPath), + {{[this](int code) { SkillsAddPathPatternAndGetPathCase1(code); }}, + {[this](int code) { SkillsAddPathPatternAndGetPathCase2(code); }}, + {[this](int code) { SkillsAddPathPatternAndGetPathCase3(code); }}, + {[this](int code) { SkillsAddPathPatternAndGetPathCase4(code); }}, + {[this](int code) { SkillsAddPathPatternAndGetPathCase5(code); }}, + {[this](int code) { SkillsAddPathPatternAndGetPathCase6(code); }}}}, + {static_cast(SkillsApi::GetPath), {{[this](int code) { SkillsGetPathCase1(code); }}}}, + {static_cast(SkillsApi::AddPath_String_HasPath), + {{[this](int code) { SkillsAddPathStringAndHasPathCase1(code); }}, + {[this](int code) { SkillsAddPathStringAndHasPathCase2(code); }}}}, + {static_cast(SkillsApi::AddPath_String_MatchType_HasPath), + {{[this](int code) { SkillsAddPathStringMatchTypeAndHasPathCase1(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndHasPathCase2(code); }}}}, + {static_cast(SkillsApi::AddPath_PatternMatcher_HasPath), + {{[this](int code) { SkillsAddPathStringMatchTypeAndHasPathCase1(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndHasPathCase2(code); }}}}, + {static_cast(SkillsApi::HasPath), {{[this](int code) { SkillsHasPathCase1(code); }}}}, + {static_cast(SkillsApi::RemovePath_String), + {{[this](int code) { SkillsAddPathStringAndRemovePathStringCase1(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase2(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase3(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase4(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase5(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase6(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase7(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase8(code); }}, + {[this](int code) { SkillsAddPathStringAndRemovePathStringCase9(code); }}}}, + {static_cast(SkillsApi::RemovePath_String_MatchType), + {{[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase1(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase2(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase3(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase4(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase5(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase6(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase7(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase8(code); }}, + {[this](int code) { SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase9(code); }}}}, + {static_cast(SkillsApi::RemovePath_PatternMatcher), + {{[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase1(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase2(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase3(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase4(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase5(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase6(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase7(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase8(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathPatternMatcherCase9(code); }}}}, + {static_cast(SkillsApi::RemovePath_Other), + {{[this](int code) { SkillsAddPathPatternAndRemovePathCase1(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathCase2(code); }}, + {[this](int code) { SkillsAddPathPatternAndRemovePathCase3(code); }}}}, + {static_cast(SkillsApi::AddType_String_CountTypes), + {{[this](int code) { SkillsAddTypeStringAndCountTypesCase1(code); }}, + {[this](int code) { SkillsAddTypeStringAndCountTypesCase2(code); }}}}, + {static_cast(SkillsApi::AddType_String_MatchType_CountTypes), + {{[this](int code) { SkillsAddTypeStringMatchTypeAndCountTypesCase1(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndCountTypesCase2(code); }}}}, + {static_cast(SkillsApi::AddType_PatternMatcher_CountTypes), + {{[this](int code) { SkillsAddTypePatternAndCountTypesCase1(code); }}, + {[this](int code) { SkillsAddTypePatternAndCountTypesCase2(code); }}}}, + {static_cast(SkillsApi::CountTypes), {{[this](int code) { SkillsCountTypesCase1(code); }}}}, + {static_cast(SkillsApi::AddType_String_GetType), + {{[this](int code) { SkillsAddTypeStringAndGetTypeCase1(code); }}, + {[this](int code) { SkillsAddTypeStringAndGetTypeCase2(code); }}, + {[this](int code) { SkillsAddTypeStringAndGetTypeCase3(code); }}, + {[this](int code) { SkillsAddTypeStringAndGetTypeCase4(code); }}, + {[this](int code) { SkillsAddTypeStringAndGetTypeCase5(code); }}, + {[this](int code) { SkillsAddTypeStringAndGetTypeCase6(code); }}}}, + {static_cast(SkillsApi::AddType_String_MatchType_GetType), + {{[this](int code) { SkillsAddTypeStringMatchTypeAndGetTypeCase1(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndGetTypeCase2(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndGetTypeCase3(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndGetTypeCase4(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndGetTypeCase5(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndGetTypeCase6(code); }}}}, + {static_cast(SkillsApi::AddType_PatternMatcher_GetType), + {{[this](int code) { SkillsAddTypePatternAndGetTypeCase1(code); }}, + {[this](int code) { SkillsAddTypePatternAndGetTypeCase2(code); }}, + {[this](int code) { SkillsAddTypePatternAndGetTypeCase3(code); }}, + {[this](int code) { SkillsAddTypePatternAndGetTypeCase4(code); }}, + {[this](int code) { SkillsAddTypePatternAndGetTypeCase5(code); }}, + {[this](int code) { SkillsAddTypePatternAndGetTypeCase6(code); }}}}, + {static_cast(SkillsApi::GetType), {{[this](int code) { SkillsGetTypeCase1(code); }}}}, + {static_cast(SkillsApi::AddType_String_HasType), + {{[this](int code) { SkillsAddTypeStringAndHasTypeCase1(code); }}, + {[this](int code) { SkillsAddTypeStringAndHasTypeCase2(code); }}}}, + {static_cast(SkillsApi::AddType_String_MatchType_HasType), + {{[this](int code) { SkillsAddTypeStringMatchTypeAndHasTypeCase1(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndHasTypeCase2(code); }}}}, + {static_cast(SkillsApi::AddType_PatternMatcher_HasType), + {{[this](int code) { SkillsAddTypeStringMatchTypeAndHasTypeCase1(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndHasTypeCase2(code); }}}}, + {static_cast(SkillsApi::HasType), {{[this](int code) { SkillsHasTypeCase1(code); }}}}, + {static_cast(SkillsApi::RemoveType_String), + {{[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase1(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase2(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase3(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase4(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase5(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase6(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase7(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase8(code); }}, + {[this](int code) { SkillsAddTypeStringAndRemoveTypeStringCase9(code); }}}}, + {static_cast(SkillsApi::RemoveType_String_MatchType), + {{[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase1(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase2(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase3(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase4(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase5(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase6(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase7(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase8(code); }}, + {[this](int code) { SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase9(code); }}}}, + {static_cast(SkillsApi::RemoveType_PatternMatcher), + {{[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase1(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase2(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase3(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase4(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase5(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase6(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase7(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase8(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypePatternMatcherCase9(code); }}}}, + {static_cast(SkillsApi::RemoveType_Other), + {{[this](int code) { SkillsAddTypePatternAndRemoveTypeCase1(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase2(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase3(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase4(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase5(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase6(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase7(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase8(code); }}, + {[this](int code) { SkillsAddTypePatternAndRemoveTypeCase9(code); }}}}, + {static_cast(SkillsApi::GetEntities), + {{[this](int code) { SkillAddEntityAndGetEntitiesCase1(code); }}, + {[this](int code) { SkillAddEntityAndGetEntitiesCase2(code); }}, + {[this](int code) { SkillAddEntityAndGetEntitiesCase3(code); }}, + {[this](int code) { SkillAddEntityAndGetEntitiesCase4(code); }}, + {[this](int code) { SkillAddEntityAndGetEntitiesCase5(code); }}}}, + {static_cast(SkillsApi::GetWantParams), + {{[this](int code) { SkillSetAndGetWantParamsCase1(code); }}, + {[this](int code) { SkillSetAndGetWantParamsCase2(code); }}, + {[this](int code) { SkillSetAndGetWantParamsCase3(code); }}, + {[this](int code) { SkillSetAndGetWantParamsCase4(code); }}, + {[this](int code) { SkillSetAndGetWantParamsCase5(code); }}}}, + {static_cast(SkillsApi::Match), + {{[this](int code) { SkillMatchCase1(code); }}, + {[this](int code) { SkillMatchCase2(code); }}, + {[this](int code) { SkillMatchCase3(code); }}, + {[this](int code) { SkillMatchCase4(code); }}, + {[this](int code) { SkillMatchCase5(code); }}, + {[this](int code) { SkillMatchCase6(code); }}}}, + {static_cast(SkillsApi::Unmarshalling), + {{[this](int code) { SkillUnmarshallingCase1(code); }}, + {[this](int code) { SkillUnmarshallingCase2(code); }}, + {[this](int code) { SkillUnmarshallingCase3(code); }}, + {[this](int code) { SkillUnmarshallingCase4(code); }}}}, + {static_cast(SkillsApi::Skills), + {{[this](int code) { SkillSkillsCase1(code); }}, + {[this](int code) { SkillSkillsCase2(code); }}, + {[this](int code) { SkillSkillsCase3(code); }}, + {[this](int code) { SkillSkillsCase4(code); }}}}, + {static_cast(SkillsApi::Skills_Skills), + {{[this](int code) { SkillSkillsSkillsCase1(code); }}, + {[this](int code) { SkillSkillsSkillsCase2(code); }}, + {[this](int code) { SkillSkillsSkillsCase3(code); }}, + {[this](int code) { SkillSkillsSkillsCase4(code); }}}}, + {static_cast(SkillsApi::AddAction), {{[this](int code) { SkillAddActionCase1(code); }}}}, + {static_cast(SkillsApi::AddEntity), {{[this](int code) { SkillAddEntityCase1(code); }}}}, + {static_cast(SkillsApi::AddAuthority), {{[this](int code) { SkillAddAuthorityCase1(code); }}}}, + {static_cast(SkillsApi::AddScheme), {{[this](int code) { SkillAddSchemeCase1(code); }}}}, + {static_cast(SkillsApi::AddSchemeSpecificPart), + {{[this](int code) { SkillAddSchemeSpecificPartCase1(code); }}}}, + }; +}; + +class KitTestFourthEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + KitTestFourthEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, FourthAbility *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"SkillsApi", + [this](int apiIndex, int caseIndex, int code) { SkillsApiStByCode(apiIndex, caseIndex, code); }}, + }; + fourthAbility_ = ability; + } + ~KitTestFourthEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + void SkillsApiStByCode(int apiIndex, int caseIndex, int code); + void KitTerminateAbility(); + + FourthAbility *fourthAbility_; + +private: + std::unordered_map> mapTestFunc_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _THIRD_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..87192013740548d04d6a0a505fb5c13417678698 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _KIT_TEST_ABILITY_MANAGER_H_ +#define _KIT_TEST_ABILITY_MANAGER_H_ +#include +#include "ability_loader.h" +#include "running_process_info.h" +#include "ability_manager.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using vector_str = std::vector; +using vector_conststr = std::vector; +using vector_func = std::vector>; +using MAP_STR_STR = std::map; +class KitTestManagerEventSubscriber; +class KitTestAbilityManager : public Ability { +public: + void SubscribeEvent(const vector_conststr &eventList); + void AbilityManagerStByCode(int apiIndex, int caseIndex, int code); + void CompareProcessName(std::vector &info, const std::string &expectedName, int code); + void CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code); + void StartAbilitySelf( + const std::string &bundleName, const std::string &abilityNmae, AbilityManagerApi api, int codeIndex, int code); + void GetAllStackInfo(AAFwk::MissionStackInfo &missionStackInfo, int stackID); + + // GetAllRunningProcesses ST kit case + void AbilityManagerGetAllRunningProcessesCase1(int code); + void AbilityManagerGetAllRunningProcessesCase2(int code); + void AbilityManagerGetAllRunningProcessesCase3(int code); + void AbilityManagerGetAllRunningProcessesCase4(int code); + void AbilityManagerGetAllRunningProcessesCase5(int code); + void AbilityManagerGetAllRunningProcessesCase6(int code); + void AbilityManagerGetAllRunningProcessesCase7(int code); + void AbilityManagerGetAllRunningProcessesCase8(int code); + void AbilityManagerGetAllRunningProcessesCase9(int code); + void AbilityManagerGetAllRunningProcessesCase10(int code); + + // GetAllStackInfo ST kit case + void AbilityManagerGetAllStackInfoCase1(int code); + void AbilityManagerGetAllStackInfoCase2(int code); + void AbilityManagerGetAllStackInfoCase3(int code); + void AbilityManagerGetAllStackInfoCase4(int code); + void AbilityManagerGetAllStackInfoCase5(int code); + void AbilityManagerGetAllStackInfoCase6(int code); + void AbilityManagerGetAllStackInfoCase7(int code); + void AbilityManagerGetAllStackInfoCase8(int code); + void AbilityManagerGetAllStackInfoCase9(int code); + + // QueryRecentAbilityMissionInfo ST kit case + void QueryRecentAbilityMissionInfoParam(int numMax, int code, std::size_t size, int flags); + void AbilityManagerQueryRecentAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase3(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase4(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase5(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase6(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase7(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase8(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase9(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase10(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase11(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase12(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase13(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase14(int code); + + // QueryRunningAbilityMissionInfo ST kit case + void QueryRunningAbilityMissionInfoParam(int numMax, int code, std::size_t size); + void AbilityManagerQueryRunningAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase3(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase4(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase5(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase6(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase7(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase8(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase9(int code); + + // MoveMissionToTop ST kit case + void AbilityManagerMoveMissionToTopCase1(int code); + void AbilityManagerMoveMissionToTopCase2(int code); + + // ClearUpApplicationData ST kit case + void AbilityManagerClearUpApplicationDataCase1(int code); + std::shared_ptr subscriber; + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + std::unordered_map mapStKitFunc_{ + {static_cast(AbilityManagerApi::GetAllRunningProcesses), + {{[this](int code) { AbilityManagerGetAllRunningProcessesCase1(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase2(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase3(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase4(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase5(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase6(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase7(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase8(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase9(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase10(code); }}}}, + {static_cast(AbilityManagerApi::GetAllStackInfo), + {{[this](int code) { AbilityManagerGetAllStackInfoCase1(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase2(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase3(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase4(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase5(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase6(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase7(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase8(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase9(code); }}}}, + {static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase3(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase4(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase5(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase6(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase7(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase8(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase9(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase10(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase11(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase12(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase13(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase14(code); }}}}, + {static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase3(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase4(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase5(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase6(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase7(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase8(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase9(code); }}}}, + {static_cast(AbilityManagerApi::MoveMissionToTop), + {{[this](int code) { AbilityManagerMoveMissionToTopCase1(code); }}, + {[this](int code) { AbilityManagerMoveMissionToTopCase2(code); }}}}, + {static_cast(AbilityManagerApi::ClearUpApplicationData), + {{[this](int code) { AbilityManagerClearUpApplicationDataCase1(code); }}}}}; +}; + +// KitTestManagerEventSubscriber Class +class KitTestManagerEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + KitTestManagerEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, KitTestAbilityManager *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = {{"AbilityManagerApi", + [this](int apiIndex, int caseIndex, int code) { AbilityManagerStByCode(apiIndex, caseIndex, code); }}}; + kitTestAbility_ = ability; + } + ~KitTestManagerEventSubscriber() + { + kitTestAbility_ = nullptr; + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void AbilityManagerStByCode(int apiIndex, int caseIndex, int code); + void KitTerminateAbility(); + +private: + std::unordered_map> mapTestFunc_; + KitTestAbilityManager *kitTestAbility_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_KIT_TEST_ABILITY_MANAGER_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..ec3e1ed23742f4211ec6b87151860cf7d4313888 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_KIT_SYSTEM_TEST_MAIN_ABILITY_H_ +#define _AMS_KIT_SYSTEM_TEST_MAIN_ABILITY_H_ +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" + +namespace OHOS { +namespace AppExecFwk { +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + MainAbility() + { + mapCase_ = { + {(int)AbilityApi::GetAbilityName, + { + [this](int code) { GetAbilityNameCase1(code); }, + }}, + {(int)AbilityApi::GetAbilityPackage, + { + [this](int code) { GetAbilityPackageCase1(code); }, + }}, + {(int)AbilityApi::GetWant, + { + [this](int code) { GetWantCase1(code); }, + [this](int code) { GetWantCase2(code); }, + [this](int code) { GetWantCase3(code); }, + }}, + {(int)AbilityApi::GetWindow, + { + [this](int code) { GetWindowCase1(code); }, + }}, + {(int)AbilityApi::Dump, + { + [this](int code) { DumpCase1(code); }, + }}, + {(int)AbilityApi::SetWant, + { + [this](int code) { SetWantCase1(code); }, + [this](int code) { SetWantCase2(code); }, + }}, + }; + } + ~MainAbility() = default; + + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + void GetAbilityNameCase1(int code); + void GetAbilityPackageCase1(int code); + void GetWantCase1(int code); + void GetWantCase2(int code); + void GetWantCase3(int code); + void GetWindowCase1(int code); + void DumpCase1(int code); + void SetWantCase1(int code); + void SetWantCase2(int code); + + std::unordered_map>> mapCase_; + std::shared_ptr subscriber; + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + virtual void OnBackPressed() override; + virtual void OnNewWant(const Want &want) override; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, MainAbility *ability) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Ability", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = ability; + } + ~FirstEventSubscriber() = default; + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_KIT_SYSTEM_TEST_MAIN_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..385591ba2615eeb89a4438756a7ec7d2b8517d7b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h @@ -0,0 +1,1539 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_KIT_SYSTEM_TEST_SECOND_ABILITY_H_ +#define _AMS_KIT_SYSTEM_TEST_SECOND_ABILITY_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" + +namespace OHOS { +namespace AppExecFwk { +class SecondEventSubscriber; +class SecondAbility : public Ability { +public: + void InsertWantCopyApi() + { + std::vector> funs = { + [this](int code) { WantCopyCase1(code); }, + }; + mapCase_[(int)WantApi::WantCopy] = funs; + } + + void InsertWantAssignApi() + { + std::vector> funs = { + [this](int code) { WantAssignCase1(code); }, + }; + mapCase_[(int)WantApi::WantAssign] = funs; + } + + void InsertAddEntityApi() + { + std::vector> funs = { + [this](int code) { WantAddEntityCase1(code); }, + [this](int code) { WantAddEntityCase2(code); }, + [this](int code) { WantAddEntityCase3(code); }, + }; + mapCase_[(int)WantApi::AddEntity] = funs; + } + + void InsertAddFlagsApi() + { + std::vector> funs = { + [this](int code) { WantAddFlagsCase1(code); }, + [this](int code) { WantAddFlagsCase2(code); }, + [this](int code) { WantAddFlagsCase3(code); }, + }; + mapCase_[(int)WantApi::AddFlags] = funs; + } + + void InsertClearWantApi() + { + std::vector> funs = { + [this](int code) { WantClearWantCase1(code); }, + [this](int code) { WantClearWantCase2(code); }, + }; + mapCase_[(int)WantApi::ClearWant] = funs; + } + + void InsertCountEntitiesApi() + { + std::vector> funs = { + [this](int code) { WantCountEntitiesCase1(code); }, + [this](int code) { WantCountEntitiesCase2(code); }, + }; + mapCase_[(int)WantApi::CountEntities] = funs; + } + + void InsertFormatMimeTypeApi() + { + std::vector> funs = { + [this](int code) { WantFormatMimeTypeCase1(code); }, + [this](int code) { WantFormatMimeTypeCase2(code); }, + [this](int code) { WantFormatMimeTypeCase3(code); }, + [this](int code) { WantFormatMimeTypeCase4(code); }, + }; + mapCase_[(int)WantApi::FormatMimeType] = funs; + } + + void InsertFormatTypeApi() + { + std::vector> funs = { + [this](int code) { WantFormatTypeCase1(code); }, + [this](int code) { WantFormatTypeCase2(code); }, + [this](int code) { WantFormatTypeCase3(code); }, + [this](int code) { WantFormatTypeCase4(code); }, + }; + mapCase_[(int)WantApi::FormatType] = funs; + } + + void InsertFormatUriApi() + { + std::vector> funs = { + [this](int code) { WantFormatUriCase1(code); }, + [this](int code) { WantFormatUriCase2(code); }, + [this](int code) { WantFormatUriCase3(code); }, + [this](int code) { WantFormatUriCase4(code); }, + }; + mapCase_[(int)WantApi::FormatUri] = funs; + } + + void InsertFormatUriAndTypeApi() + { + std::vector> funs = { + [this](int code) { WantFormatUriAndTypeCase1(code); }, + [this](int code) { WantFormatUriAndTypeCase2(code); }, + [this](int code) { WantFormatUriAndTypeCase3(code); }, + [this](int code) { WantFormatUriAndTypeCase4(code); }, + }; + mapCase_[(int)WantApi::FormatUriAndType] = funs; + } + + void InsertGetActionApi() + { + std::vector> funs = { + [this](int code) { WantGetActionCase1(code); }, + [this](int code) { WantGetActionCase2(code); }, + [this](int code) { WantGetActionCase3(code); }, + }; + mapCase_[(int)WantApi::GetAction] = funs; + } + + void InsertGetBundleApi() + { + std::vector> funs = { + [this](int code) { WantGetBundleCase1(code); }, + [this](int code) { WantGetBundleCase2(code); }, + [this](int code) { WantGetBundleCase3(code); }, + }; + mapCase_[(int)WantApi::GetBundle] = funs; + } + + void InsertGetEntitiesApi() + { + std::vector> funs = { + [this](int code) { WantGetEntitiesCase1(code); }, + [this](int code) { WantGetEntitiesCase2(code); }, + [this](int code) { WantGetEntitiesCase3(code); }, + }; + mapCase_[(int)WantApi::GetEntities] = funs; + } + + void InsertGetElementApi() + { + std::vector> funs = { + [this](int code) { WantGetElementCase1(code); }, + [this](int code) { WantGetElementCase2(code); }, + [this](int code) { WantGetElementCase3(code); }, + }; + mapCase_[(int)WantApi::GetElement] = funs; + } + + void InsertGetUriApi() + { + std::vector> funs = { + [this](int code) { WantGetUriCase1(code); }, + [this](int code) { WantGetUriCase2(code); }, + [this](int code) { WantGetUriCase3(code); }, + }; + mapCase_[(int)WantApi::GetUri] = funs; + } + + void InsertGetUriStringApi() + { + std::vector> funs = { + [this](int code) { WantGetUriStringCase1(code); }, + [this](int code) { WantGetUriStringCase2(code); }, + [this](int code) { WantGetUriStringCase3(code); }, + [this](int code) { WantGetUriStringCase4(code); }, + }; + mapCase_[(int)WantApi::GetUriString] = funs; + } + + void InsertGetFlagsApi() + { + std::vector> funs = { + [this](int code) { WantGetFlagsCase1(code); }, + [this](int code) { WantGetFlagsCase2(code); }, + [this](int code) { WantGetFlagsCase3(code); }, + }; + mapCase_[(int)WantApi::GetFlags] = funs; + } + + void InsertGetSchemeApi() + { + std::vector> funs = { + [this](int code) { WantGetSchemeCase1(code); }, + [this](int code) { WantGetSchemeCase2(code); }, + [this](int code) { WantGetSchemeCase3(code); }, + [this](int code) { WantGetSchemeCase4(code); }, + }; + mapCase_[(int)WantApi::GetScheme] = funs; + } + + void InsertGetTypeApi() + { + std::vector> funs = { + [this](int code) { WantGetTypeCase1(code); }, + [this](int code) { WantGetTypeCase2(code); }, + [this](int code) { WantGetTypeCase3(code); }, + }; + mapCase_[(int)WantApi::GetType] = funs; + } + + void InsertHasEntityApi() + { + std::vector> funs = { + [this](int code) { WantHasEntityCase1(code); }, + [this](int code) { WantHasEntityCase2(code); }, + [this](int code) { WantHasEntityCase3(code); }, + [this](int code) { WantHasEntityCase4(code); }, + }; + mapCase_[(int)WantApi::HasEntity] = funs; + } + + void InsertMakeMainAbilityApi() + { + std::vector> funs = { + [this](int code) { WantMakeMainAbilityCase1(code); }, + [this](int code) { WantMakeMainAbilityCase2(code); }, + }; + mapCase_[(int)WantApi::MakeMainAbility] = funs; + } + + void InsertMarshallingApi() + { + std::vector> funs = { + [this](int code) { WantMarshallingCase1(code); }, + [this](int code) { WantMarshallingCase2(code); }, + [this](int code) { WantMarshallingCase3(code); }, + [this](int code) { WantMarshallingCase4(code); }, + [this](int code) { WantMarshallingCase5(code); }, + [this](int code) { WantMarshallingCase6(code); }, + [this](int code) { WantMarshallingCase7(code); }, + [this](int code) { WantMarshallingCase8(code); }, + [this](int code) { WantMarshallingCase9(code); }, + [this](int code) { WantMarshallingCase10(code); }, + [this](int code) { WantMarshallingCase11(code); }, + [this](int code) { WantMarshallingCase12(code); }, + [this](int code) { WantMarshallingCase13(code); }, + [this](int code) { WantMarshallingCase14(code); }, + [this](int code) { WantMarshallingCase15(code); }, + [this](int code) { WantMarshallingCase16(code); }, + [this](int code) { WantMarshallingCase17(code); }, + [this](int code) { WantMarshallingCase18(code); }, + [this](int code) { WantMarshallingCase19(code); }, + [this](int code) { WantMarshallingCase20(code); }, + [this](int code) { WantMarshallingCase21(code); }, + [this](int code) { WantMarshallingCase22(code); }, + [this](int code) { WantMarshallingCase23(code); }, + [this](int code) { WantMarshallingCase24(code); }, + }; + mapCase_[(int)WantApi::Marshalling] = funs; + } + + void InsertParseUriApi() + { + std::vector> funs = { + [this](int code) { WantParseUriCase1(code); }, + [this](int code) { WantParseUriCase2(code); }, + [this](int code) { WantParseUriCase3(code); }, + [this](int code) { WantParseUriCase4(code); }, + [this](int code) { WantParseUriCase5(code); }, + [this](int code) { WantParseUriCase6(code); }, + [this](int code) { WantParseUriCase7(code); }, + [this](int code) { WantParseUriCase8(code); }, + [this](int code) { WantParseUriCase9(code); }, + [this](int code) { WantParseUriCase10(code); }, + [this](int code) { WantParseUriCase11(code); }, + [this](int code) { WantParseUriCase12(code); }, + [this](int code) { WantParseUriCase13(code); }, + [this](int code) { WantParseUriCase14(code); }, + [this](int code) { WantParseUriCase15(code); }, + [this](int code) { WantParseUriCase16(code); }, + [this](int code) { WantParseUriCase17(code); }, + [this](int code) { WantParseUriCase18(code); }, + [this](int code) { WantParseUriCase19(code); }, + [this](int code) { WantParseUriCase20(code); }, + [this](int code) { WantParseUriCase21(code); }, + [this](int code) { WantParseUriCase22(code); }, + [this](int code) { WantParseUriCase23(code); }, + }; + mapCase_[(int)WantApi::ParseUri] = funs; + } + + void InsertRemoveEntityApi() + { + std::vector> funs = { + [this](int code) { WantRemoveEntityCase1(code); }, + [this](int code) { WantRemoveEntityCase2(code); }, + [this](int code) { WantRemoveEntityCase3(code); }, + [this](int code) { WantRemoveEntityCase4(code); }, + [this](int code) { WantRemoveEntityCase5(code); }, + }; + mapCase_[(int)WantApi::RemoveEntity] = funs; + } + + void InsertRemoveFlagsApi() + { + std::vector> funs = { + [this](int code) { WantRemoveFlagsCase1(code); }, + [this](int code) { WantRemoveFlagsCase2(code); }, + [this](int code) { WantRemoveFlagsCase3(code); }, + [this](int code) { WantRemoveFlagsCase4(code); }, + [this](int code) { WantRemoveFlagsCase5(code); }, + }; + mapCase_[(int)WantApi::RemoveFlags] = funs; + } + + void InsertSetActionApi() + { + std::vector> funs = { + [this](int code) { WantSetActionCase1(code); }, + [this](int code) { WantSetActionCase2(code); }, + [this](int code) { WantSetActionCase3(code); }, + [this](int code) { WantSetActionCase4(code); }, + [this](int code) { WantSetActionCase5(code); }, + }; + mapCase_[(int)WantApi::SetAction] = funs; + } + + void InsertSetBundleApi() + { + std::vector> funs = { + [this](int code) { WantSetBundleCase1(code); }, + [this](int code) { WantSetBundleCase2(code); }, + [this](int code) { WantSetBundleCase3(code); }, + [this](int code) { WantSetBundleCase4(code); }, + [this](int code) { WantSetBundleCase5(code); }, + }; + mapCase_[(int)WantApi::SetBundle] = funs; + } + + void InsertSetElementApi() + { + std::vector> funs = { + [this](int code) { WantSetElementCase1(code); }, + [this](int code) { WantSetElementCase2(code); }, + [this](int code) { WantSetElementCase3(code); }, + }; + mapCase_[(int)WantApi::SetElement] = funs; + } + + void InsertSetElementNameStringStringApi() + { + std::vector> funs = { + [this](int code) { WantSetElementNameStringStringCase1(code); }, + [this](int code) { WantSetElementNameStringStringCase2(code); }, + [this](int code) { WantSetElementNameStringStringCase3(code); }, + [this](int code) { WantSetElementNameStringStringCase4(code); }, + [this](int code) { WantSetElementNameStringStringCase5(code); }, + }; + mapCase_[(int)WantApi::SetElementName_String_String] = funs; + } + + void InsertSetElementNameStringStringStringApi() + { + std::vector> funs = { + [this](int code) { WantSetElementNameStringStringStringCase1(code); }, + [this](int code) { WantSetElementNameStringStringStringCase2(code); }, + [this](int code) { WantSetElementNameStringStringStringCase3(code); }, + [this](int code) { WantSetElementNameStringStringStringCase4(code); }, + [this](int code) { WantSetElementNameStringStringStringCase5(code); }, + }; + mapCase_[(int)WantApi::SetElementName_String_String_String] = funs; + } + + void InsertSetFlagsApi() + { + std::vector> funs = { + [this](int code) { WantSetFlagsCase1(code); }, + [this](int code) { WantSetFlagsCase2(code); }, + [this](int code) { WantSetFlagsCase3(code); }, + [this](int code) { WantSetFlagsCase4(code); }, + [this](int code) { WantSetFlagsCase5(code); }, + [this](int code) { WantSetFlagsCase6(code); }, + [this](int code) { WantSetFlagsCase7(code); }, + [this](int code) { WantSetFlagsCase8(code); }, + [this](int code) { WantSetFlagsCase9(code); }, + [this](int code) { WantSetFlagsCase10(code); }, + [this](int code) { WantSetFlagsCase11(code); }, + }; + mapCase_[(int)WantApi::SetFlags] = funs; + } + + void InsertSetTypeApi() + { + std::vector> funs = { + [this](int code) { WantSetTypeCase1(code); }, + [this](int code) { WantSetTypeCase2(code); }, + [this](int code) { WantSetTypeCase3(code); }, + [this](int code) { WantSetTypeCase4(code); }, + }; + mapCase_[(int)WantApi::SetType] = funs; + } + + void InsertSetUriApi() + { + std::vector> funs = { + [this](int code) { WantSetUriCase1(code); }, + [this](int code) { WantSetUriCase2(code); }, + [this](int code) { WantSetUriCase3(code); }, + [this](int code) { WantSetUriCase4(code); }, + }; + mapCase_[(int)WantApi::SetUri] = funs; + } + + void InsertSetUriAndTypeApi() + { + std::vector> funs = { + [this](int code) { WantSetUriAndTypeCase1(code); }, + [this](int code) { WantSetUriAndTypeCase2(code); }, + [this](int code) { WantSetUriAndTypeCase3(code); }, + [this](int code) { WantSetUriAndTypeCase4(code); }, + }; + mapCase_[(int)WantApi::SetUriAndType] = funs; + } + + void InsertToUriApi() + { + std::vector> funs = { + [this](int code) { WantToUriCase1(code); }, + [this](int code) { WantToUriCase2(code); }, + [this](int code) { WantToUriCase3(code); }, + [this](int code) { WantToUriCase4(code); }, + [this](int code) { WantToUriCase5(code); }, + [this](int code) { WantToUriCase6(code); }, + [this](int code) { WantToUriCase7(code); }, + [this](int code) { WantToUriCase8(code); }, + [this](int code) { WantToUriCase9(code); }, + [this](int code) { WantToUriCase10(code); }, + [this](int code) { WantToUriCase11(code); }, + [this](int code) { WantToUriCase12(code); }, + [this](int code) { WantToUriCase13(code); }, + [this](int code) { WantToUriCase14(code); }, + [this](int code) { WantToUriCase15(code); }, + [this](int code) { WantToUriCase16(code); }, + [this](int code) { WantToUriCase17(code); }, + [this](int code) { WantToUriCase18(code); }, + [this](int code) { WantToUriCase19(code); }, + [this](int code) { WantToUriCase20(code); }, + [this](int code) { WantToUriCase21(code); }, + [this](int code) { WantToUriCase22(code); }, + [this](int code) { WantToUriCase23(code); }, + }; + mapCase_[(int)WantApi::ToUri] = funs; + } + + void InsertWantParseUriApi() + { + std::vector> funs = { + [this](int code) { WantWantParseUriCase1(code); }, + [this](int code) { WantWantParseUriCase2(code); }, + [this](int code) { WantWantParseUriCase3(code); }, + }; + mapCase_[(int)WantApi::WantParseUri] = funs; + } + + void InsertGetParamsApi() + { + std::vector> funs = { + [this](int code) { WantGetParamsCase1(code); }, + [this](int code) { WantGetParamsCase2(code); }, + [this](int code) { WantGetParamsCase3(code); }, + }; + mapCase_[(int)WantApi::GetParams] = funs; + } + + void InsertGetByteParamApi() + { + std::vector> funs = { + [this](int code) { WantGetByteParamCase1(code); }, + [this](int code) { WantGetByteParamCase2(code); }, + [this](int code) { WantGetByteParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetByteParam] = funs; + } + + void InsertGetByteArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetByteArrayParamCase1(code); }, + [this](int code) { WantGetByteArrayParamCase2(code); }, + [this](int code) { WantGetByteArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetByteArrayParam] = funs; + } + + void InsertGetBoolParamApi() + { + std::vector> funs = { + [this](int code) { WantGetBoolParamCase1(code); }, + [this](int code) { WantGetBoolParamCase2(code); }, + [this](int code) { WantGetBoolParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetBoolParam] = funs; + } + + void InsertGetBoolArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetBoolArrayParamCase1(code); }, + [this](int code) { WantGetBoolArrayParamCase2(code); }, + [this](int code) { WantGetBoolArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetBoolArrayParam] = funs; + } + + void InsertGetCharParamApi() + { + std::vector> funs = { + [this](int code) { WantGetCharParamCase1(code); }, + [this](int code) { WantGetCharParamCase2(code); }, + [this](int code) { WantGetCharParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetCharParam] = funs; + } + + void InsertGetCharArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetCharArrayParamCase1(code); }, + [this](int code) { WantGetCharArrayParamCase2(code); }, + [this](int code) { WantGetCharArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetCharArrayParam] = funs; + } + + void InsertGetIntParamApi() + { + std::vector> funs = { + [this](int code) { WantGetIntParamCase1(code); }, + [this](int code) { WantGetIntParamCase2(code); }, + [this](int code) { WantGetIntParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetIntParam] = funs; + } + + void InsertGetIntArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetIntArrayParamCase1(code); }, + [this](int code) { WantGetIntArrayParamCase2(code); }, + [this](int code) { WantGetIntArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetIntArrayParam] = funs; + } + + void InsertGetDoubleParamApi() + { + std::vector> funs = { + [this](int code) { WantGetDoubleParamCase1(code); }, + [this](int code) { WantGetDoubleParamCase2(code); }, + [this](int code) { WantGetDoubleParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetDoubleParam] = funs; + } + + void InsertGetDoubleArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetDoubleArrayParamCase1(code); }, + [this](int code) { WantGetDoubleArrayParamCase2(code); }, + [this](int code) { WantGetDoubleArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetDoubleArrayParam] = funs; + } + + void InsertGetFloatParamApi() + { + std::vector> funs = { + [this](int code) { WantGetFloatParamCase1(code); }, + [this](int code) { WantGetFloatParamCase2(code); }, + [this](int code) { WantGetFloatParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetFloatParam] = funs; + } + + void InsertGetFloatArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetFloatArrayParamCase1(code); }, + [this](int code) { WantGetFloatArrayParamCase2(code); }, + [this](int code) { WantGetFloatArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetFloatArrayParam] = funs; + } + + void InsertGetLongParamApi() + { + std::vector> funs = { + [this](int code) { WantGetLongParamCase1(code); }, + [this](int code) { WantGetLongParamCase2(code); }, + [this](int code) { WantGetLongParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetLongParam] = funs; + } + + void InsertGetLongArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetLongArrayParamCase1(code); }, + [this](int code) { WantGetLongArrayParamCase2(code); }, + [this](int code) { WantGetLongArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetLongArrayParam] = funs; + } + + void InsertGetShortParamApi() + { + std::vector> funs = { + [this](int code) { WantGetShortParamCase1(code); }, + [this](int code) { WantGetShortParamCase2(code); }, + [this](int code) { WantGetShortParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetShortParam] = funs; + } + + void InsertGetShortArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetShortArrayParamCase1(code); }, + [this](int code) { WantGetShortArrayParamCase2(code); }, + [this](int code) { WantGetShortArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetShortArrayParam] = funs; + } + + void InsertGetStringParamApi() + { + std::vector> funs = { + [this](int code) { WantGetStringParamCase1(code); }, + [this](int code) { WantGetStringParamCase2(code); }, + [this](int code) { WantGetStringParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetStringParam] = funs; + } + + void InsertGetStringArrayParamApi() + { + std::vector> funs = { + [this](int code) { WantGetStringArrayParamCase1(code); }, + [this](int code) { WantGetStringArrayParamCase2(code); }, + [this](int code) { WantGetStringArrayParamCase3(code); }, + }; + mapCase_[(int)WantApi::GetStringArrayParam] = funs; + } + + void InsertSetParamByteApi() + { + std::vector> funs = { + [this](int code) { WantSetParamByteCase1(code); }, + [this](int code) { WantSetParamByteCase2(code); }, + [this](int code) { WantSetParamByteCase3(code); }, + [this](int code) { WantSetParamByteCase4(code); }, + [this](int code) { WantSetParamByteCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_byte] = funs; + } + + void InsertSetParamByteArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamByteArrayCase1(code); }, + [this](int code) { WantSetParamByteArrayCase2(code); }, + [this](int code) { WantSetParamByteArrayCase3(code); }, + [this](int code) { WantSetParamByteArrayCase4(code); }, + [this](int code) { WantSetParamByteArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_byte_array] = funs; + } + + void InsertSetParamBoolApi() + { + std::vector> funs = { + [this](int code) { WantSetParamBoolCase1(code); }, + [this](int code) { WantSetParamBoolCase2(code); }, + [this](int code) { WantSetParamBoolCase3(code); }, + [this](int code) { WantSetParamBoolCase4(code); }, + [this](int code) { WantSetParamBoolCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_bool] = funs; + } + + void InsertSetParamBoolArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamBoolArrayCase1(code); }, + [this](int code) { WantSetParamBoolArrayCase2(code); }, + [this](int code) { WantSetParamBoolArrayCase3(code); }, + [this](int code) { WantSetParamBoolArrayCase4(code); }, + [this](int code) { WantSetParamBoolArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_bool_array] = funs; + } + + void InsertSetParamCharApi() + { + std::vector> funs = { + [this](int code) { WantSetParamCharCase1(code); }, + [this](int code) { WantSetParamCharCase2(code); }, + [this](int code) { WantSetParamCharCase3(code); }, + [this](int code) { WantSetParamCharCase4(code); }, + [this](int code) { WantSetParamCharCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_char] = funs; + } + + void InsertSetParamCharArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamCharArrayCase1(code); }, + [this](int code) { WantSetParamCharArrayCase2(code); }, + [this](int code) { WantSetParamCharArrayCase3(code); }, + [this](int code) { WantSetParamCharArrayCase4(code); }, + [this](int code) { WantSetParamCharArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_char_array] = funs; + } + + void InsertSetParamIntApi() + { + std::vector> funs = { + [this](int code) { WantSetParamIntCase1(code); }, + [this](int code) { WantSetParamIntCase2(code); }, + [this](int code) { WantSetParamIntCase3(code); }, + [this](int code) { WantSetParamIntCase4(code); }, + [this](int code) { WantSetParamIntCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_int] = funs; + } + + void InsertSetParamIntArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamIntArrayCase1(code); }, + [this](int code) { WantSetParamIntArrayCase2(code); }, + [this](int code) { WantSetParamIntArrayCase3(code); }, + [this](int code) { WantSetParamIntArrayCase4(code); }, + [this](int code) { WantSetParamIntArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_int_array] = funs; + } + + void InsertSetParamDoubleApi() + { + std::vector> funs = { + [this](int code) { WantSetParamDoubleCase1(code); }, + [this](int code) { WantSetParamDoubleCase2(code); }, + [this](int code) { WantSetParamDoubleCase3(code); }, + [this](int code) { WantSetParamDoubleCase4(code); }, + [this](int code) { WantSetParamDoubleCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_double] = funs; + } + + void InsertSetParamDoubleArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamDoubleArrayCase1(code); }, + [this](int code) { WantSetParamDoubleArrayCase2(code); }, + [this](int code) { WantSetParamDoubleArrayCase3(code); }, + [this](int code) { WantSetParamDoubleArrayCase4(code); }, + [this](int code) { WantSetParamDoubleArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_double_array] = funs; + } + + void InsertSetParamFloatApi() + { + std::vector> funs = { + [this](int code) { WantSetParamFloatCase1(code); }, + [this](int code) { WantSetParamFloatCase2(code); }, + [this](int code) { WantSetParamFloatCase3(code); }, + [this](int code) { WantSetParamFloatCase4(code); }, + [this](int code) { WantSetParamFloatCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_float] = funs; + } + + void InsertSetParamFloatArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamFloatArrayCase1(code); }, + [this](int code) { WantSetParamFloatArrayCase2(code); }, + [this](int code) { WantSetParamFloatArrayCase3(code); }, + [this](int code) { WantSetParamFloatArrayCase4(code); }, + [this](int code) { WantSetParamFloatArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_float_array] = funs; + } + + void InsertSetParamLongApi() + { + std::vector> funs = { + [this](int code) { WantSetParamLongCase1(code); }, + [this](int code) { WantSetParamLongCase2(code); }, + [this](int code) { WantSetParamLongCase3(code); }, + [this](int code) { WantSetParamLongCase4(code); }, + [this](int code) { WantSetParamLongCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_long] = funs; + } + + void InsertSetParamLongArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamLongArrayCase1(code); }, + [this](int code) { WantSetParamLongArrayCase2(code); }, + [this](int code) { WantSetParamLongArrayCase3(code); }, + [this](int code) { WantSetParamLongArrayCase4(code); }, + [this](int code) { WantSetParamLongArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_long_array] = funs; + } + + void InsertSetParamShortApi() + { + std::vector> funs = { + [this](int code) { WantSetParamShortCase1(code); }, + [this](int code) { WantSetParamShortCase2(code); }, + [this](int code) { WantSetParamShortCase3(code); }, + [this](int code) { WantSetParamShortCase4(code); }, + [this](int code) { WantSetParamShortCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_short] = funs; + } + + void InsertSetParamShortArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamShortArrayCase1(code); }, + [this](int code) { WantSetParamShortArrayCase2(code); }, + [this](int code) { WantSetParamShortArrayCase3(code); }, + [this](int code) { WantSetParamShortArrayCase4(code); }, + [this](int code) { WantSetParamShortArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_short_array] = funs; + } + + void InsertSetParamStringApi() + { + std::vector> funs = { + [this](int code) { WantSetParamStringCase1(code); }, + [this](int code) { WantSetParamStringCase2(code); }, + [this](int code) { WantSetParamStringCase3(code); }, + [this](int code) { WantSetParamStringCase4(code); }, + [this](int code) { WantSetParamStringCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_string] = funs; + } + + void InsertSetParamStringArrayApi() + { + std::vector> funs = { + [this](int code) { WantSetParamStringArrayCase1(code); }, + [this](int code) { WantSetParamStringArrayCase2(code); }, + [this](int code) { WantSetParamStringArrayCase3(code); }, + [this](int code) { WantSetParamStringArrayCase4(code); }, + [this](int code) { WantSetParamStringArrayCase5(code); }, + }; + mapCase_[(int)WantApi::SetParam_string_array] = funs; + } + + void InsertHasParameterApi() + { + std::vector> funs = { + [this](int code) { WantHasParameterCase1(code); }, + [this](int code) { WantHasParameterCase2(code); }, + [this](int code) { WantHasParameterCase3(code); }, + [this](int code) { WantHasParameterCase4(code); }, + [this](int code) { WantHasParameterCase5(code); }, + }; + mapCase_[(int)WantApi::HasParameter] = funs; + } + + void InsertReplaceParamsWantParamsApi() + { + std::vector> funs = { + [this](int code) { WantReplaceParamsWantParamsCase1(code); }, + [this](int code) { WantReplaceParamsWantParamsCase2(code); }, + [this](int code) { WantReplaceParamsWantParamsCase3(code); }, + [this](int code) { WantReplaceParamsWantParamsCase4(code); }, + [this](int code) { WantReplaceParamsWantParamsCase5(code); }, + }; + mapCase_[(int)WantApi::ReplaceParams_WantParams] = funs; + } + + void InsertReplaceParamsWantApi() + { + std::vector> funs = { + [this](int code) { WantReplaceParamsWantCase1(code); }, + [this](int code) { WantReplaceParamsWantCase2(code); }, + [this](int code) { WantReplaceParamsWantCase3(code); }, + [this](int code) { WantReplaceParamsWantCase4(code); }, + [this](int code) { WantReplaceParamsWantCase5(code); }, + }; + mapCase_[(int)WantApi::ReplaceParams_Want] = funs; + } + + void InsertRemoveParamApi() + { + std::vector> funs = { + [this](int code) { WantRemoveParamCase1(code); }, + [this](int code) { WantRemoveParamCase2(code); }, + [this](int code) { WantRemoveParamCase3(code); }, + }; + mapCase_[(int)WantApi::RemoveParam] = funs; + } + + void InsertGetOperationApi() + { + std::vector> funs = { + [this](int code) { WantGetOperationCase1(code); }, + [this](int code) { WantGetOperationCase2(code); }, + [this](int code) { WantGetOperationCase3(code); }, + }; + mapCase_[(int)WantApi::GetOperation] = funs; + } + + void InsertOperationEqualsApi() + { + std::vector> funs = { + [this](int code) { WantOperationEqualsCase1(code); }, + [this](int code) { WantOperationEqualsCase2(code); }, + [this](int code) { WantOperationEqualsCase3(code); }, + [this](int code) { WantOperationEqualsCase4(code); }, + }; + mapCase_[(int)WantApi::OperationEquals] = funs; + } + + void InsertCloneOperationApi() + { + std::vector> funs = { + [this](int code) { WantCloneOperationCase1(code); }, + [this](int code) { WantCloneOperationCase2(code); }, + [this](int code) { WantCloneOperationCase3(code); }, + }; + mapCase_[(int)WantApi::CloneOperation] = funs; + } + + SecondAbility() + { + InitData(); + InitDataAgain(); + } + + void InitData() + { + InsertWantCopyApi(); + InsertWantAssignApi(); + InsertAddEntityApi(); + InsertAddFlagsApi(); + InsertClearWantApi(); + InsertCountEntitiesApi(); + InsertFormatMimeTypeApi(); + InsertFormatTypeApi(); + InsertFormatUriApi(); + InsertFormatUriAndTypeApi(); + InsertGetActionApi(); + InsertGetBundleApi(); + InsertGetEntitiesApi(); + InsertGetElementApi(); + InsertGetUriApi(); + InsertGetUriStringApi(); + InsertGetFlagsApi(); + InsertGetSchemeApi(); + InsertGetTypeApi(); + InsertHasEntityApi(); + InsertMakeMainAbilityApi(); + InsertMarshallingApi(); + InsertParseUriApi(); + InsertRemoveEntityApi(); + InsertRemoveFlagsApi(); + InsertSetActionApi(); + InsertSetBundleApi(); + InsertSetElementApi(); + InsertSetElementNameStringStringApi(); + InsertSetElementNameStringStringStringApi(); + InsertSetFlagsApi(); + InsertSetTypeApi(); + InsertSetUriApi(); + InsertSetUriAndTypeApi(); + InsertToUriApi(); + InsertWantParseUriApi(); + InsertGetParamsApi(); + InsertGetByteParamApi(); + InsertGetByteArrayParamApi(); + InsertGetBoolParamApi(); + InsertGetBoolArrayParamApi(); + InsertGetCharParamApi(); + InsertGetCharArrayParamApi(); + InsertGetIntParamApi(); + InsertGetIntArrayParamApi(); + } + + void InitDataAgain() + { + InsertGetDoubleParamApi(); + InsertGetDoubleArrayParamApi(); + InsertGetFloatParamApi(); + InsertGetFloatArrayParamApi(); + InsertGetLongParamApi(); + InsertGetLongArrayParamApi(); + InsertGetShortParamApi(); + InsertGetShortArrayParamApi(); + InsertGetStringParamApi(); + InsertGetStringArrayParamApi(); + InsertSetParamByteApi(); + InsertSetParamByteArrayApi(); + InsertSetParamBoolApi(); + InsertSetParamBoolArrayApi(); + InsertSetParamCharApi(); + InsertSetParamCharArrayApi(); + InsertSetParamIntApi(); + InsertSetParamIntArrayApi(); + InsertSetParamDoubleApi(); + InsertSetParamDoubleArrayApi(); + InsertSetParamFloatApi(); + InsertSetParamFloatArrayApi(); + InsertSetParamLongApi(); + InsertSetParamLongArrayApi(); + InsertSetParamShortApi(); + InsertSetParamShortArrayApi(); + InsertSetParamStringApi(); + InsertSetParamStringArrayApi(); + InsertHasParameterApi(); + InsertReplaceParamsWantParamsApi(); + InsertReplaceParamsWantApi(); + InsertRemoveParamApi(); + InsertGetOperationApi(); + InsertOperationEqualsApi(); + InsertCloneOperationApi(); + } + + virtual ~SecondAbility() = default; + void SubscribeEvent(); + void TestWant(int apiIndex, int caseIndex, int code); + bool CompareWantNoParams(const Want &source, const Want &target); + + void WantCopyCase1(int code); + void WantAssignCase1(int code); + + void WantAddEntityCase1(int code); + void WantAddEntityCase2(int code); + void WantAddEntityCase3(int code); + + void WantAddFlagsCase1(int code); + void WantAddFlagsCase2(int code); + void WantAddFlagsCase3(int code); + + void WantClearWantCase1(int code); + void WantClearWantCase2(int code); + + void WantCountEntitiesCase1(int code); + void WantCountEntitiesCase2(int code); + + void WantFormatMimeTypeCase1(int code); + void WantFormatMimeTypeCase2(int code); + void WantFormatMimeTypeCase3(int code); + void WantFormatMimeTypeCase4(int code); + + void WantFormatTypeCase1(int code); + void WantFormatTypeCase2(int code); + void WantFormatTypeCase3(int code); + void WantFormatTypeCase4(int code); + + void WantParseUriCase1(int code); + void WantParseUriCase2(int code); + void WantParseUriCase3(int code); + void WantParseUriCase4(int code); + void WantParseUriCase5(int code); + void WantParseUriCase6(int code); + void WantParseUriCase7(int code); + void WantParseUriCase8(int code); + void WantParseUriCase9(int code); + void WantParseUriCase10(int code); + void WantParseUriCase11(int code); + void WantParseUriCase12(int code); + void WantParseUriCase13(int code); + void WantParseUriCase14(int code); + void WantParseUriCase15(int code); + void WantParseUriCase16(int code); + void WantParseUriCase17(int code); + void WantParseUriCase18(int code); + void WantParseUriCase19(int code); + void WantParseUriCase20(int code); + void WantParseUriCase21(int code); + void WantParseUriCase22(int code); + void WantParseUriCase23(int code); + + void WantFormatUriCase1(int code); + void WantFormatUriCase2(int code); + void WantFormatUriCase3(int code); + void WantFormatUriCase4(int code); + + void WantFormatUriAndTypeCase1(int code); + void WantFormatUriAndTypeCase2(int code); + void WantFormatUriAndTypeCase3(int code); + void WantFormatUriAndTypeCase4(int code); + + void WantGetActionCase1(int code); + void WantGetActionCase2(int code); + void WantGetActionCase3(int code); + + void WantGetBundleCase1(int code); + void WantGetBundleCase2(int code); + void WantGetBundleCase3(int code); + + void WantGetEntitiesCase1(int code); + void WantGetEntitiesCase2(int code); + void WantGetEntitiesCase3(int code); + + void WantGetElementCase1(int code); + void WantGetElementCase2(int code); + void WantGetElementCase3(int code); + + void WantGetUriCase1(int code); + void WantGetUriCase2(int code); + void WantGetUriCase3(int code); + + void WantGetUriStringCase1(int code); + void WantGetUriStringCase2(int code); + void WantGetUriStringCase3(int code); + void WantGetUriStringCase4(int code); + + void WantGetFlagsCase1(int code); + void WantGetFlagsCase2(int code); + void WantGetFlagsCase3(int code); + + void WantGetSchemeCase1(int code); + void WantGetSchemeCase2(int code); + void WantGetSchemeCase3(int code); + void WantGetSchemeCase4(int code); + + void WantGetTypeCase1(int code); + void WantGetTypeCase2(int code); + void WantGetTypeCase3(int code); + + void WantHasEntityCase1(int code); + void WantHasEntityCase2(int code); + void WantHasEntityCase3(int code); + void WantHasEntityCase4(int code); + + void WantMakeMainAbilityCase1(int code); + void WantMakeMainAbilityCase2(int code); + + void WantMarshallingCase1(int code); + void WantMarshallingCase2(int code); + void WantMarshallingCase3(int code); + void WantMarshallingCase4(int code); + void WantMarshallingCase5(int code); + void WantMarshallingCase6(int code); + void WantMarshallingCase7(int code); + void WantMarshallingCase8(int code); + void WantMarshallingCase9(int code); + void WantMarshallingCase10(int code); + void WantMarshallingCase11(int code); + void WantMarshallingCase12(int code); + void WantMarshallingCase13(int code); + void WantMarshallingCase14(int code); + void WantMarshallingCase15(int code); + void WantMarshallingCase16(int code); + void WantMarshallingCase17(int code); + void WantMarshallingCase18(int code); + void WantMarshallingCase19(int code); + void WantMarshallingCase20(int code); + void WantMarshallingCase21(int code); + void WantMarshallingCase22(int code); + void WantMarshallingCase23(int code); + void WantMarshallingCase24(int code); + + void WantRemoveEntityCase1(int code); + void WantRemoveEntityCase2(int code); + void WantRemoveEntityCase3(int code); + void WantRemoveEntityCase4(int code); + void WantRemoveEntityCase5(int code); + + void WantRemoveFlagsCase1(int code); + void WantRemoveFlagsCase2(int code); + void WantRemoveFlagsCase3(int code); + void WantRemoveFlagsCase4(int code); + void WantRemoveFlagsCase5(int code); + + void WantSetActionCase1(int code); + void WantSetActionCase2(int code); + void WantSetActionCase3(int code); + void WantSetActionCase4(int code); + void WantSetActionCase5(int code); + + void WantSetBundleCase1(int code); + void WantSetBundleCase2(int code); + void WantSetBundleCase3(int code); + void WantSetBundleCase4(int code); + void WantSetBundleCase5(int code); + + void WantSetElementCase1(int code); + void WantSetElementCase2(int code); + void WantSetElementCase3(int code); + + void WantSetElementNameStringStringCase1(int code); + void WantSetElementNameStringStringCase2(int code); + void WantSetElementNameStringStringCase3(int code); + void WantSetElementNameStringStringCase4(int code); + void WantSetElementNameStringStringCase5(int code); + + void WantSetElementNameStringStringStringCase1(int code); + void WantSetElementNameStringStringStringCase2(int code); + void WantSetElementNameStringStringStringCase3(int code); + void WantSetElementNameStringStringStringCase4(int code); + void WantSetElementNameStringStringStringCase5(int code); + + void WantSetFlagsCase1(int code); + void WantSetFlagsCase2(int code); + void WantSetFlagsCase3(int code); + void WantSetFlagsCase4(int code); + void WantSetFlagsCase5(int code); + void WantSetFlagsCase6(int code); + void WantSetFlagsCase7(int code); + void WantSetFlagsCase8(int code); + void WantSetFlagsCase9(int code); + void WantSetFlagsCase10(int code); + void WantSetFlagsCase11(int code); + + void WantSetTypeCase1(int code); + void WantSetTypeCase2(int code); + void WantSetTypeCase3(int code); + void WantSetTypeCase4(int code); + + void WantSetUriCase1(int code); + void WantSetUriCase2(int code); + void WantSetUriCase3(int code); + void WantSetUriCase4(int code); + + void WantSetUriAndTypeCase1(int code); + void WantSetUriAndTypeCase2(int code); + void WantSetUriAndTypeCase3(int code); + void WantSetUriAndTypeCase4(int code); + + void WantToUriCase1(int code); + void WantToUriCase2(int code); + void WantToUriCase3(int code); + void WantToUriCase4(int code); + void WantToUriCase5(int code); + void WantToUriCase6(int code); + void WantToUriCase7(int code); + void WantToUriCase8(int code); + void WantToUriCase9(int code); + void WantToUriCase10(int code); + void WantToUriCase11(int code); + void WantToUriCase12(int code); + void WantToUriCase13(int code); + void WantToUriCase14(int code); + void WantToUriCase15(int code); + void WantToUriCase16(int code); + void WantToUriCase17(int code); + void WantToUriCase18(int code); + void WantToUriCase19(int code); + void WantToUriCase20(int code); + void WantToUriCase21(int code); + void WantToUriCase22(int code); + void WantToUriCase23(int code); + + void WantWantParseUriCase1(int code); + void WantWantParseUriCase2(int code); + void WantWantParseUriCase3(int code); + + void WantGetParamsCase1(int code); + void WantGetParamsCase2(int code); + void WantGetParamsCase3(int code); + + void WantGetByteParamCase1(int code); + void WantGetByteParamCase2(int code); + void WantGetByteParamCase3(int code); + + void WantGetByteArrayParamCase1(int code); + void WantGetByteArrayParamCase2(int code); + void WantGetByteArrayParamCase3(int code); + + void WantGetBoolParamCase1(int code); + void WantGetBoolParamCase2(int code); + void WantGetBoolParamCase3(int code); + + void WantGetBoolArrayParamCase1(int code); + void WantGetBoolArrayParamCase2(int code); + void WantGetBoolArrayParamCase3(int code); + + void WantGetCharParamCase1(int code); + void WantGetCharParamCase2(int code); + void WantGetCharParamCase3(int code); + + void WantGetCharArrayParamCase1(int code); + void WantGetCharArrayParamCase2(int code); + void WantGetCharArrayParamCase3(int code); + + void WantGetIntParamCase1(int code); + void WantGetIntParamCase2(int code); + void WantGetIntParamCase3(int code); + + void WantGetIntArrayParamCase1(int code); + void WantGetIntArrayParamCase2(int code); + void WantGetIntArrayParamCase3(int code); + + void WantGetDoubleParamCase1(int code); + void WantGetDoubleParamCase2(int code); + void WantGetDoubleParamCase3(int code); + + void WantGetDoubleArrayParamCase1(int code); + void WantGetDoubleArrayParamCase2(int code); + void WantGetDoubleArrayParamCase3(int code); + + void WantGetFloatParamCase1(int code); + void WantGetFloatParamCase2(int code); + void WantGetFloatParamCase3(int code); + + void WantGetFloatArrayParamCase1(int code); + void WantGetFloatArrayParamCase2(int code); + void WantGetFloatArrayParamCase3(int code); + + void WantGetLongParamCase1(int code); + void WantGetLongParamCase2(int code); + void WantGetLongParamCase3(int code); + + void WantGetLongArrayParamCase1(int code); + void WantGetLongArrayParamCase2(int code); + void WantGetLongArrayParamCase3(int code); + + void WantGetShortParamCase1(int code); + void WantGetShortParamCase2(int code); + void WantGetShortParamCase3(int code); + + void WantGetShortArrayParamCase1(int code); + void WantGetShortArrayParamCase2(int code); + void WantGetShortArrayParamCase3(int code); + + void WantGetStringParamCase1(int code); + void WantGetStringParamCase2(int code); + void WantGetStringParamCase3(int code); + + void WantGetStringArrayParamCase1(int code); + void WantGetStringArrayParamCase2(int code); + void WantGetStringArrayParamCase3(int code); + + void WantSetParamByteCase1(int code); + void WantSetParamByteCase2(int code); + void WantSetParamByteCase3(int code); + void WantSetParamByteCase4(int code); + void WantSetParamByteCase5(int code); + + void WantSetParamByteArrayCase1(int code); + void WantSetParamByteArrayCase2(int code); + void WantSetParamByteArrayCase3(int code); + void WantSetParamByteArrayCase4(int code); + void WantSetParamByteArrayCase5(int code); + + void WantSetParamBoolCase1(int code); + void WantSetParamBoolCase2(int code); + void WantSetParamBoolCase3(int code); + void WantSetParamBoolCase4(int code); + void WantSetParamBoolCase5(int code); + + void WantSetParamBoolArrayCase1(int code); + void WantSetParamBoolArrayCase2(int code); + void WantSetParamBoolArrayCase3(int code); + void WantSetParamBoolArrayCase4(int code); + void WantSetParamBoolArrayCase5(int code); + + void WantSetParamCharCase1(int code); + void WantSetParamCharCase2(int code); + void WantSetParamCharCase3(int code); + void WantSetParamCharCase4(int code); + void WantSetParamCharCase5(int code); + + void WantSetParamCharArrayCase1(int code); + void WantSetParamCharArrayCase2(int code); + void WantSetParamCharArrayCase3(int code); + void WantSetParamCharArrayCase4(int code); + void WantSetParamCharArrayCase5(int code); + + void WantSetParamIntCase1(int code); + void WantSetParamIntCase2(int code); + void WantSetParamIntCase3(int code); + void WantSetParamIntCase4(int code); + void WantSetParamIntCase5(int code); + + void WantSetParamIntArrayCase1(int code); + void WantSetParamIntArrayCase2(int code); + void WantSetParamIntArrayCase3(int code); + void WantSetParamIntArrayCase4(int code); + void WantSetParamIntArrayCase5(int code); + + void WantSetParamDoubleCase1(int code); + void WantSetParamDoubleCase2(int code); + void WantSetParamDoubleCase3(int code); + void WantSetParamDoubleCase4(int code); + void WantSetParamDoubleCase5(int code); + + void WantSetParamDoubleArrayCase1(int code); + void WantSetParamDoubleArrayCase2(int code); + void WantSetParamDoubleArrayCase3(int code); + void WantSetParamDoubleArrayCase4(int code); + void WantSetParamDoubleArrayCase5(int code); + + void WantSetParamFloatCase1(int code); + void WantSetParamFloatCase2(int code); + void WantSetParamFloatCase3(int code); + void WantSetParamFloatCase4(int code); + void WantSetParamFloatCase5(int code); + + void WantSetParamFloatArrayCase1(int code); + void WantSetParamFloatArrayCase2(int code); + void WantSetParamFloatArrayCase3(int code); + void WantSetParamFloatArrayCase4(int code); + void WantSetParamFloatArrayCase5(int code); + + void WantSetParamLongCase1(int code); + void WantSetParamLongCase2(int code); + void WantSetParamLongCase3(int code); + void WantSetParamLongCase4(int code); + void WantSetParamLongCase5(int code); + + void WantSetParamLongArrayCase1(int code); + void WantSetParamLongArrayCase2(int code); + void WantSetParamLongArrayCase3(int code); + void WantSetParamLongArrayCase4(int code); + void WantSetParamLongArrayCase5(int code); + + void WantSetParamShortCase1(int code); + void WantSetParamShortCase2(int code); + void WantSetParamShortCase3(int code); + void WantSetParamShortCase4(int code); + void WantSetParamShortCase5(int code); + + void WantSetParamShortArrayCase1(int code); + void WantSetParamShortArrayCase2(int code); + void WantSetParamShortArrayCase3(int code); + void WantSetParamShortArrayCase4(int code); + void WantSetParamShortArrayCase5(int code); + + void WantSetParamStringCase1(int code); + void WantSetParamStringCase2(int code); + void WantSetParamStringCase3(int code); + void WantSetParamStringCase4(int code); + void WantSetParamStringCase5(int code); + + void WantSetParamStringArrayCase1(int code); + void WantSetParamStringArrayCase2(int code); + void WantSetParamStringArrayCase3(int code); + void WantSetParamStringArrayCase4(int code); + void WantSetParamStringArrayCase5(int code); + + void WantHasParameterCase1(int code); + void WantHasParameterCase2(int code); + void WantHasParameterCase3(int code); + void WantHasParameterCase4(int code); + void WantHasParameterCase5(int code); + + void WantReplaceParamsWantParamsCase1(int code); + void WantReplaceParamsWantParamsCase2(int code); + void WantReplaceParamsWantParamsCase3(int code); + void WantReplaceParamsWantParamsCase4(int code); + void WantReplaceParamsWantParamsCase5(int code); + + void WantReplaceParamsWantCase1(int code); + void WantReplaceParamsWantCase2(int code); + void WantReplaceParamsWantCase3(int code); + void WantReplaceParamsWantCase4(int code); + void WantReplaceParamsWantCase5(int code); + + void WantRemoveParamCase1(int code); + void WantRemoveParamCase2(int code); + void WantRemoveParamCase3(int code); + + void WantGetOperationCase1(int code); + void WantGetOperationCase2(int code); + void WantGetOperationCase3(int code); + + void WantOperationEqualsCase1(int code); + void WantOperationEqualsCase2(int code); + void WantOperationEqualsCase3(int code); + void WantOperationEqualsCase4(int code); + + void WantCloneOperationCase1(int code); + void WantCloneOperationCase2(int code); + void WantCloneOperationCase3(int code); + + std::unordered_map>> mapCase_; + std::shared_ptr subscriber; + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + virtual void OnBackPressed() override; + virtual void OnNewWant(const Want &want) override; +}; + +class SecondEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { +public: + SecondEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &sp, SecondAbility *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Want", [this](int apiIndex, int caseIndex, int code) { TestWant(apiIndex, caseIndex, code); }}, + }; + secondAbility = ability; + } + ~SecondEventSubscriber() = default; + void TestWant(int apiIndex, int caseIndex, int code) + { + secondAbility->TestWant(apiIndex, caseIndex, code); + } + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data); + + SecondAbility *secondAbility; + std::unordered_map> mapTestFunc_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_KIT_SYSTEM_TEST_SECOND_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..cf145f0a098b859321a56fff020026d90eafd9bd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _Six_ABILITY_H_ +#define _Six_ABILITY_H_ +#include +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" +#include "process_info.h" + +namespace OHOS { +namespace AppExecFwk { +using vector_str = std::vector; +using vector_conststr = std::vector; +using vector_func = std::vector>; +class KitTestSixEventSubscriber; + +class SixthAbility : public Ability { +public: + void SubscribeEvent(const vector_conststr &eventList); + void ApplicationStByCode(int apiIndex, int caseIndex, int code); + // RegisterAbilityLifecycleCallbacks ST case + void SkillRegisterAbilityLifecycleCallbacksCase1(int code); + void SkillRegisterAbilityLifecycleCallbacksCase2(int code); + void SkillRegisterAbilityLifecycleCallbacksCase3(int code); + void SkillRegisterAbilityLifecycleCallbacksCase4(int code); + void SkillRegisterAbilityLifecycleCallbacksCase5(int code); + void SkillRegisterAbilityLifecycleCallbacksCase6(int code); + void SkillRegisterAbilityLifecycleCallbacksCase7(int code); + void SkillRegisterAbilityLifecycleCallbacksCase8(int code); + + // UnregisterAbilityLifecycleCallbacks + void SkillUnregisterAbilityLifecycleCallbacksCase1(int code); + void SkillUnregisterAbilityLifecycleCallbacksCase2(int code); + void SkillUnregisterAbilityLifecycleCallbacksCase3(int code); + void SkillUnregisterAbilityLifecycleCallbacksCase4(int code); + void SkillUnregisterAbilityLifecycleCallbacksCase5(int code); + void SkillUnregisterAbilityLifecycleCallbacksCase6(int code); + void SkillUnregisterAbilityLifecycleCallbacksCase7(int code); + void SkillUnregisterAbilityLifecycleCallbacksCase8(int code); + + // DispatchAbilitySavedState ST case + void SkillDispatchAbilitySavedStateCase1(int code); + void SkillDispatchAbilitySavedStateCase2(int code); + + // RegisterElementsCallbacks + void SkillRegisterElementsCallbacksCase1(int code); + void SkillRegisterElementsCallbacksCase2(int code); + void SkillRegisterElementsCallbacksCase3(int code); + void SkillRegisterElementsCallbacksCase4(int code); + + // UnregisterElementsCallbacks + void SkillUnregisterElementsCallbacksCase1(int code); + void SkillUnregisterElementsCallbacksCase2(int code); + void SkillUnregisterElementsCallbacksCase3(int code); + void SkillUnregisterElementsCallbacksCase4(int code); + + std::shared_ptr subscriber; + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn_; + std::string targetBundle_; + std::string targetAbility_; + std::unordered_map mapStKitFunc_ = { + {static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks), + {{[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase1(code); }}, + {[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase2(code); }}, + {[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase3(code); }}, + {[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase4(code); }}, + {[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase5(code); }}, + {[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase6(code); }}, + {[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase7(code); }}, + {[this](int code) { SkillRegisterAbilityLifecycleCallbacksCase8(code); }}}}, + {static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks), + {{[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase1(code); }}, + {[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase2(code); }}, + {[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase3(code); }}, + {[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase4(code); }}, + {[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase5(code); }}, + {[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase6(code); }}, + {[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase7(code); }}, + {[this](int code) { SkillUnregisterAbilityLifecycleCallbacksCase8(code); }}}}, + {static_cast(OHOSApplicationApi::DispatchAbilitySavedState), + {{[this](int code) { SkillDispatchAbilitySavedStateCase1(code); }}, + {[this](int code) { SkillDispatchAbilitySavedStateCase2(code); }}}}, + {static_cast(OHOSApplicationApi::RegisterElementsCallbacks), + {{[this](int code) { SkillRegisterElementsCallbacksCase1(code); }}, + {[this](int code) { SkillRegisterElementsCallbacksCase2(code); }}, + {[this](int code) { SkillRegisterElementsCallbacksCase3(code); }}, + {[this](int code) { SkillRegisterElementsCallbacksCase4(code); }}}}, + {static_cast(OHOSApplicationApi::UnregisterElementsCallbacks), + {{[this](int code) { SkillUnregisterElementsCallbacksCase1(code); }}, + {[this](int code) { SkillUnregisterElementsCallbacksCase2(code); }}, + {[this](int code) { SkillUnregisterElementsCallbacksCase3(code); }}, + {[this](int code) { SkillUnregisterElementsCallbacksCase4(code); }}}}, + }; +}; + +class KitTestSixEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + KitTestSixEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"OHOSApplicationApi", + [this](int apiIndex, int caseIndex, int code) { ApplicationStByCode(apiIndex, caseIndex, code); }}, + }; + sixthAbility_ = nullptr; + } + ~KitTestSixEventSubscriber() + { + sixthAbility_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void ApplicationStByCode(int apiIndex, int caseIndex, int code); + void KitTerminateAbility(); + + SixthAbility *sixthAbility_; + +private: + std::unordered_map> mapTestFunc_; +}; + +// Record the number of callback function exec +class CallbackCount { +public: + int GetOnAbilityStartCount(); + int GetOnAbilityInactiveCount(); + int GetOnAbilityBackgroundCount(); + int GetOnAbilityForegroundCount(); + int GetOnAbilityActiveCount(); + int GetOnAbilityStopCount(); + int GetOnAbilitySaveStateCount(); + int GetOnConfigurationCount(); + int GetOnMemoryLevelCount(); + + void SetOnAbilityStartCount(); + void SetOnAbilityInactiveCount(); + void SetOnAbilityBackgroundCount(); + void SetOnAbilityForegroundCount(); + void SetOnAbilityActiveCount(); + void SetOnAbilityStopCount(); + void SetOnAbilitySaveStateCount(); + void SetOnConfigurationCount(); + void SetOnMemoryLevelCount(); + +private: + int onAbilityStartCount = 0; + int onAbilityInactiveCount = 0; + int onAbilityBackgroundCount = 0; + int onAbilityForegroundCount = 0; + int onAbilityActiveCount = 0; + int onAbilityStopCount = 0; + int onAbilitySaveStateCount = 0; + int onConfigurationCount = 0; + int onMemoryLevelCount = 0; +}; + +// The Lifecycle callback function class (First) +class KitTestFirstLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + CallbackCount GetCallbackCount(); + +private: + CallbackCount callbackCount_; +}; + +// The Lifecycle callback function class (Second) +class KitTestSecondLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + CallbackCount GetCallbackCount(); + +private: + CallbackCount callbackCount_; +}; + +// The Lifecycle callback function class (Third) +class KitTestThirdLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + CallbackCount GetCallbackCount(); + +private: + CallbackCount callbackCount_; +}; + +// The Elements callback function class (First) +class KitTestFirstElementsCallback : public ElementsCallback { +public: + virtual void OnConfigurationUpdated(const std::shared_ptr &ability, const Configuration &config) override; + virtual void OnMemoryLevel(int level) override; + CallbackCount GetCallbackCount(); + +private: + CallbackCount callbackCount_; +}; + +// The Elements callback function class (Second) +class KitTestSecondElementsCallback : public ElementsCallback { +public: + virtual void OnConfigurationUpdated(const std::shared_ptr &ability, const Configuration &config) override; + virtual void OnMemoryLevel(int level) override; + CallbackCount GetCallbackCount(); + +private: + CallbackCount callbackCount_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _Six_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0af55daf4ded4319a4da63849373fcf9ba3d4b03 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _TEST_UTILS_H_ +#define _TEST_UTILS_H_ +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _TEST_UTILS_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..f83e7bb013421d718a97b190d761cc8ca85cddad --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _THIRD_ABILITY_H_ +#define _THIRD_ABILITY_H_ +#include +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" +#include "process_info.h" + +namespace OHOS { +namespace AppExecFwk { +using vector_str = std::vector; +using vector_conststr = std::vector; +using vector_func = std::vector>; +class KitTestThirdEventSubscriber; + +class ThirdAbility : public Ability { +public: + void SubscribeEvent(const vector_conststr &eventList); + void ProcessInfoStByCode(int apiIndex, int caseIndex, int code); + bool CompareProcessInfo(const ProcessInfo &processInfo1, const ProcessInfo &processInfo2); + void GetParcelByProcessName(ProcessInfo &processInfo, const std::string &expectedString, int code); + void GetParcelByProcessID(ProcessInfo &processInfo, const int expectedInt, int code); + void GetProcessNameByParcel(const std::string &processInfo, int processID, int code); + void GetProcessIDByParcel(const std::string &processName, int processID, int code); + void ComparePidProcessName(ProcessInfo &processInfo, int expectedPid, const std::string &expectedName, int code); + + // GetPid ST kit Case + void ProcessInfoGetPidCase1(int code); + void ProcessInfoGetPidCase2(int code); + void ProcessInfoGetPidCase3(int code); + void ProcessInfoGetPidCase4(int code); + + // GetProcessName ST kit Case + void ProcessInfoGetProcessNameCase1(int code); + void ProcessInfoGetProcessNameCase2(int code); + void ProcessInfoGetProcessNameCase3(int code); + void ProcessInfoGetProcessNameCase4(int code); + + // Marshalling ST kit Case + void ProcessInfoMarshallingCase1(int code); + void ProcessInfoMarshallingCase2(int code); + void ProcessInfoMarshallingCase3(int code); + void ProcessInfoMarshallingCase4(int code); + void ProcessInfoMarshallingCase5(int code); + void ProcessInfoMarshallingCase6(int code); + + // Unmarshalling ST kit Case + void ProcessInfoUnmarshallingCase1(int code); + void ProcessInfoUnmarshallingCase2(int code); + void ProcessInfoUnmarshallingCase3(int code); + void ProcessInfoUnmarshallingCase4(int code); + void ProcessInfoUnmarshallingCase5(int code); + void ProcessInfoUnmarshallingCase6(int code); + void ProcessInfoUnmarshallingCase7(int code); + void ProcessInfoUnmarshallingCase8(int code); + void ProcessInfoUnmarshallingCase9(int code); + + // ProcessInfo ST kit Case + void ProcessInfoProcessInfoCase1(int code); + void ProcessInfoProcessInfoCase2(int code); + + // ProcessInfo_String_int ST kit Case + void ProcessInfoProcessInfoStringintCase1(int code); + void ProcessInfoProcessInfoStringintCase2(int code); + void ProcessInfoProcessInfoStringintCase3(int code); + void ProcessInfoProcessInfoStringintCase4(int code); + void ProcessInfoProcessInfoStringintCase5(int code); + void ProcessInfoProcessInfoStringintCase6(int code); + + std::shared_ptr subscriber; + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn_; + std::string targetBundle_; + std::string targetAbility_; + std::unordered_map mapStKitFunc_ = { + {static_cast(ProcessInfoApi::GetPid), + {{[this](int code) { ProcessInfoGetPidCase1(code); }}, + {[this](int code) { ProcessInfoGetPidCase2(code); }}, + {[this](int code) { ProcessInfoGetPidCase3(code); }}, + {[this](int code) { ProcessInfoGetPidCase4(code); }}}}, + {static_cast(ProcessInfoApi::GetProcessName), + {{[this](int code) { ProcessInfoGetProcessNameCase1(code); }}, + {[this](int code) { ProcessInfoGetProcessNameCase2(code); }}, + {[this](int code) { ProcessInfoGetProcessNameCase3(code); }}, + {[this](int code) { ProcessInfoGetProcessNameCase4(code); }}}}, + {static_cast(ProcessInfoApi::Marshalling), + {{[this](int code) { ProcessInfoMarshallingCase1(code); }}, + {[this](int code) { ProcessInfoMarshallingCase2(code); }}, + {[this](int code) { ProcessInfoMarshallingCase3(code); }}, + {[this](int code) { ProcessInfoMarshallingCase4(code); }}, + {[this](int code) { ProcessInfoMarshallingCase5(code); }}, + {[this](int code) { ProcessInfoMarshallingCase6(code); }}}}, + {static_cast(ProcessInfoApi::Unmarshalling), + {{[this](int code) { ProcessInfoUnmarshallingCase1(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase2(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase3(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase4(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase5(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase6(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase7(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase8(code); }}, + {[this](int code) { ProcessInfoUnmarshallingCase9(code); }}}}, + {static_cast(ProcessInfoApi::ProcessInfo), + {{[this](int code) { ProcessInfoProcessInfoCase1(code); }}, + {[this](int code) { ProcessInfoProcessInfoCase2(code); }}}}, + {static_cast(ProcessInfoApi::ProcessInfo_String_int), + {{[this](int code) { ProcessInfoProcessInfoStringintCase1(code); }}, + {[this](int code) { ProcessInfoProcessInfoStringintCase2(code); }}, + {[this](int code) { ProcessInfoProcessInfoStringintCase3(code); }}, + {[this](int code) { ProcessInfoProcessInfoStringintCase4(code); }}, + {[this](int code) { ProcessInfoProcessInfoStringintCase5(code); }}, + {[this](int code) { ProcessInfoProcessInfoStringintCase6(code); }}}}}; +}; + +class KitTestThirdEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + KitTestThirdEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, ThirdAbility *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ProcessInfoApi", + [this](int apiIndex, int caseIndex, int code) { ProcessInfoStByCode(apiIndex, caseIndex, code); }}, + }; + thirdAbility_ = ability; + } + ~KitTestThirdEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void ProcessInfoStByCode(int apiIndex, int caseIndex, int code); + void KitTerminateAbility(); + ThirdAbility *thirdAbility_; + +private: + std::unordered_map> mapTestFunc_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _THIRD_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a99add0aa9189e99aab9dfd33ffe144279970fd9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp @@ -0,0 +1,1010 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "fifth_ability.h" +#include "app_log_wrapper.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/base_types.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace AAFwk; +using namespace OHOS::EventFwk; +constexpr unsigned loopSize = 10; +void FifthAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FifthAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +void FifthAbility::OnStart(const Want &want) +{ + APP_LOGI("FifthAbility::onStart"); + Ability::OnStart(want); + SubscribeEvent(); +} + +void FifthAbility::OnStop() +{ + APP_LOGI("FifthAbility::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, Ability::GetState(), "OnStop"); +} + +void FifthAbility::OnActive() +{ + APP_LOGI("FifthAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, Ability::GetState(), "OnActive"); +} + +void FifthAbility::OnInactive() +{ + APP_LOGI("FifthAbility::OnInactive"); + Ability::OnInactive(); +} + +void FifthAbility::OnBackground() +{ + APP_LOGI("FifthAbility::OnBackground"); + Ability::OnBackground(); +} + +void FifthAbility::OnForeground(const Want &want) +{ + APP_LOGI("FifthAbility::OnForeground"); + Ability::OnForeground(want); +} + +void FifthAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("FifthAbility::OnAbilityResult"); + Ability::OnAbilityResult(requestCode, resultCode, resultData); +} + +void FifthAbility::OnBackPressed() +{ + APP_LOGI("FifthAbility::OnBackPressed"); + Ability::OnBackPressed(); +} + +void FifthAbility::OnNewWant(const Want &want) +{ + APP_LOGI("FifthAbility::OnNewWant"); + Ability::OnNewWant(want); +} + +void FifthAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIFTH, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void FifthEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FifthEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FifthEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FifthEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIFTH.c_str()) == 0) { + auto target = data.GetData(); + auto handle = 0; + auto api = 1; + auto code = 2; + auto paramMinSize = 3; + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < static_cast(paramMinSize)) { + return; + } + if (mapTestFunc_.find(caseInfo[handle]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[handle]](std::stoi(caseInfo[api]), std::stoi(caseInfo[code]), data.GetCode()); + } else { + APP_LOGI("FifthEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void FifthAbility::TestWantParams(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("FifthAbility::TestWantParams"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// set string param +void FifthAbility::WantParamsSetParamCase1(int code) +{ + APP_LOGI("WantParamsSetParamCase1"); + std::string key = "key"; + std::string value = "value"; + WantParams wParams; + wParams.SetParam(key, String::Box(value)); + bool result = (String::Unbox(IString::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set bool param +void FifthAbility::WantParamsSetParamCase2(int code) +{ + std::string key = "key"; + bool value = true; + WantParams wParams; + wParams.SetParam(key, Boolean::Box(value)); + bool result = (Boolean::Unbox(IBoolean::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set byte param +void FifthAbility::WantParamsSetParamCase3(int code) +{ + std::string key = "key"; + byte value = 9; + WantParams wParams; + wParams.SetParam(key, Byte::Box(value)); + bool result = (Byte::Unbox(IByte::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set char param +void FifthAbility::WantParamsSetParamCase4(int code) +{ + std::string key = "key"; + zchar value = 'z'; + WantParams wParams; + wParams.SetParam(key, Char::Box(value)); + bool result = (Char::Unbox(IChar::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set short param +void FifthAbility::WantParamsSetParamCase5(int code) +{ + std::string key = "key"; + short value = 99; + WantParams wParams; + wParams.SetParam(key, Short::Box(value)); + bool result = (Short::Unbox(IShort::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set int param +void FifthAbility::WantParamsSetParamCase6(int code) +{ + std::string key = "key"; + int value = 999; + WantParams wParams; + wParams.SetParam(key, Integer::Box(value)); + bool result = (Integer::Unbox(IInteger::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set long param +void FifthAbility::WantParamsSetParamCase7(int code) +{ + std::string key = "key"; + long value = 9999L; + WantParams wParams; + wParams.SetParam(key, Long::Box(value)); + bool result = (Long::Unbox(ILong::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set float param +void FifthAbility::WantParamsSetParamCase8(int code) +{ + std::string key = "key"; + float value = 9999.99f; + WantParams wParams; + wParams.SetParam(key, Float::Box(value)); + bool result = (Float::Unbox(IFloat::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set double param +void FifthAbility::WantParamsSetParamCase9(int code) +{ + std::string key = "key"; + double value = 99998888.99; + WantParams wParams; + wParams.SetParam(key, Double::Box(value)); + bool result = (Double::Unbox(IDouble::Query(wParams.GetParam(key))) == value); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +template +static void SetArray(const InterfaceID &id, const std::vector &value, sptr &ao) +{ + typename std::vector::size_type size = value.size(); + ao = new Array(size, id); + for (typename std::vector::size_type i = 0; i < size; i++) { + ao->Set(i, T2::Box(value[i])); + } +} + +template +static void FillArray(IArray *ao, std::vector &array) +{ + auto func = [&](IInterface *object) { array.push_back(T2::Unbox(T3::Query(object))); }; + Array::ForEach(ao, func); +} + +// set string array param +void FifthAbility::WantParamsSetParamCase10(int code) +{ + std::string key = "key"; + std::vector value = {"aa", "bb", "cc"}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IString); + for (std::vector::size_type i = 0; i < size; i++) { + ao->Set(i, String::Box(value[i])); + } + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set bool array param +void FifthAbility::WantParamsSetParamCase11(int code) +{ + std::string key = "key"; + std::vector value = {false, true, true, false}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IBoolean); + SetArray(g_IID_IBoolean, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set byte array param +void FifthAbility::WantParamsSetParamCase12(int code) +{ + std::string key = "key"; + std::vector value = {1, 2, 3, 4}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IByte); + SetArray(g_IID_IByte, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set char array param +void FifthAbility::WantParamsSetParamCase13(int code) +{ + std::string key = "key"; + std::vector value = {'1', '2', '3', '4'}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IChar); + SetArray(g_IID_IChar, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set short array param +void FifthAbility::WantParamsSetParamCase14(int code) +{ + std::string key = "key"; + std::vector value = {'1', '2', '3', '4'}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IShort); + SetArray(g_IID_IShort, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set int array param +void FifthAbility::WantParamsSetParamCase15(int code) +{ + std::string key = "key"; + std::vector value = {10, 20, 30, 40}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IInteger); + SetArray(g_IID_IInteger, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set long array param +void FifthAbility::WantParamsSetParamCase16(int code) +{ + std::string key = "key"; + std::vector value = {100L, 200L, 300L, 400L}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_ILong); + SetArray(g_IID_ILong, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set float array param +void FifthAbility::WantParamsSetParamCase17(int code) +{ + std::string key = "key"; + std::vector value = {100.1f, 200.1f, 300.1f, 400.1f}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IFloat); + SetArray(g_IID_IFloat, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// set double array param +void FifthAbility::WantParamsSetParamCase18(int code) +{ + std::string key = "key"; + std::vector value = {100.1, 200.1, 300.1, 400.1}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IDouble); + SetArray(g_IID_IDouble, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wParams.GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// empty key on empty WantParams +void FifthAbility::WantParamsHasParamCase1(int code) +{ + std::string key = ""; + WantParams wParams; + bool result = (wParams.HasParam(key) == false); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// empty key has value +void FifthAbility::WantParamsHasParamCase2(int code) +{ + std::string key = ""; + sptr value = String::Box("value"); + WantParams wParams; + wParams.SetParam(key, value); + bool result = (wParams.HasParam(key) == true); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// not empty key on empty WantParams +void FifthAbility::WantParamsHasParamCase3(int code) +{ + std::string key = "key"; + WantParams wParams; + bool result = (wParams.HasParam(key) == false); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// not empty key has a value +void FifthAbility::WantParamsHasParamCase4(int code) +{ + std::string key = "key"; + sptr value = String::Box("value"); + WantParams wParams; + wParams.SetParam(key, value); + bool result = (wParams.HasParam(key) == true); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// key with special character has a value +void FifthAbility::WantParamsHasParamCase5(int code) +{ + std::string key = "~!@#$%^&*()_+`-=:\"<>?;',./"; + sptr value = String::Box("value"); + WantParams wParams; + wParams.SetParam(key, value); + bool result = (wParams.HasParam(key) == true); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// empty WantParams +void FifthAbility::WantParamsIsEmptyCase1(int code) +{ + WantParams wParams; + bool result = (wParams.IsEmpty() == true); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// WantParams with params +void FifthAbility::WantParamsIsEmptyCase2(int code) +{ + std::string key = "key"; + sptr value = String::Box("value"); + WantParams wParams; + wParams.SetParam(key, value); + bool result = (wParams.IsEmpty() == false); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall string param +void FifthAbility::WantParamsMarshallingCase1(int code) +{ + std::string key = "key"; + std::string value = "value"; + WantParams wParams; + wParams.SetParam(key, String::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (String::Unbox(IString::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall bool param +void FifthAbility::WantParamsMarshallingCase2(int code) +{ + std::string key = "key"; + bool value = true; + WantParams wParams; + wParams.SetParam(key, Boolean::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (Boolean::Unbox(IBoolean::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall byte param +void FifthAbility::WantParamsMarshallingCase3(int code) +{ + std::string key = "key"; + byte value = 9; + WantParams wParams; + wParams.SetParam(key, Byte::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (Byte::Unbox(IByte::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall char param +void FifthAbility::WantParamsMarshallingCase4(int code) +{ + std::string key = "key"; + zchar value = 'z'; + WantParams wParams; + wParams.SetParam(key, Char::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (Char::Unbox(IChar::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall short param +void FifthAbility::WantParamsMarshallingCase5(int code) +{ + std::string key = "key"; + short value = 99; + WantParams wParams; + wParams.SetParam(key, Short::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (Short::Unbox(IShort::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall int param +void FifthAbility::WantParamsMarshallingCase6(int code) +{ + std::string key = "key"; + int value = 999; + WantParams wParams; + wParams.SetParam(key, Integer::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (Integer::Unbox(IInteger::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall long param +void FifthAbility::WantParamsMarshallingCase7(int code) +{ + std::string key = "key"; + long value = 9999L; + std::string strValue = "9999"; + WantParams wParams; + wParams.SetParam(key, Long::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); +#ifdef WANT_PARAM_USE_LONG + bool result = (Long)::Unbox(ILong::Query(wantParamsOut->GetParam(key))) == value); +#else + bool result = (String::Unbox(IString::Query(wantParamsOut->GetParam(key))) == strValue); +#endif + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall float param +void FifthAbility::WantParamsMarshallingCase8(int code) +{ + std::string key = "key"; + float value = 9999.99f; + WantParams wParams; + wParams.SetParam(key, Float::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (Float::Unbox(IFloat::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall double param +void FifthAbility::WantParamsMarshallingCase9(int code) +{ + std::string key = "key"; + double value = 99998888.99; + WantParams wParams; + wParams.SetParam(key, Double::Box(value)); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + bool result = (Double::Unbox(IDouble::Query(wantParamsOut->GetParam(key))) == value); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall string array param +void FifthAbility::WantParamsMarshallingCase10(int code) +{ + std::string key = "key"; + std::vector value = {"aa", "bb", "cc"}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IString); + for (std::vector::size_type i = 0; i < size; i++) { + ao->Set(i, String::Box(value[i])); + } + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall bool array param +void FifthAbility::WantParamsMarshallingCase11(int code) +{ + std::string key = "key"; + std::vector value = {false, true, true, false}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IBoolean); + SetArray(g_IID_IBoolean, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall byte array param +void FifthAbility::WantParamsMarshallingCase12(int code) +{ + std::string key = "key"; + std::vector value = {1, 2, 3, 4}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IByte); + SetArray(g_IID_IByte, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall char array param +void FifthAbility::WantParamsMarshallingCase13(int code) +{ + std::string key = "key"; + std::vector value = {'1', '2', '3', '4'}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IChar); + SetArray(g_IID_IChar, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall short array param +void FifthAbility::WantParamsMarshallingCase14(int code) +{ + std::string key = "key"; + std::vector value = {'1', '2', '3', '4'}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IShort); + SetArray(g_IID_IShort, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall int array param +void FifthAbility::WantParamsMarshallingCase15(int code) +{ + std::string key = "key"; + std::vector value = {10, 20, 30, 40}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IInteger); + SetArray(g_IID_IInteger, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall long array param +void FifthAbility::WantParamsMarshallingCase16(int code) +{ + std::string key = "key"; + std::vector value = {100L, 200L, 300L, 400L}; + std::vector strValue = {"100", "200", "300", "400"}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_ILong); + SetArray(g_IID_ILong, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); +#ifdef WANT_PARAM_USE_LONG + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); +#else + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (strValue == getParamValue); +#endif + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall float array param +void FifthAbility::WantParamsMarshallingCase17(int code) +{ + std::string key = "key"; + std::vector value = {100.1f, 200.1f, 300.1f, 400.1f}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IFloat); + SetArray(g_IID_IFloat, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// marshall and unmarshall double array param +void FifthAbility::WantParamsMarshallingCase18(int code) +{ + std::string key = "key"; + std::vector value = {100.1, 200.1, 300.1, 400.1}; + + std::vector::size_type size = value.size(); + sptr ao = new Array(size, g_IID_IDouble); + SetArray(g_IID_IDouble, value, ao); + + WantParams wParams; + wParams.SetParam(key, ao); + Parcel in; + wParams.Marshalling(in); + WantParams *wantParamsOut = WantParams::Unmarshalling(in); + std::vector getParamValue; + sptr getParamAo = IArray::Query(wantParamsOut->GetParam(key)); + FillArray(getParamAo, getParamValue); + bool result = (value == getParamValue); + if (wantParamsOut) { + delete wantParamsOut; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// no any param +void FifthAbility::WantParamsSizeCase1(int code) +{ + WantParams wParams; + bool result = (wParams.Size() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// only one param +void FifthAbility::WantParamsSizeCase2(int code) +{ + std::string key = "key"; + sptr value = String::Box("value"); + WantParams wParams; + wParams.SetParam(key, value); + bool result = (wParams.Size() == 1); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// multiple params +void FifthAbility::WantParamsSizeCase3(int code) +{ + std::string key = "key"; + sptr value = nullptr; + WantParams wParams; + for (unsigned i = 0; i < loopSize; i++) { + sptr value = String::Box("value" + std::to_string(i)); + wParams.SetParam(key + std::to_string(i), value); + } + bool result = (wParams.Size() == loopSize); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// no any key +void FifthAbility::WantParamsKeySetCase1(int code) +{ + WantParams wParams; + bool result = (wParams.KeySet().size() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// multiple keys +void FifthAbility::WantParamsKeySetCase2(int code) +{ + std::string key = "key"; + sptr value = nullptr; + WantParams wParams; + for (unsigned i = 0; i < loopSize; i++) { + sptr value = String::Box("value" + std::to_string(i)); + wParams.SetParam(key + std::to_string(i), value); + } + bool result = (wParams.KeySet().size() == loopSize); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// copy empty WantParams +void FifthAbility::WantParamsCopyCase1(int code) +{ + WantParams wParams; + WantParams wParamsCopy(wParams); + bool result = (wParamsCopy.Size() == wParams.Size()); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// copy WantParams with multiple param +void FifthAbility::WantParamsCopyCase2(int code) +{ + std::string key = "key"; + sptr value = nullptr; + WantParams wParams; + for (unsigned i = 0; i < loopSize; i++) { + sptr value = String::Box("value" + std::to_string(i)); + wParams.SetParam(key + std::to_string(i), value); + } + WantParams wParamsCopy(wParams); + bool result = (wParamsCopy.Size() == wParams.Size()); + result = result && (*(wParamsCopy.KeySet().begin()) == *(wParams.KeySet().begin())) && + (*(wParamsCopy.KeySet().rbegin()) == *(wParams.KeySet().rbegin())); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// remove not existed param +void FifthAbility::WantParamsRemoveCase1(int code) +{ + std::string key = "key"; + sptr value = String::Box("value"); + WantParams wParams; + bool result = (wParams.GetParam(key) == nullptr); + wParams.Remove(key); + result = result && (wParams.GetParam(key) == nullptr); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +// remove existed param +void FifthAbility::WantParamsRemoveCase2(int code) +{ + std::string key = "key"; + sptr value = String::Box("value"); + WantParams wParams; + wParams.SetParam(key, value); + bool result = wParams.GetParam(key) != nullptr; + wParams.Remove(key); + result = result && (wParams.GetParam(key) == nullptr); + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +} + +REGISTER_AA(FifthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp new file mode 100755 index 0000000000000000000000000000000000000000..844827e876c07a86e52bbddfa7071202769429f1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp @@ -0,0 +1,2506 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "fourth_ability.h" +#include +#include +#include +#include "app_log_wrapper.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +namespace { +const std::string normalString = "kitapp.system.test"; +// Special string +const std::string specialString = "@#¥#//\\%&*_=+[]^:!~();,.'?3243adsafdf_中文"; +const std::string normalPathAndType = "kitapp.system/.test"; +const std::string skillspecialTypeStr1 = "special.kitapp.system.test"; +// Special string +const std::string skillspecialTypeStr2 = "special.kitapp.system.test/*"; +// Special string +const std::string skillspecialTypeStr3 = "/special.kitapp.system.test"; +const int cycleCount = 1000; +enum class AddFunctionType { Add_String, Add_String_MatchType, Add_PatternMatcher }; +} // namespace + +#define COUNTFUNCTION(objectName, countFunction, expected, code) \ + do { \ + int actionCount = objectName.countFunction(); \ + bool result = (actionCount == (expected)); \ + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); \ + } while (0); + +#define GETFUNCTION(objectName, getFunction, parameter, expected, code) \ + do { \ + std::string skillAction = objectName.getFunction(parameter); \ + bool result = (skillAction == (expected)); \ + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); \ + } while (0); + +#define HASFUNCTION(objectName, hasFunction, parameter, expected, code) \ + do { \ + bool isHas = objectName.hasFunction(parameter); \ + bool result = (isHas == (expected)); \ + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); \ + } while (0); + +// Add Path and Type Define Function +#define ADDFUNCTION(objeceName, addFunction, stringParameter, addFunctionType) \ + do { \ + if (AddFunctionType::Add_String == (addFunctionType)) { \ + objeceName.addFunction((stringParameter)); \ + } else if (AddFunctionType::Add_String_MatchType == (addFunctionType)) { \ + skill.addFunction((stringParameter), MatchType::PREFIX); \ + } else { \ + PatternsMatcher pm((stringParameter), MatchType::PREFIX); \ + skill.addFunction(pm); \ + } \ + } while (0); + +#define REMOVEFUNCTION(objeceName, removeFunction, stringParameter, addFunctionType) \ + do { \ + if (AddFunctionType::Add_String == (addFunctionType)) { \ + objeceName.removeFunction((stringParameter)); \ + } else if (AddFunctionType::Add_String_MatchType == (addFunctionType)) { \ + skill.removeFunction((stringParameter), MatchType::PREFIX); \ + } else { \ + PatternsMatcher pm((stringParameter), MatchType::PREFIX); \ + skill.removeFunction(pm); \ + } \ + } while (0); + +// Add and Count ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) +#define SKILLS_ADD_AND_COUNT_CASE1(addFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); + +#define SKILLS_ADD_AND_COUNT_CASE2(countFunction, code) \ + do { \ + Skills skill; \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); + +#define SKILLS_ADD_AND_COUNT_CASE3(addFunction, countFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); + +// Add and Get ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) +#define SKILLS_ADD_AND_GET_CASE1(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + GETFUNCTION(skill, getFunction, 0, normalString, code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE2(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + GETFUNCTION(skill, getFunction, 10, std::string(), code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE3(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + GETFUNCTION(skill, getFunction, -10, std::string(), code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE4(getFunction, code) \ + do { \ + Skills skill; \ + GETFUNCTION(skill, getFunction, 0, std::string(), code) \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE5(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + GETFUNCTION(skill, getFunction, 0, specialString, code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE6(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + GETFUNCTION(skill, getFunction, 0, normalString, code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE7(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + GETFUNCTION(skill, getFunction, 150, std::string(), code) \ + } while (0); + +// Add and Has ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) +#define SKILLS_ADD_AND_HAS_CASE1(addFunction, hasFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + HASFUNCTION(skill, hasFunction, normalString, true, code); \ + } while (0); + +#define SKILLS_ADD_AND_HAS_CASE2(hasFunction, code) \ + do { \ + Skills skill; \ + HASFUNCTION(skill, hasFunction, normalString, false, code); \ + } while (0); + +#define SKILLS_ADD_AND_HAS_CASE3(addFunction, hasFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + HASFUNCTION(skill, hasFunction, specialString, true, code); \ + } while (0); + +// Add,Remove,Count and Has ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) +#define SKILLS_ADD_AND_REMOVE_CASE1(addFunction, removeFunction, hasFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.removeFunction(specialString); \ + HASFUNCTION(skill, hasFunction, specialString, false, code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE2(addFunction, removeFunction, getFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.removeFunction(specialString); \ + GETFUNCTION(skill, getFunction, 0, std::string(), code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE3(addFunction, removeFunction, hasFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(normalString); \ + HASFUNCTION(skill, hasFunction, normalString, false, code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE4(addFunction, removeFunction, hasFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(specialString); \ + HASFUNCTION(skill, hasFunction, normalString, true, code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE5(addFunction, removeFunction, getFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(normalString); \ + GETFUNCTION(skill, getFunction, 150, std::string(), code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE6(addFunction, removeFunction, getFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(specialString); \ + GETFUNCTION(skill, getFunction, 0, normalString, code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE7(addFunction, removeFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.removeFunction(specialString); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE8(addFunction, removeFunction, countFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(normalString); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); + +#define SKILLS_ADD_AND_REMOVE_CASE9(addFunction, removeFunction, countFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(specialString); \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); + +// Add and Count ST kit Case(Path,Type) +#define SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(addFunction, countFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE2(countFunction, code) \ + do { \ + Skills skill; \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(addFunction, countFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); + +// Add and Get ST kit Case(Path,Type) +#define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(addFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 0, normalPathAndType, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(addFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 10, std::string(), code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(addFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + GETFUNCTION(skill, getFunction, -10, std::string(), code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE4(getFunction, code) \ + do { \ + Skills skill; \ + GETFUNCTION(skill, getFunction, 0, std::string(), code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(addFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)) \ + GETFUNCTION(skill, getFunction, 0, specialString, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(addFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + GETFUNCTION(skill, getFunction, 0, normalPathAndType, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(addFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + GETFUNCTION(skill, getFunction, 150, std::string(), code); \ + } while (0); + +// Add and Has ST kit Case(Path,Type) +#define SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(addFunction, hasFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + HASFUNCTION(skill, hasFunction, normalPathAndType, true, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE2(hasFunction, code) \ + do { \ + Skills skill; \ + HASFUNCTION(skill, hasFunction, normalPathAndType, false, code) \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(addFunction, hasFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)) \ + HASFUNCTION(skill, hasFunction, specialString, true, code); \ + } while (0); + +// Add,Remove,Count and Has ST kit Case(Path,Type) +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(addFunction, removeFunction, hasFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)); \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + HASFUNCTION(skill, hasFunction, specialString, false, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(addFunction, removeFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)); \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 0, std::string(), code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(addFunction, removeFunction, hasFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, normalPathAndType, (addFunctionType)); \ + HASFUNCTION(skill, hasFunction, normalPathAndType, false, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(addFunction, removeFunction, hasFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + HASFUNCTION(skill, hasFunction, normalPathAndType, true, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(addFunction, removeFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, normalPathAndType, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 150, std::string(), code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(addFunction, removeFunction, getFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 0, normalPathAndType, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7(addFunction, removeFunction, countFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)); \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8(addFunction, removeFunction, countFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, normalPathAndType, (addFunctionType)); \ + COUNTFUNCTION(skill, countFunction, 0, code) \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9(addFunction, removeFunction, countFunction, code, addFunctionType) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)) \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE10(addFunction, removeFunction, hasFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.addFunction(specialString, MatchType::PREFIX); \ + skill.removeFunction(specialString); \ + HASFUNCTION(skill, hasFunction, specialString, true, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE11(addFunction, removeFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString, MatchType::DEFAULT); \ + skill.addFunction(specialString, MatchType::PREFIX); \ + skill.addFunction(specialString, MatchType::GLOBAL); \ + skill.removeFunction(specialString); \ + COUNTFUNCTION(skill, countFunction, 2, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE12(addFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.addFunction(specialString, MatchType::DEFAULT); \ + skill.addFunction(specialString, MatchType::PREFIX); \ + skill.addFunction(specialString, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 3, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE13(addFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr1); \ + skill.addFunction(skillspecialTypeStr1, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr1, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr1, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE14(addFunction, hasFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr1); \ + skill.addFunction(skillspecialTypeStr1, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr1, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr1, MatchType::GLOBAL); \ + HASFUNCTION(skill, hasFunction, skillspecialTypeStr1, false, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE15(addFunction, hasFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr2); \ + skill.addFunction(skillspecialTypeStr2, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr2, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr2, MatchType::GLOBAL); \ + HASFUNCTION(skill, hasFunction, skillspecialTypeStr1, true, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE16(addFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr2); \ + skill.addFunction(skillspecialTypeStr2, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr2, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr2, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 3, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE17(addFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr3); \ + skill.addFunction(skillspecialTypeStr3, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr3, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr3, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 3, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE18(addFunction, hasFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr3); \ + skill.addFunction(skillspecialTypeStr3, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr3, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr3, MatchType::GLOBAL); \ + HASFUNCTION(skill, hasFunction, skillspecialTypeStr3, true, code); \ + } while (0); + +// Skills Add ST Case +#define SKILLS_ADD_CASE1(addFunction, countFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + skill.addFunction(specialString); \ + skill.addFunction(specialString); \ + skill.addFunction(normalPathAndType); \ + skill.addFunction("Ams_Kit_ST_Case"); \ + COUNTFUNCTION(skill, countFunction, 4, code); \ + } while (0); + +void FourthAbility::SubscribeEvent(const vector_conststr &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void FourthAbility::SkillsApiStByCode(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("FourthAbility::SkillsApiStByCode"); + if (mapStKitFunc_.find(apiIndex) != mapStKitFunc_.end() && + static_cast(mapStKitFunc_[apiIndex].size()) > caseIndex) { + mapStKitFunc_[apiIndex][caseIndex](code); + } else { + APP_LOGI("SkillsApiStByCode error"); + } +} + +bool FourthAbility::CompareEntity(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + bool equalEntity = (skills1.CountEntities() == skills2.CountEntities()); + if (equalEntity) { + int count = 0; + count = skills1.CountEntities(); + for (int i = 0; i < count; i++) { + bool result = (skills1.GetEntity(i) == skills2.GetEntity(i)); + if (!result) { + return false; + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareAction(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + bool equalAction = (skills1.CountActions() == skills2.CountActions()); + if (equalAction) { + int count = 0; + count = skills1.CountActions(); + for (int i = 0; i < count; i++) { + bool result = (skills1.GetAction(i) == skills2.GetAction(i)); + if (!result) { + return false; + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareAuthority(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + bool equalAuthority = (skills1.CountAuthorities() == skills2.CountAuthorities()); + if (equalAuthority) { + int count = 0; + count = skills1.CountAuthorities(); + for (int i = 0; i < count; i++) { + bool result = (skills1.GetAuthority(i) == skills2.GetAuthority(i)); + if (!result) { + return false; + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareScheme(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + bool equalScheme = (skills1.CountSchemes() == skills2.CountSchemes()); + if (equalScheme) { + int count = 0; + count = skills1.CountSchemes(); + for (int i = 0; i < count; i++) { + bool result = (skills1.GetScheme(i) == skills2.GetScheme(i)); + if (!result) { + return false; + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareSPath(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + bool equalPath = (skills1.CountPaths() == skills2.CountPaths()); + if (equalPath) { + int count = 0; + count = skills1.CountPaths(); + for (int i = 0; i < count; i++) { + bool result = (skills1.GetPath(i) == skills2.GetPath(i)); + if (!result) { + return false; + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareSsp(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + bool equalSsp = (skills1.CountSchemeSpecificParts() == skills2.CountSchemeSpecificParts()); + if (equalSsp) { + int count = 0; + count = skills1.CountSchemeSpecificParts(); + for (int i = 0; i < count; i++) { + bool result = (skills1.GetSchemeSpecificPart(i) == skills2.GetSchemeSpecificPart(i)); + if (!result) { + return false; + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareType(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + bool equalType = (skills1.CountTypes() == skills2.CountTypes()); + if (equalType) { + int count = 0; + count = skills1.CountTypes(); + for (int i = 0; i < count; i++) { + bool result = (skills1.GetType(i) == skills2.GetType(i)); + if (!result) { + return false; + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareWantParams(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + std::set key1; + std::set key2; + key1 = skills1.GetWantParams().KeySet(); + key2 = skills2.GetWantParams().KeySet(); + bool equalKeyCount = (key1.size() == key2.size()); + if (equalKeyCount) { + if (key1.size() != 0) { + std::set::iterator iter1 = key1.begin(); + std::set::iterator iter2 = key2.begin(); + for (; iter1 != key1.end() && iter2 != key2.end(); iter1++, iter2++) { + bool result = (*iter1 == *iter2); + if (!result) { + return false; + } + } + } + return true; + } + return false; +} + +bool FourthAbility::CompareSkills(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2) +{ + return (CompareEntity(skills1, skills2) && CompareAction(skills1, skills2) && CompareAuthority(skills1, skills2) && + CompareScheme(skills1, skills2) && CompareSPath(skills1, skills2) && CompareSsp(skills1, skills2) && + CompareType(skills1, skills2) && CompareWantParams(skills1, skills2)); +} + +// Skills API ST Start +// AddAction and CountActions ST kit Case +void FourthAbility::SkillsAddActionAndCountActionsCase1(int code) +{ + SKILLS_ADD_AND_COUNT_CASE1(AddAction, CountActions, code); +} + +void FourthAbility::SkillsAddActionAndCountActionsCase2(int code) +{ + SKILLS_ADD_AND_COUNT_CASE2(CountActions, code); +} + +void FourthAbility::SkillsAddActionAndCountActionsCase3(int code) +{ + SKILLS_ADD_AND_COUNT_CASE3(AddAction, CountActions, code); +} + +// AddAction and GetAction ST kit Case +void FourthAbility::SkillsAddActionAndGetActionCase1(int code) +{ + SKILLS_ADD_AND_GET_CASE1(AddAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndGetActionCase2(int code) +{ + SKILLS_ADD_AND_GET_CASE2(AddAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndGetActionCase3(int code) +{ + SKILLS_ADD_AND_GET_CASE3(AddAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndGetActionCase4(int code) +{ + SKILLS_ADD_AND_GET_CASE4(GetAction, code); +} + +void FourthAbility::SkillsAddActionAndGetActionCase5(int code) +{ + SKILLS_ADD_AND_GET_CASE5(AddAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndGetActionCase6(int code) +{ + SKILLS_ADD_AND_GET_CASE6(AddAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndGetActionCase7(int code) +{ + SKILLS_ADD_AND_GET_CASE7(AddAction, GetAction, code); +} + +// AddAction and HasAction ST kit Case +void FourthAbility::SkillsAddActionAndHasActionCase1(int code) +{ + SKILLS_ADD_AND_HAS_CASE1(AddAction, HasAction, code); +} + +void FourthAbility::SkillsAddActionAndHasActionCase2(int code) +{ + SKILLS_ADD_AND_HAS_CASE2(HasAction, code); +} + +void FourthAbility::SkillsAddActionAndHasActionCase3(int code) +{ + SKILLS_ADD_AND_HAS_CASE3(AddAction, HasAction, code); +} +// AddAction,RemoveAction,CountActions and HasAction ST kit Case +void FourthAbility::SkillsAddActionAndRemoveActionCase1(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE1(AddAction, RemoveAction, HasAction, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase2(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE2(AddAction, RemoveAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase3(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE3(AddAction, RemoveAction, HasAction, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase4(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE4(AddAction, RemoveAction, HasAction, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase5(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE5(AddAction, RemoveAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase6(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE6(AddAction, RemoveAction, GetAction, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase7(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE7(AddAction, RemoveAction, CountActions, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase8(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE8(AddAction, RemoveAction, CountActions, code); +} + +void FourthAbility::SkillsAddActionAndRemoveActionCase9(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE9(AddAction, RemoveAction, CountActions, code); +} + +// AddEntity and CountEntities ST kit Case +void FourthAbility::SkillsAddEntityAndCountEntitiesCase1(int code) +{ + SKILLS_ADD_AND_COUNT_CASE1(AddEntity, CountEntities, code); +} + +void FourthAbility::SkillsAddEntityAndCountEntitiesCase2(int code) +{ + SKILLS_ADD_AND_COUNT_CASE2(CountEntities, code); +} + +void FourthAbility::SkillsAddEntityAndCountEntitiesCase3(int code) +{ + SKILLS_ADD_AND_COUNT_CASE3(AddEntity, CountEntities, code); +} + +// AddEntity and GetEntity ST kit Case +void FourthAbility::SkillsAddEntityAndGetEntityCase1(int code) +{ + SKILLS_ADD_AND_GET_CASE1(AddEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndGetEntityCase2(int code) +{ + SKILLS_ADD_AND_GET_CASE2(AddEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndGetEntityCase3(int code) +{ + SKILLS_ADD_AND_GET_CASE3(AddEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndGetEntityCase4(int code) +{ + SKILLS_ADD_AND_GET_CASE4(GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndGetEntityCase5(int code) +{ + SKILLS_ADD_AND_GET_CASE5(AddEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndGetEntityCase6(int code) +{ + SKILLS_ADD_AND_GET_CASE6(AddEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndGetEntityCase7(int code) +{ + SKILLS_ADD_AND_GET_CASE7(AddEntity, GetEntity, code); +} + +// AddEntity and HasEntity ST kit Case +void FourthAbility::SkillsAddEntityAndHasEntityCase1(int code) +{ + SKILLS_ADD_AND_HAS_CASE1(AddEntity, HasEntity, code); +} + +void FourthAbility::SkillsAddEntityAndHasEntityCase2(int code) +{ + SKILLS_ADD_AND_HAS_CASE2(HasEntity, code); +} + +void FourthAbility::SkillsAddEntityAndHasEntityCase3(int code) +{ + SKILLS_ADD_AND_HAS_CASE3(AddEntity, HasEntity, code); +} + +// AddEntity,RemoveEntity,CountEntities and HasEntity ST kit Case +void FourthAbility::SkillsAddEntityAndRemoveEntityCase1(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE1(AddEntity, RemoveEntity, HasEntity, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase2(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE2(AddEntity, RemoveEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase3(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE3(AddEntity, RemoveEntity, HasEntity, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase4(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE4(AddEntity, RemoveEntity, HasEntity, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase5(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE5(AddEntity, RemoveEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase6(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE6(AddEntity, RemoveEntity, GetEntity, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase7(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE7(AddEntity, RemoveEntity, CountEntities, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase8(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE8(AddEntity, RemoveEntity, CountEntities, code); +} + +void FourthAbility::SkillsAddEntityAndRemoveEntityCase9(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE9(AddEntity, RemoveEntity, CountEntities, code); +} + +// AddAuthority and CountAuthorities ST kit Case +void FourthAbility::SkillsAddAuthorityAndCountAuthoritiesCase1(int code) +{ + SKILLS_ADD_AND_COUNT_CASE1(AddAuthority, CountAuthorities, code); +} + +void FourthAbility::SkillsAddAuthorityAndCountAuthoritiesCase2(int code) +{ + SKILLS_ADD_AND_COUNT_CASE2(CountAuthorities, code); +} + +void FourthAbility::SkillsAddAuthorityAndCountAuthoritiesCase3(int code) +{ + SKILLS_ADD_AND_COUNT_CASE3(AddAuthority, CountAuthorities, code); +} + +// AddAuthority and GetAuthority ST kit Case +void FourthAbility::SkillsAddAuthorityAndGetAuthorityCase1(int code) +{ + SKILLS_ADD_AND_GET_CASE1(AddAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndGetAuthorityCase2(int code) +{ + SKILLS_ADD_AND_GET_CASE2(AddAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndGetAuthorityCase3(int code) +{ + SKILLS_ADD_AND_GET_CASE3(AddAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndGetAuthorityCase4(int code) +{ + SKILLS_ADD_AND_GET_CASE4(GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndGetAuthorityCase5(int code) +{ + SKILLS_ADD_AND_GET_CASE5(AddAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndGetAuthorityCase6(int code) +{ + SKILLS_ADD_AND_GET_CASE6(AddAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndGetAuthorityCase7(int code) +{ + SKILLS_ADD_AND_GET_CASE7(AddAuthority, GetAuthority, code); +} + +// AddAuthority and HasAuthority ST kit Case +void FourthAbility::SkillsAddAuthorityAndHasAuthorityCase1(int code) +{ + SKILLS_ADD_AND_HAS_CASE1(AddAuthority, HasAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndHasAuthorityCase2(int code) +{ + SKILLS_ADD_AND_HAS_CASE2(HasAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndHasAuthorityCase3(int code) +{ + SKILLS_ADD_AND_HAS_CASE3(AddAuthority, HasAuthority, code); +} + +// AddAuthority,RemoveAuthority,CountAuthorities and HasAuthority ST kit Case +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase1(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE1(AddAuthority, RemoveAuthority, HasAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase2(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE2(AddAuthority, RemoveAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase3(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE3(AddAuthority, RemoveAuthority, HasAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase4(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE4(AddAuthority, RemoveAuthority, HasAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase5(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE5(AddAuthority, RemoveAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase6(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE6(AddAuthority, RemoveAuthority, GetAuthority, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase7(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE7(AddAuthority, RemoveAuthority, CountAuthorities, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase8(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE8(AddAuthority, RemoveAuthority, CountAuthorities, code); +} + +void FourthAbility::SkillsAddAuthorityAndRemoveAuthorityCase9(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE9(AddAuthority, RemoveAuthority, CountAuthorities, code); +} + +// AddScheme and CountSchemes ST kit Case +void FourthAbility::SkillsAddSchemeAndCountSchemesCase1(int code) +{ + SKILLS_ADD_AND_COUNT_CASE1(AddScheme, CountSchemes, code); +} + +void FourthAbility::SkillsAddSchemeAndCountSchemesCase2(int code) +{ + SKILLS_ADD_AND_COUNT_CASE2(CountSchemes, code); +} + +void FourthAbility::SkillsAddSchemeAndCountSchemesCase3(int code) +{ + SKILLS_ADD_AND_COUNT_CASE3(AddScheme, CountSchemes, code); +} + +// AddScheme and GetScheme ST kit Case +void FourthAbility::SkillsAddSchemeAndGetSchemeCase1(int code) +{ + SKILLS_ADD_AND_GET_CASE1(AddScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndGetSchemeCase2(int code) +{ + SKILLS_ADD_AND_GET_CASE2(AddScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndGetSchemeCase3(int code) +{ + SKILLS_ADD_AND_GET_CASE3(AddScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndGetSchemeCase4(int code) +{ + SKILLS_ADD_AND_GET_CASE4(GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndGetSchemeCase5(int code) +{ + SKILLS_ADD_AND_GET_CASE5(AddScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndGetSchemeCase6(int code) +{ + SKILLS_ADD_AND_GET_CASE6(AddScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndGetSchemeCase7(int code) +{ + SKILLS_ADD_AND_GET_CASE7(AddScheme, GetScheme, code); +} + +// AddScheme and HasScheme ST kit Case +void FourthAbility::SkillsAddSchemeAndHasSchemeCase1(int code) +{ + SKILLS_ADD_AND_HAS_CASE1(AddScheme, HasScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndHasSchemeCase2(int code) +{ + SKILLS_ADD_AND_HAS_CASE2(HasScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndHasSchemeCase3(int code) +{ + SKILLS_ADD_AND_HAS_CASE3(AddScheme, HasScheme, code); +} + +// AddScheme,RemoveScheme,CountSchemes and HasScheme ST kit Case +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase1(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE1(AddScheme, RemoveScheme, HasScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase2(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE2(AddScheme, RemoveScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase3(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE3(AddScheme, RemoveScheme, HasScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase4(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE4(AddScheme, RemoveScheme, HasScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase5(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE5(AddScheme, RemoveScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase6(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE6(AddScheme, RemoveScheme, GetScheme, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase7(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE7(AddScheme, RemoveScheme, CountSchemes, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase8(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE8(AddScheme, RemoveScheme, CountSchemes, code); +} + +void FourthAbility::SkillsAddSchemeAndRemoveSchemeCase9(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE9(AddScheme, RemoveScheme, CountSchemes, code); +} + +// AddSchemeSpecificPart and CountSchemeSpecificParts ST kit Case +void FourthAbility::SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase1(int code) +{ + SKILLS_ADD_AND_COUNT_CASE1(AddSchemeSpecificPart, CountSchemeSpecificParts, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase2(int code) +{ + SKILLS_ADD_AND_COUNT_CASE2(CountSchemeSpecificParts, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndCountSchemeSpecificPartsCase3(int code) +{ + SKILLS_ADD_AND_COUNT_CASE3(AddSchemeSpecificPart, CountSchemeSpecificParts, code); +} + +// AddSchemeSpecificPart and GetSchemeSpecificPart ST kit Case +void FourthAbility::SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase1(int code) +{ + SKILLS_ADD_AND_GET_CASE1(AddSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase2(int code) +{ + SKILLS_ADD_AND_GET_CASE2(AddSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase3(int code) +{ + SKILLS_ADD_AND_GET_CASE3(AddSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase4(int code) +{ + SKILLS_ADD_AND_GET_CASE4(GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase5(int code) +{ + SKILLS_ADD_AND_GET_CASE5(AddSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase6(int code) +{ + SKILLS_ADD_AND_GET_CASE6(AddSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndGetSchemeSpecificPartCase7(int code) +{ + SKILLS_ADD_AND_GET_CASE7(AddSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +// AddSchemeSpecificPart and HasSchemeSpecificPart ST kit Case +void FourthAbility::SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase1(int code) +{ + SKILLS_ADD_AND_HAS_CASE1(AddSchemeSpecificPart, HasSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase2(int code) +{ + SKILLS_ADD_AND_HAS_CASE2(HasSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndHasSchemeSpecificPartCase3(int code) +{ + SKILLS_ADD_AND_HAS_CASE3(AddSchemeSpecificPart, HasSchemeSpecificPart, code); +} + +// AddSchemeSpecificPart,RemoveSchemeSpecificPart,CountSchemeSpecificParts and HasSchemeSpecificPart ST kit Case +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase1(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE1(AddSchemeSpecificPart, RemoveSchemeSpecificPart, HasSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase2(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE2(AddSchemeSpecificPart, RemoveSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase3(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE3(AddSchemeSpecificPart, RemoveSchemeSpecificPart, HasSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase4(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE4(AddSchemeSpecificPart, RemoveSchemeSpecificPart, HasSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase5(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE5(AddSchemeSpecificPart, RemoveSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase6(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE6(AddSchemeSpecificPart, RemoveSchemeSpecificPart, GetSchemeSpecificPart, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase7(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE7(AddSchemeSpecificPart, RemoveSchemeSpecificPart, CountSchemeSpecificParts, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase8(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE8(AddSchemeSpecificPart, RemoveSchemeSpecificPart, CountSchemeSpecificParts, code); +} + +void FourthAbility::SkillsAddSchemeSpecificPartAndRemoveSchemeSpecificPartCase9(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE9(AddSchemeSpecificPart, RemoveSchemeSpecificPart, CountSchemeSpecificParts, code); +} + +// AddPath_String and CountPaths ST kit Case +void FourthAbility::SkillsAddPathStringAndCountPathsCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(AddPath, CountPaths, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndCountPathsCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(AddPath, CountPaths, code, AddFunctionType::Add_String); +} + +// AddPath_String_MatchType and CountPaths ST kit Case +void FourthAbility::SkillsAddPathStringMatchTypeAndCountPathsCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(AddPath, CountPaths, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndCountPathsCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(AddPath, CountPaths, code, AddFunctionType::Add_String_MatchType); +} + +// AddPath_PatternMatcher and CountPaths ST kit Case +void FourthAbility::SkillsAddPathPatternAndCountPathsCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(AddPath, CountPaths, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndCountPathsCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(AddPath, CountPaths, code, AddFunctionType::Add_PatternMatcher); +} + +// CountPaths ST kit Case +void FourthAbility::SkillsCountPathsCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE2(CountPaths, code); +} + +// AddPath_String and GetPath ST kit Case +void FourthAbility::SkillsAddPathStringAndGetPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(AddPath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndGetPathCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(AddPath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndGetPathCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(AddPath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndGetPathCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(AddPath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndGetPathCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(AddPath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndGetPathCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(AddPath, GetPath, code, AddFunctionType::Add_String); +} + +// AddPath_String_MatchType and GetPath ST kit Case +void FourthAbility::SkillsAddPathStringMatchTypeAndGetPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(AddPath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndGetPathCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(AddPath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndGetPathCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(AddPath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndGetPathCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(AddPath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndGetPathCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(AddPath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndGetPathCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(AddPath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +// AddPath_PatternMatcher and GetPath ST kit Case +void FourthAbility::SkillsAddPathPatternAndGetPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(AddPath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndGetPathCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(AddPath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndGetPathCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(AddPath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndGetPathCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(AddPath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndGetPathCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(AddPath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndGetPathCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(AddPath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +// GetPath ST kit Case +void FourthAbility::SkillsGetPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE4(GetPath, code); +} + +// AddPath_String and HasPath ST kit Case +void FourthAbility::SkillsAddPathStringAndHasPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(AddPath, HasPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndHasPathCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(AddPath, HasPath, code, AddFunctionType::Add_String); +} + +// AddPath_String_MatchType and HasPath ST kit Case +void FourthAbility::SkillsAddPathStringMatchTypeAndHasPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(AddPath, HasPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndHasPathCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(AddPath, HasPath, code, AddFunctionType::Add_String_MatchType); +} + +// AddPath_PatternMatcher and HasPath ST kit Case +void FourthAbility::SkillsAddPathPatternAndHasPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(AddPath, HasPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndHasPathCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(AddPath, HasPath, code, AddFunctionType::Add_PatternMatcher); +} + +// HasPath ST kit Case +void FourthAbility::SkillsHasPathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE2(HasPath, code); +} + +// AddPath_String and RemovePath ST kit Case +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase7(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7(AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase8(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8(AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddPathStringAndRemovePathStringCase9(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9(AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_String); +} + +// AddPath_String_MatchType and RemovePathStringMatchType ST kit Case +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase7(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7( + AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase8(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8( + AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddPathStringMatchTypeAndRemovePathStringMatchTypeCase9(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9( + AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_String_MatchType); +} + +// AddPath_PatternMatcher and RemovePathPatternMatcher ST kit Case +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(AddPath, RemovePath, HasPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(AddPath, RemovePath, GetPath, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase7(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7(AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase8(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8(AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathPatternMatcherCase9(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9(AddPath, RemovePath, CountPaths, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE10(AddPath, RemovePath, HasPath, code); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE11(AddPath, RemovePath, CountPaths, code); +} + +void FourthAbility::SkillsAddPathPatternAndRemovePathCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE12(AddPath, CountPaths, code); +} + +// AddType_String and CountTypes ST kit Case +void FourthAbility::SkillsAddTypeStringAndCountTypesCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(AddType, CountTypes, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndCountTypesCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(AddType, CountTypes, code, AddFunctionType::Add_String); +} + +// AddType_String_MatchType and CountTypes ST kit Case +void FourthAbility::SkillsAddTypeStringMatchTypeAndCountTypesCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(AddType, CountTypes, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndCountTypesCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(AddType, CountTypes, code, AddFunctionType::Add_String_MatchType); +} + +// AddType_PatternMatcher and CountTypes ST kit Case +void FourthAbility::SkillsAddTypePatternAndCountTypesCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(AddType, CountTypes, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndCountTypesCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(AddType, CountTypes, code, AddFunctionType::Add_PatternMatcher); +} + +// CountTypes ST kit Case +void FourthAbility::SkillsCountTypesCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE2(CountTypes, code); +} + +// AddType_String and GetType ST kit Case +void FourthAbility::SkillsAddTypeStringAndGetTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(AddType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndGetTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(AddType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndGetTypeCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(AddType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndGetTypeCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(AddType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndGetTypeCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(AddType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndGetTypeCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(AddType, GetType, code, AddFunctionType::Add_String); +} + +// AddType_String_MatchType and GetType ST kit Case +void FourthAbility::SkillsAddTypeStringMatchTypeAndGetTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(AddType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndGetTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(AddType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndGetTypeCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(AddType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndGetTypeCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(AddType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndGetTypeCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(AddType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndGetTypeCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(AddType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +// AddType_PatternMatcher and GetType ST kit Case +void FourthAbility::SkillsAddTypePatternAndGetTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(AddType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndGetTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(AddType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndGetTypeCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(AddType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndGetTypeCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(AddType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndGetTypeCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(AddType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndGetTypeCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(AddType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +// GetType ST kit Case +void FourthAbility::SkillsGetTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE4(GetType, code); +} + +// AddType_String and HasType ST kit Case +void FourthAbility::SkillsAddTypeStringAndHasTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(AddType, HasType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndHasTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(AddType, HasType, code, AddFunctionType::Add_String); +} + +// AddType_String_MatchType and HasType ST kit Case +void FourthAbility::SkillsAddTypeStringMatchTypeAndHasTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(AddType, HasType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndHasTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(AddType, HasType, code, AddFunctionType::Add_String_MatchType); +} + +// AddType_PatternMatcher and HasType ST kit Case +void FourthAbility::SkillsAddTypePatternAndHasTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(AddType, HasType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndHasTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(AddType, HasType, code, AddFunctionType::Add_PatternMatcher); +} + +// HasType ST kit Case +void FourthAbility::SkillsHasTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE2(HasType, code); +} + +// AddType_String and RemoveType ST kit Case +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(AddType, RemoveType, HasType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(AddType, RemoveType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(AddType, RemoveType, HasType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(AddType, RemoveType, HasType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(AddType, RemoveType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(AddType, RemoveType, GetType, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase7(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7(AddType, RemoveType, CountTypes, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase8(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8(AddType, RemoveType, CountTypes, code, AddFunctionType::Add_String); +} + +void FourthAbility::SkillsAddTypeStringAndRemoveTypeStringCase9(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9(AddType, RemoveType, CountTypes, code, AddFunctionType::Add_String); +} + +// AddType_String_MatchType and RemoveTypeStringMatchType ST kit Case +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(AddType, RemoveType, HasType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(AddType, RemoveType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(AddType, RemoveType, HasType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(AddType, RemoveType, HasType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(AddType, RemoveType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(AddType, RemoveType, GetType, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase7(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7( + AddType, RemoveType, CountTypes, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase8(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8( + AddType, RemoveType, CountTypes, code, AddFunctionType::Add_String_MatchType); +} + +void FourthAbility::SkillsAddTypeStringMatchTypeAndRemoveTypeStringMatchTypeCase9(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9( + AddType, RemoveType, CountTypes, code, AddFunctionType::Add_String_MatchType); +} + +// AddType_PatternMatcher and RemoveTypePatternMatcher ST kit Case +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(AddType, RemoveType, HasType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(AddType, RemoveType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(AddType, RemoveType, HasType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(AddType, RemoveType, HasType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(AddType, RemoveType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(AddType, RemoveType, GetType, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase7(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7(AddType, RemoveType, CountTypes, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase8(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8(AddType, RemoveType, CountTypes, code, AddFunctionType::Add_PatternMatcher); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypePatternMatcherCase9(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9(AddType, RemoveType, CountTypes, code, AddFunctionType::Add_PatternMatcher); +} + +// AddType and RemoveType ST kit Case +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase1(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE10(AddType, RemoveType, HasType, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase2(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE11(AddType, RemoveType, CountTypes, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase3(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE12(AddType, CountTypes, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase4(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE13(AddType, CountTypes, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase5(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE14(AddType, HasType, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase6(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE15(AddType, HasType, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase7(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE16(AddType, CountTypes, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase8(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE17(AddType, CountTypes, code); +} + +void FourthAbility::SkillsAddTypePatternAndRemoveTypeCase9(int code) +{ + SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE18(AddType, HasType, code); +} + +// AddEntity and GetEntities ST kit Case +void FourthAbility::SkillAddEntityAndGetEntitiesCase1(int code) +{ + Skills skill; + skill.AddEntity(normalString); + bool result = (skill.GetEntities().size() == 1); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillAddEntityAndGetEntitiesCase2(int code) +{ + Skills skill; + skill.AddEntity(normalString); + skill.AddEntity(specialString); + skill.AddEntity("ams_kit_test"); + skill.AddEntity(normalString); + skill.AddEntity(specialString); + bool result = (skill.GetEntities().size() == 3); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillAddEntityAndGetEntitiesCase3(int code) +{ + Skills skill; + skill.AddEntity(normalString); + skill.AddEntity(specialString); + skill.AddEntity("ams_kit_test"); + skill.AddEntity(normalString); + skill.AddEntity(specialString); + bool result = (skill.CountEntities() == static_cast(skill.GetEntities().size())); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillAddEntityAndGetEntitiesCase4(int code) +{ + Skills skill; + skill.AddEntity(normalString); + bool result = (skill.GetEntity(0) == skill.GetEntities().at(0)); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillAddEntityAndGetEntitiesCase5(int code) +{ + Skills skill; + skill.AddEntity(normalString); + skill.AddEntity(specialString); + skill.RemoveEntity(normalString); + bool result = (specialString == skill.GetEntities().at(0)); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +// SetWantParams and GetWantParams ST kit Case +void FourthAbility::SkillSetAndGetWantParamsCase1(int code) +{ + SkillsGetWantParams(true, code); +} + +void FourthAbility::SkillSetAndGetWantParamsCase2(int code) +{ + SkillsGetWantParams(12345, code); +} + +void FourthAbility::SkillSetAndGetWantParamsCase3(int code) +{ + SkillsGetWantParams(123, code); +} + +void FourthAbility::SkillSetAndGetWantParamsCase4(int code) +{ + SkillsGetWantParams(specialString, code); +} + +void FourthAbility::SkillSetAndGetWantParamsCase5(int code) +{ + SkillsGetWantParams(normalString, code); +} + +void FourthAbility::SkillMatchCase1(int code) +{ + std::string strEntity = "entity.system.com"; + Skills skill; + skill.AddAction(normalString); + Want want; + want.SetAction(normalString); + skill.AddEntity(strEntity); + want.AddEntity(strEntity); + bool result = skill.Match(want); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillMatchCase2(int code) +{ + Skills skill; + skill.AddAction(normalString); + Want want; + want.SetAction(""); + bool result = !skill.Match(want); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillMatchCase3(int code) +{ + Skills skill; + std::string strEntity = "entity.system.com"; + skill.AddEntity(strEntity); + Want want; + want.AddEntity(strEntity); + bool result = skill.Match(want); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillMatchCase4(int code) +{ + Skills skill; + std::string strEntity = "entity.system.com"; + skill.AddEntity(strEntity); + Want want; + want.AddEntity(""); + bool result = !skill.Match(want); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillMatchCase5(int code) +{ + std::string strEntity = "entity.system.com"; + Skills skill; + skill.AddAction(specialString); + Want want; + want.SetAction(normalString); + skill.AddEntity(strEntity); + want.AddEntity(strEntity); + bool result = !skill.Match(want); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillMatchCase6(int code) +{ + Skills skill; + std::string strEntity = "entity.system.com"; + skill.AddEntity(strEntity); + Want want; + want.AddEntity(specialString); + bool result = !skill.Match(want); + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); +} + +void FourthAbility::SkillUnmarshallingCase1(int code) +{ + Skills skillIn; + Skills *skillOut = nullptr; + skillIn.AddEntity(""); + skillIn.AddAction(""); + skillIn.AddAuthority(""); + skillIn.AddScheme(""); + skillIn.AddPath(""); + skillIn.AddSchemeSpecificPart(""); + skillIn.AddType(""); + WantParams wantParams; + std::string keyStr = ""; + int valueInt = 123; + wantParams.SetParam(keyStr, Integer::Box(valueInt)); + skillIn.SetWantParams(wantParams); + Parcel in; + skillIn.Marshalling(in); + skillOut = Skills::Unmarshalling(in); + if (skillOut == nullptr) { + return; + } + + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, *skillOut))); + delete skillOut; + skillOut = nullptr; +} + +void FourthAbility::SkillUnmarshallingCase2(int code) +{ + Skills skillIn; + Skills *skillOut = nullptr; + skillIn.AddEntity(normalString); + skillIn.AddAction(normalString); + skillIn.AddAuthority(normalString); + skillIn.AddScheme(normalString); + skillIn.AddPath(normalString); + skillIn.AddSchemeSpecificPart(normalString); + skillIn.AddType(normalPathAndType); + WantParams wantParams; + std::string keyStr = normalString; + int valueInt = 123; + wantParams.SetParam(keyStr, Integer::Box(valueInt)); + skillIn.SetWantParams(wantParams); + Parcel in; + skillIn.Marshalling(in); + skillOut = Skills::Unmarshalling(in); + if (skillOut == nullptr) { + return; + } + + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, *skillOut))); + delete skillOut; + skillOut = nullptr; +} + +void FourthAbility::SkillUnmarshallingCase3(int code) +{ + Skills skillIn; + Skills *skillOut = nullptr; + skillIn.AddEntity(specialString); + skillIn.AddAction(specialString); + skillIn.AddAuthority(specialString); + skillIn.AddScheme(specialString); + skillIn.AddPath(specialString); + skillIn.AddSchemeSpecificPart(specialString); + skillIn.AddType(skillspecialTypeStr2); + WantParams wantParams; + std::string keyStr = specialString; + int valueInt = 123; + wantParams.SetParam(keyStr, Integer::Box(valueInt)); + skillIn.SetWantParams(wantParams); + Parcel in; + skillIn.Marshalling(in); + skillOut = Skills::Unmarshalling(in); + if (skillOut == nullptr) { + return; + } + + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, *skillOut))); + delete skillOut; + skillOut = nullptr; +} + +void FourthAbility::SkillUnmarshallingCase4(int code) +{ + Skills skillIn; + Skills *skillOut = nullptr; + skillIn.AddEntity(""); + skillIn.AddAction(""); + skillIn.AddAuthority(""); + skillIn.AddScheme(""); + skillIn.AddPath(""); + skillIn.AddSchemeSpecificPart(""); + skillIn.AddType(""); + skillIn.AddEntity(normalString); + skillIn.AddAction(normalString); + skillIn.AddAuthority(normalString); + skillIn.AddScheme(normalString); + skillIn.AddPath(normalString); + skillIn.AddSchemeSpecificPart(normalString); + skillIn.AddType(normalPathAndType); + skillIn.AddEntity(specialString); + skillIn.AddAction(specialString); + skillIn.AddAuthority(specialString); + skillIn.AddScheme(specialString); + skillIn.AddPath(specialString); + skillIn.AddSchemeSpecificPart(specialString); + skillIn.AddType(skillspecialTypeStr2); + WantParams wantParams; + int valueInt = 123; + std::string valueString = "kitST"; + wantParams.SetParam(normalString, Integer::Box(valueInt)); + wantParams.SetParam(specialString, String::Box(valueString)); + skillIn.SetWantParams(wantParams); + Parcel in; + skillIn.Marshalling(in); + skillOut = Skills::Unmarshalling(in); + if (skillOut == nullptr) { + return; + } + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, *skillOut))); + delete skillOut; + skillOut = nullptr; +} + +// Skills ST kit Case +void FourthAbility::SkillSkillsCase1(int code) +{ + SKILLS_ADD_AND_COUNT_CASE1(AddAction, CountActions, code); +} + +void FourthAbility::SkillSkillsCase2(int code) +{ + SKILLS_ADD_AND_GET_CASE1(AddAction, GetAction, code); +} + +void FourthAbility::SkillSkillsCase3(int code) +{ + SKILLS_ADD_AND_HAS_CASE1(AddEntity, HasEntity, code); +} + +void FourthAbility::SkillSkillsCase4(int code) +{ + SKILLS_ADD_AND_REMOVE_CASE1(AddEntity, RemoveEntity, HasEntity, code); +} + +// Skills_Skills ST kit Case +void FourthAbility::SkillSkillsSkillsCase1(int code) +{ + Skills skillIn; + skillIn.AddEntity(""); + skillIn.AddAction(""); + skillIn.AddAuthority(""); + skillIn.AddScheme(""); + skillIn.AddPath(""); + skillIn.AddSchemeSpecificPart(""); + skillIn.AddType(""); + Skills skillOut(skillIn); + + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, skillOut))); +} + +void FourthAbility::SkillSkillsSkillsCase2(int code) +{ + Skills skillIn; + skillIn.AddEntity(normalString); + skillIn.AddAction(normalString); + skillIn.AddAuthority(normalString); + skillIn.AddScheme(normalString); + skillIn.AddPath(normalString); + skillIn.AddSchemeSpecificPart(normalString); + skillIn.AddType(normalPathAndType); + Skills skillOut(skillIn); + + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, skillOut))); +} + +void FourthAbility::SkillSkillsSkillsCase3(int code) +{ + Skills skillIn; + skillIn.AddEntity(specialString); + skillIn.AddAction(specialString); + skillIn.AddAuthority(specialString); + skillIn.AddScheme(specialString); + skillIn.AddPath(specialString); + skillIn.AddSchemeSpecificPart(specialString); + skillIn.AddType(skillspecialTypeStr2); + Skills skillOut(skillIn); + + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, skillOut))); +} + +void FourthAbility::SkillSkillsSkillsCase4(int code) +{ + Skills skillIn; + skillIn.AddEntity(""); + skillIn.AddAction(""); + skillIn.AddAuthority(""); + skillIn.AddScheme(""); + skillIn.AddPath(""); + skillIn.AddSchemeSpecificPart(""); + skillIn.AddType(""); + skillIn.AddEntity(normalString); + skillIn.AddAction(normalString); + skillIn.AddAuthority(normalString); + skillIn.AddScheme(normalString); + skillIn.AddPath(normalString); + skillIn.AddSchemeSpecificPart(normalString); + skillIn.AddType(normalPathAndType); + skillIn.AddEntity(specialString); + skillIn.AddAction(specialString); + skillIn.AddAuthority(specialString); + skillIn.AddScheme(specialString); + skillIn.AddPath(specialString); + skillIn.AddSchemeSpecificPart(specialString); + skillIn.AddType(skillspecialTypeStr2); + Skills skillOut(skillIn); + + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(CompareSkills(skillIn, skillOut))); +} + +// Skills AddAction ST kit Case +void FourthAbility::SkillAddActionCase1(int code) +{ + SKILLS_ADD_CASE1(AddAction, CountActions, code); +} + +// Skills AddEntity ST kit Case +void FourthAbility::SkillAddEntityCase1(int code) +{ + SKILLS_ADD_CASE1(AddEntity, CountEntities, code); +} + +// Skills AddAuthority ST kit Case +void FourthAbility::SkillAddAuthorityCase1(int code) +{ + SKILLS_ADD_CASE1(AddAuthority, CountAuthorities, code); +} + +// Skills AddScheme ST kit Case +void FourthAbility::SkillAddSchemeCase1(int code) +{ + SKILLS_ADD_CASE1(AddScheme, CountSchemes, code); +} + +// Skills AddSchemeSpecificPart ST kit Case +void FourthAbility::SkillAddSchemeSpecificPartCase1(int code) +{ + SKILLS_ADD_CASE1(AddSchemeSpecificPart, CountSchemeSpecificParts, code); +} + +// Skills API ST End +void FourthAbility::OnStart(const Want &want) +{ + APP_LOGI("FourthAbility::onStart"); + Ability::OnStart(want); + SubscribeEvent(g_requPageFourthAbilitySTVector); + std::string eventData = GetAbilityName() + g_abilityStateOnStart; + TestUtils::PublishEvent(g_respPageFourthAbilityST, 0, eventData); +} + +void FourthAbility::OnStop() +{ + APP_LOGI("FourthAbility::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + std::string eventData = GetAbilityName() + g_abilityStateOnStop; + TestUtils::PublishEvent(g_respPageFourthAbilityST, 0, eventData); +} + +void FourthAbility::OnActive() +{ + APP_LOGI("FourthAbility::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + g_abilityStateOnActive; + TestUtils::PublishEvent(g_respPageFourthAbilityST, 0, eventData); +} + +void FourthAbility::OnInactive() +{ + APP_LOGI("FourthAbility::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + g_abilityStateOnInactive; + TestUtils::PublishEvent(g_respPageFourthAbilityST, 0, eventData); +} + +void FourthAbility::OnBackground() +{ + APP_LOGI("FourthAbility::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + g_abilityStateOnBackground; + TestUtils::PublishEvent(g_respPageFourthAbilityST, 0, eventData); +} + +void FourthAbility::OnForeground(const Want &want) +{ + APP_LOGI("FourthAbility::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + g_abilityStateOnForeground; + TestUtils::PublishEvent(g_respPageFourthAbilityST, 0, eventData); +} + +void FourthAbility::OnNewWant(const Want &want) +{ + APP_LOGI("FourthAbility::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + g_abilityStateOnNewWant; + TestUtils::PublishEvent(g_respPageFourthAbilityST, 0, eventData); +} + +void KitTestFourthEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (g_requPageFourthAbilityST == eventName) { + auto target = data.GetData(); + vector_str splitResult = TestUtils::split(target, "_"); + auto handle = 0; + auto api = 1; + auto code = 2; + auto paramMinSize = 3; + auto keyMap = splitResult.at(handle); + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && + splitResult.size() >= static_cast(paramMinSize)) { + auto apiIndex = atoi(splitResult.at(api).c_str()); + auto caseIndex = atoi(splitResult.at(code).c_str()); + mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); + } else { + if (keyMap == "TerminateAbility") { + KitTerminateAbility(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } + } +} + +void KitTestFourthEventSubscriber::SkillsApiStByCode(int apiIndex, int caseIndex, int code) +{ + if (fourthAbility_ != nullptr) { + fourthAbility_->SkillsApiStByCode(apiIndex, caseIndex, code); + } +} + +void KitTestFourthEventSubscriber::KitTerminateAbility() +{ + if (fourthAbility_ != nullptr) { + fourthAbility_->TerminateAbility(); + } +} + +REGISTER_AA(FourthAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..844f12ec941cbef0c02630eb53adf904c3a4b5e0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp @@ -0,0 +1,611 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "kit_test_ability_manager.h" +#include +#include +#include +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +namespace { +const std::string bundleName = "com.ohos.amsst.AppKitAbilityManager"; +const std::string abilityName = "KitTestAbilityManagerSecond"; +const std::string currentAbilityName = "KitTestAbilityManager"; +const std::string currentProcessInfo = "com.ohos.amsst.AppKit"; +const std::string launchAbilityName = "com.ohos.launcher.MainAbility"; +const std::string launchProcessInfo = "com.ohos.launcher"; +bool isMoveMissionToTop = false; +int moveMissionToTopCode = -1; +int isClearUpApplicationData = false; +int numThree = 3; +} // namespace + +void KitTestAbilityManager::SubscribeEvent(const vector_conststr &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void KitTestAbilityManager::AbilityManagerStByCode(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerStByCode"); + if (mapStKitFunc_.find(apiIndex) != mapStKitFunc_.end() && + static_cast(mapStKitFunc_[apiIndex].size()) > caseIndex) { + mapStKitFunc_[apiIndex][caseIndex](code); + } else { + APP_LOGI("AbilityManagerStByCode error"); + } +} + +void KitTestAbilityManager::CompareProcessName( + std::vector &info, const std::string &expectedName, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == expectedName) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == processName && processInfo.state_ == expectedState) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::StartAbilitySelf( + const std::string &bundleName, const std::string &abilityNmae, AbilityManagerApi api, int codeIndex, int code) +{ + MAP_STR_STR params; + params["apiIndex"] = std::to_string(static_cast(api)); + params["caseIndex"] = std::to_string(codeIndex); + params["code"] = std::to_string(code); + Want want = TestUtils::MakeWant("", abilityNmae, bundleName, params); + StartAbility(want); +} + +void KitTestAbilityManager::GetAllStackInfo(MissionStackInfo &missionStackInfo, int stackID) +{ + StackInfo stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); + for (const auto &missionInfo : stackInfo.missionStackInfos) { + if (missionInfo.id == stackID) { + missionStackInfo = missionInfo; + break; + } + } +} + +// GetAllRunningProcesses ST kit case +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase1"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, currentProcessInfo, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase2"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, launchProcessInfo, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase3"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + bool result = false; + for (auto runProcessInfo : info) { + if (runProcessInfo.processName_ == currentProcessInfo && processInfo->GetPid() == runProcessInfo.pid_) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase4"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessState(info, currentProcessInfo, AppProcessState::APP_STATE_FOREGROUND, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase8"); + auto index = 3; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase9"); + auto index = 4; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase10(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase10"); + auto index = 5; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +// GetAllStackInfo ST kit case +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase1"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + bool result = (missionStackInfo.missionRecords.size() == 1); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase2"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool result = (abilityInfos[0].mainName.compare(currentAbilityName) == 0); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase3"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + bool result = (missionStackInfo.missionRecords.size() == 1); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase4"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool result = (abilityInfos[0].mainName.compare(launchAbilityName) == 0); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase8"); + auto index = 3; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase9"); + auto index = 4; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +// QueryRecentAbilityMissionInfo ST kit case +void KitTestAbilityManager::QueryRecentAbilityMissionInfoParam(int numMax, int code, std::size_t size, int flags) +{ + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numMax, flags); + bool result = (info.size() == size); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase1"); + auto num = -1; + auto size = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_IGNORE_UNAVAILABLE); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase2"); + auto num = 3; + auto size = 0; + auto flag = -1; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase3"); + auto num = 3; + auto size = 0; + auto flag = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase4"); + auto num = 3; + auto size = 0; + auto flag = 3; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase5"); + auto num = 3; + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase6"); + auto num = 3; + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_IGNORE_UNAVAILABLE); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase7"); + std::vector info; + auto num = 3; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(num, RECENT_WITH_EXCLUDED); + bool result = false; + if (info.size() == 1 && info[0].size == 1) { + result = true; + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase8"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase9"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase10(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase10"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase11(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase11"); + auto num = std::numeric_limits::min(); + auto size = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase12(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase12"); + auto num = std::numeric_limits::max(); + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase13(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase13"); + auto num = 3; + auto size = 0; + auto flag = std::numeric_limits::min(); + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase14(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase14"); + auto num = 3; + auto size = 0; + auto flag = std::numeric_limits::max(); + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +// QueryRunningAbilityMissionInfo ST kit case +void KitTestAbilityManager::QueryRunningAbilityMissionInfoParam(int numMax, int code, std::size_t size) +{ + std::vector info; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numMax); + bool result = (info.size() == size); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase1"); + auto num = -1; + auto flag = 0; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase2"); + auto num = 0; + auto flag = 0; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase3"); + auto num = 3; + auto flag = 1; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase4"); + std::vector info; + auto num = 3; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(num); + bool result = false; + if (info.size() == 1 && info[0].size == 1) { + result = true; + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase8"); + QueryRunningAbilityMissionInfoParam(std::numeric_limits::min(), code, 0); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase9"); + QueryRunningAbilityMissionInfoParam(std::numeric_limits::max(), code, 1); +} + +// MoveMissionToTop ST kit case +void KitTestAbilityManager::AbilityManagerMoveMissionToTopCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerMoveMissionToTopCase1"); + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::MoveMissionToTop, 0, code); +} + +void KitTestAbilityManager::AbilityManagerMoveMissionToTopCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerMoveMissionToTopCase2"); + moveMissionToTopCode = code; + isMoveMissionToTop = true; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + StartAbility(wantEntity); +} + +// ClearUpApplicationData ST kit case +void KitTestAbilityManager::AbilityManagerClearUpApplicationDataCase1(int code) +{ + isClearUpApplicationData = true; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::ClearUpApplicationData, 0, code); +} + +void KitTestAbilityManager::OnStart(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::onStart"); + Ability::OnStart(want); + SubscribeEvent(g_requPageManagerAbilitySTVector); + std::string eventData = GetAbilityName() + g_abilityStateOnStart; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnStop() +{ + APP_LOGI("KitTestAbilityManager::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + std::string eventData = GetAbilityName() + g_abilityStateOnStop; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnActive() +{ + APP_LOGI("KitTestAbilityManager::OnActive"); + Ability::OnActive(); + if (isMoveMissionToTop) { + TestUtils::PublishEvent(g_respPageManagerAbilityST, moveMissionToTopCode, "1"); + isMoveMissionToTop = false; + moveMissionToTopCode = -1; + } + std::string eventData = GetAbilityName() + g_abilityStateOnActive; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnInactive() +{ + APP_LOGI("KitTestAbilityManager::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + g_abilityStateOnInactive; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnBackground() +{ + APP_LOGI("KitTestAbilityManager::OnBackground"); + Ability::OnBackground(); + if (isMoveMissionToTop) { + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == 1) { + GetAbilityManager()->MoveMissionToTop(info[0].id); + } + } + if (isClearUpApplicationData != false) { + AbilityManager::GetInstance().ClearUpApplicationData(currentProcessInfo); + isClearUpApplicationData = false; + } + std::string eventData = GetAbilityName() + g_abilityStateOnBackground; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnForeground(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + g_abilityStateOnForeground; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnNewWant(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + g_abilityStateOnNewWant; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +// KitTestManagerEventSubscriber Class +void KitTestManagerEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (g_requPageManagerAbilityST == eventName) { + auto target = data.GetData(); + auto handle = 0; + auto api = 1; + auto code = 2; + auto paramMinSize = 3; + vector_str splitResult = TestUtils::split(target, "_"); + auto keyMap = splitResult.at(handle); + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && + splitResult.size() >= static_cast(paramMinSize)) { + auto apiIndex = atoi(splitResult.at(api).c_str()); + auto caseIndex = atoi(splitResult.at(code).c_str()); + mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); + } else { + if (keyMap == "TerminateAbility") { + KitTerminateAbility(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } + } +} + +void KitTestManagerEventSubscriber::AbilityManagerStByCode(int apiIndex, int caseIndex, int code) +{ + if (kitTestAbility_ != nullptr) { + kitTestAbility_->AbilityManagerStByCode(apiIndex, caseIndex, code); + } +} + +void KitTestManagerEventSubscriber::KitTerminateAbility() +{ + if (kitTestAbility_ != nullptr) { + kitTestAbility_->TerminateAbility(); + } +} + +REGISTER_AA(KitTestAbilityManager) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cfd54c7116f9ef39a5078997851729a45e407011 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, Ability::GetState(), "onStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, Ability::GetState(), "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, Ability::GetState(), "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, Ability::GetState(), "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, Ability::GetState(), "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, Ability::GetState(), "OnForeground"); +} + +void MainAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("MainAbility::OnAbilityResult"); + Ability::OnAbilityResult(requestCode, resultCode, resultData); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_ON_ABILITY_RESULT, 0, resultData.ToUri()); +} + +void MainAbility::OnBackPressed() +{ + APP_LOGI("MainAbility::OnBackPressed"); + Ability::OnBackPressed(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_ON_BACK_PRESSED, 0, ""); +} + +void MainAbility::OnNewWant(const Want &want) +{ + APP_LOGI("MainAbility::OnNewWant"); + Ability::OnNewWant(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_ON_NEW_WANT, 0, want.ToUri()); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIRST, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { + auto target = data.GetData(); + auto handle = 0; + auto api = 1; + auto code = 2; + auto caseInfo = TestUtils::split(target, "_"); + auto paramMinSize = 3; + if (caseInfo.size() < static_cast(paramMinSize)) { + return; + } + if (mapTestFunc_.find(caseInfo[handle]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[handle]](std::stoi(caseInfo[api]), std::stoi(caseInfo[code]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// get current ability name +void MainAbility::GetAbilityNameCase1(int code) +{ + std::string abilityName = Ability::GetAbilityName(); + bool result = abilityName == "MainAbility"; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// get AbilityPackage object +void MainAbility::GetAbilityPackageCase1(int code) +{ + auto abilityPackage = Ability::GetAbilityPackage(); + bool result = abilityPackage != nullptr; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// get want from empty Want +void MainAbility::GetWantCase1(int code) +{ + auto getWant = Ability::GetWant(); + bool result = getWant == nullptr; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// set and get want +void MainAbility::GetWantCase2(int code) +{ + std::string action = "action"; + Want setWant; + setWant.SetAction(action); + Ability::SetWant(setWant); + bool result = Ability::GetWant()->GetAction() == action; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// get want repeatedly +void MainAbility::GetWantCase3(int code) +{ + std::string action = "action"; + bool result = true; + std::string tmpAction; + for (int i = 0; i < pressureTimes; i++) { + Want setWant; + tmpAction = action + std::to_string(i); + setWant.SetAction(tmpAction); + Ability::SetWant(setWant); + result = result && Ability::GetWant()->GetAction() == tmpAction; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::GetWindowCase1(int code) +{ + APP_LOGI("MainAbility::GetWindowCase1"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::DumpCase1(int code) +{ + APP_LOGI("MainAbility::DumpCase1"); + std::string dumpInfo; + Ability::Dump(dumpInfo); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// set empty Want +void MainAbility::SetWantCase1(int code) +{ + std::string empty; + Want setWant; + Ability::SetWant(setWant); + bool result = Ability::GetWant()->GetAction() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// set want repeatedly +void MainAbility::SetWantCase2(int code) +{ + std::string action = "action"; + std::string tmpAction; + for (int i = 0; i < pressureTimes; i++) { + Want setWant; + tmpAction = action + std::to_string(i); + setWant.SetAction(tmpAction); + Ability::SetWant(setWant); + } + bool result = Ability::GetWant()->GetAction() == tmpAction; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp new file mode 100755 index 0000000000000000000000000000000000000000..eab7fd56f89f5c64c5562a4dcf793523d22bb1d0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp @@ -0,0 +1,5282 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/base_types.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" +#include "ohos/aafwk/content/operation_builder.h" +#include "test_utils.h" +#include "uri.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace AAFwk; +using namespace OHOS::EventFwk; +namespace { +constexpr size_t ARRAY_SIZE = 10000; +constexpr int LARGE_STR_LEN = 65534; +constexpr int SMALL_INT = 5; +constexpr unsigned setValue = 128; +constexpr unsigned addValue = 64; +constexpr unsigned removeValue = 128; +constexpr int even = 2; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +std::string WANT_HEADER = "#Intent;"; +} // namespace + +bool SecondAbility::CompareWantNoParams(const Want &source, const Want &target) +{ + bool result = source.GetAction() == target.GetAction(); + result = result && source.GetFlags() == target.GetFlags(); + result = result && source.GetType() == target.GetType(); + result = result && source.GetEntities() == target.GetEntities(); + result = result && source.GetElement() == target.GetElement(); + return result; +} + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "Init"); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::onStart"); + SubscribeEvent(); + + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnStop"); +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnActive"); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnForeground"); +} + +void SecondAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("SecondAbility::OnAbilityResult"); + Ability::OnAbilityResult(requestCode, resultCode, resultData); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnAbilityResult"); +} + +void SecondAbility::OnBackPressed() +{ + APP_LOGI("SecondAbility::OnBackPressed"); + Ability::OnBackPressed(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnBackPressed"); +} + +void SecondAbility::OnNewWant(const Want &want) +{ + APP_LOGI("SecondAbility::OnNewWant"); + Ability::OnNewWant(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnNewWant"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + auto paramMinSize = 3; + if (caseInfo.size() < static_cast(paramMinSize)) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestWant(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestWant"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// copy constructor +void SecondAbility::WantCopyCase1(int code) +{ + Want want; + std::string action = "WantCopyCase1"; + want = want.SetAction(action); + Want wantCopy = Want(want); + bool result = (wantCopy.GetAction().compare(action) == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// assignment constructor +void SecondAbility::WantAssignCase1(int code) +{ + Want want; + std::string action = "WantAssignCase1"; + want = want.SetAction(action); + Want wantAssign = want; + bool result = (wantAssign.GetAction().compare(action) == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add empty entity +void SecondAbility::WantAddEntityCase1(int code) +{ + std::string empty; + Want want; + want.AddEntity(""); + auto entities = want.GetEntities(); + bool result = (entities.size() == 1); + result = result && (entities.at(0) == empty); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add entity with special character +void SecondAbility::WantAddEntityCase2(int code) +{ + std::string entity = "~!@#$%^&*()_+`-=:\";\'<>?,./\\|\a\b\f\n\r\t\v\0\111\xAB"; + Want want; + want.AddEntity(entity); + auto entities = want.GetEntities(); + bool result = (entities.size() == 1); + result = result && (entities.at(0) == entity); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add entity continuously +void SecondAbility::WantAddEntityCase3(int code) +{ + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.AddEntity(std::string(i, 'A')); + } + bool result = (want.GetEntities().size() == pressureTimes); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add flags min +void SecondAbility::WantAddFlagsCase1(int code) +{ + unsigned flag = 0; + Want want; + want.AddFlags(flag); + bool result = (want.GetFlags() == flag); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add flags max +void SecondAbility::WantAddFlagsCase2(int code) +{ + Want want; + want.AddFlags(std::numeric_limits::max()); + bool result = (want.GetFlags() == std::numeric_limits::max()); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add flags continuously +void SecondAbility::WantAddFlagsCase3(int code) +{ + Want want; + unsigned int sum = 0; + for (int i = 0; i < pressureTimes; i++) { + want.AddFlags(i); + sum |= static_cast(i); + } + bool result = (want.GetFlags() == sum); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// clear want normally +void SecondAbility::WantClearWantCase1(int code) +{ + std::string empty; + OHOS::AppExecFwk::ElementName emptyElementName; + Want want; + want.SetType("type"); + want.SetAction("action"); + want.SetFlags(1); + auto elementName = OHOS::AppExecFwk::ElementName("deviceId", "bundleName", "abilityName"); + want.SetElement(elementName); + AAFwk::WantParams parameters; + std::string keyString = "keyString"; + parameters.SetParam(keyString, AAFwk::String::Box("valueString")); + want.SetParams(parameters); + want.AddEntity("wantEntity"); + Want::ClearWant(&want); + bool result = (want.GetType() == empty); + result = result && (want.GetAction() == empty); + result = result && (want.GetFlags() == 0); + result = result && (want.GetElement() == emptyElementName); + result = result && (want.GetStringParam(keyString) == empty); + result = result && (want.GetEntities().size() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// clear want continuously +void SecondAbility::WantClearWantCase2(int code) +{ + std::string empty; + Want want; + want.SetType("type"); + for (int i = 0; i < pressureTimes; i++) { + Want::ClearWant(&want); + } + bool result = (want.GetType() == empty); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// count entity on empty Want +void SecondAbility::WantCountEntitiesCase1(int code) +{ + Want want; + bool result = (want.CountEntities() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// count entity after add entity +void SecondAbility::WantCountEntitiesCase2(int code) +{ + Want want; + const int entityCount = 3; + for (int i = 0; i < entityCount; i++) { + want.AddEntity("wantEntity" + std::to_string(i)); + } + bool result = (want.CountEntities() == entityCount); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format normal mime type +void SecondAbility::WantFormatMimeTypeCase1(int code) +{ + std::string mimeType = "WantFormatMimeType;Case1"; + std::string mimeTypeFormat = "wantformatmimetype"; + bool result = mimeTypeFormat.compare(Want::FormatMimeType(mimeType)) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format mime type uppercase +void SecondAbility::WantFormatMimeTypeCase2(int code) +{ + std::string mimeType = "WANTFORMATMIMETYPE/CASE1"; + std::string mimeTypeFormat = "wantformatmimetype/case1"; + bool result = mimeTypeFormat.compare(Want::FormatMimeType(mimeType)) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format mime type with special character +void SecondAbility::WantFormatMimeTypeCase3(int code) +{ + std::string mimeType = "WantFormatMimeType~!@#$%^&*()_+`-=:\"\\',.<>?;Case1"; + std::string mimeTypeFormat = "wantformatmimetype~!@#$%^&*()_+`-=:\"\\',.<>?"; + bool result = mimeTypeFormat.compare(Want::FormatMimeType(mimeType)) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +// format mime type with space and tab +void SecondAbility::WantFormatMimeTypeCase4(int code) +{ + std::string mimeType = "Want Format Mime \tType;Case1"; + std::string mimeTypeFormat = "wantformatmime\ttype"; + bool result = mimeTypeFormat.compare(Want::FormatMimeType(mimeType)) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format normal type +void SecondAbility::WantFormatTypeCase1(int code) +{ + std::string mimeType = "WantFormatMimeType;Case1"; + std::string mimeTypeFormat = "wantformatmimetype"; + Want want; + want = want.FormatType(mimeType); + bool result = want.GetType().compare(mimeTypeFormat) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format type uppercase +void SecondAbility::WantFormatTypeCase2(int code) +{ + std::string mimeType = "WANTFORMATMIMETYPE;CASE1"; + std::string mimeTypeFormat = "wantformatmimetype"; + Want want; + want = want.FormatType(mimeType); + bool result = want.GetType().compare(mimeTypeFormat) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format type with special character +void SecondAbility::WantFormatTypeCase3(int code) +{ + std::string mimeType = "WantFormatMimeType~!@#$%^&*()_+`-=:\"\\',.<>?;/Case1"; + std::string mimeTypeFormat = "wantformatmimetype~!@#$%^&*()_+`-=:\"\\',.<>?"; + Want want; + want = want.FormatType(mimeType); + bool result = want.GetType().compare(mimeTypeFormat) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format type with space, upper case and tab +void SecondAbility::WantFormatTypeCase4(int code) +{ + std::string mimeType = "Want Format Mime \tType;Case1"; + std::string mimeTypeFormat = "wantformatmime\ttype"; + Want want; + want = want.FormatType(mimeType); + bool result = want.GetType().compare(mimeTypeFormat) == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format duplicated action +void SecondAbility::WantFormatUriCase1(int code) +{ + std::string uriString = "HTTP://www.baidu.com"; + Uri uri(uriString); + Want want; + want = want.FormatUri(uri); + auto operation = want.GetOperation(); + bool result = (operation.GetUri().ToString().compare("http://www.baidu.com") == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format ElementName +void SecondAbility::WantFormatUriCase2(int code) +{ + std::string uri = "WWW.baidu.com"; + Want want; + want = want.FormatUri(uri); + auto operation = want.GetOperation(); + bool result = (operation.GetUri().ToString().compare("WWW.baidu.com") == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format string parameter +void SecondAbility::WantFormatUriCase3(int code) +{ + std::string uri = ""; + Want want; + want = want.FormatUri(uri); + auto operation = want.GetOperation(); + bool result = (operation.GetUri().ToString().compare("") == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// format return value of ToUri +void SecondAbility::WantFormatUriCase4(int code) +{ + std::string uri = "Http://"; + Want want; + want = want.FormatUri(uri); + auto operation = want.GetOperation(); + bool result = (operation.GetUri().ToString().compare("http://") == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::WantFormatUriAndTypeCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::WantFormatUriAndTypeCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::WantFormatUriAndTypeCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::WantFormatUriAndTypeCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty action +void SecondAbility::WantGetActionCase1(int code) +{ + std::string empty; + Want want; + bool result = want.GetAction() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get action +void SecondAbility::WantGetActionCase2(int code) +{ + std::string action("action"); + Want want; + want.SetAction(action); + bool result = want.GetAction() == action; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get action continuously +void SecondAbility::WantGetActionCase3(int code) +{ + std::string action("action"); + Want want; + want.SetAction(action); + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetAction() == action); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty bundle +void SecondAbility::WantGetBundleCase1(int code) +{ + std::string empty; + Want want; + bool result = want.GetBundle() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get bundle +void SecondAbility::WantGetBundleCase2(int code) +{ + std::string bundle("bundle"); + Want want; + want.SetBundle(bundle); + bool result = want.GetBundle() == bundle; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get bundle continuously +void SecondAbility::WantGetBundleCase3(int code) +{ + std::string bundle("bundle"); + Want want; + want.SetBundle(bundle); + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetBundle() == bundle); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty entities +void SecondAbility::WantGetEntitiesCase1(int code) +{ + std::vector empty; + Want want; + bool result = want.GetEntities() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add entity and get entities +void SecondAbility::WantGetEntitiesCase2(int code) +{ + std::vector entities = {"entity1", "entity2", "entity3"}; + Want want; + for (const auto &entity : entities) { + want.AddEntity(entity); + } + bool result = want.GetEntities() == entities; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add entity and get entities continuously +void SecondAbility::WantGetEntitiesCase3(int code) +{ + std::vector entities = {"entity1", "entity2", "entity3"}; + Want want; + for (const auto &entity : entities) { + want.AddEntity(entity); + } + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetEntities() == entities); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty element +void SecondAbility::WantGetElementCase1(int code) +{ + ElementName emptyElement; + Want want; + bool result = want.GetElement() == emptyElement; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get element +void SecondAbility::WantGetElementCase2(int code) +{ + ElementName element("deviceId", "bundleName", "abilityName"); + Want want; + want.SetElement(element); + bool result = want.GetElement() == element; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get element continuously +void SecondAbility::WantGetElementCase3(int code) +{ + ElementName element("deviceId", "bundleName", "abilityName"); + Want want; + want.SetElement(element); + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetElement() == element); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty uri +void SecondAbility::WantGetUriCase1(int code) +{ + Uri uri(""); + Want want; + bool result = want.GetUri().Equals(uri); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get uri +void SecondAbility::WantGetUriCase2(int code) +{ + std::string uriString = WANT_HEADER + "action=action;end"; + Uri uri(uriString); + Want want; + want.SetUri(uriString); + bool result = want.GetUri().Equals(uri); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get uri continuously +void SecondAbility::WantGetUriCase3(int code) +{ + std::string uriString = WANT_HEADER + "action=action;end"; + Uri uri(uriString); + Want want; + want.SetUri(uriString); + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetUri().Equals(uri)); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty uri string +void SecondAbility::WantGetUriStringCase1(int code) +{ + std::string emptyUri(""); + Want want; + bool result = want.GetUriString() == emptyUri; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set property and get uri string +void SecondAbility::WantGetUriStringCase2(int code) +{ + std::string uriString(WANT_HEADER + "action=action;end"); + Want want; + want.SetAction(uriString); + bool result = want.GetAction() == uriString; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set uri and get uri string +void SecondAbility::WantGetUriStringCase3(int code) +{ + std::string uriString(WANT_HEADER + "action=action;end"); + Want want; + want.SetUri(uriString); + bool result = want.GetUriString() == uriString; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get uri string continuously +void SecondAbility::WantGetUriStringCase4(int code) +{ + std::string uriString(WANT_HEADER + "action=action;end"); + Want want; + want.SetUri(uriString); + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetUriString() == uriString); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty flags +void SecondAbility::WantGetFlagsCase1(int code) +{ + Want want; + bool result = want.GetFlags() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get flags +void SecondAbility::WantGetFlagsCase2(int code) +{ + unsigned flags = 128; + Want want; + want.SetFlags(flags); + bool result = want.GetFlags() == flags; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get flags continuously +void SecondAbility::WantGetFlagsCase3(int code) +{ + unsigned flags = 128; + Want want; + want.SetFlags(flags); + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetFlags() == flags); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::WantGetSchemeCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::WantGetSchemeCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::WantGetSchemeCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::WantGetSchemeCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty type +void SecondAbility::WantGetTypeCase1(int code) +{ + std::string empty; + Want want; + bool result = want.GetType() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get type +void SecondAbility::WantGetTypeCase2(int code) +{ + std::string type = "typeString"; + Want want; + want.SetType(type); + bool result = want.GetType() == type; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get type continuously +void SecondAbility::WantGetTypeCase3(int code) +{ + std::string type = "typeString"; + Want want; + want.SetType(type); + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + result = result && (want.GetType() == type); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// no any entity +void SecondAbility::WantHasEntityCase1(int code) +{ + std::string entity = "entity"; + Want want; + bool result = !want.HasEntity(entity); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// no target entity +void SecondAbility::WantHasEntityCase2(int code) +{ + std::string entity = "entity"; + std::string entity2 = "entity2"; + Want want; + want.AddEntity(entity); + bool result = !want.HasEntity(entity2); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// target entity exists +void SecondAbility::WantHasEntityCase3(int code) +{ + std::string entity = "entity"; + std::string entity2 = "entity2"; + Want want; + want.AddEntity(entity); + want.AddEntity(entity2); + bool result = want.HasEntity(entity); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// HasEntity continuously +void SecondAbility::WantHasEntityCase4(int code) +{ + std::string entity = "entity"; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + std::string tmpEntity = entity + std::to_string(i); + want.AddEntity(tmpEntity); + result = result && want.HasEntity(tmpEntity); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// MakeMainAbility with empty ElementName +void SecondAbility::WantMakeMainAbilityCase1(int code) +{ + ElementName element; + Want *want = Want::MakeMainAbility(element); + bool result = want != nullptr; + if (want != nullptr) { + result = result && want->GetAction() == Want::ACTION_HOME; + result = result && want->HasEntity(Want::ENTITY_HOME); + result = result && want->GetElement() == element; + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// MakeMainAbility with normal ElementName +void SecondAbility::WantMakeMainAbilityCase2(int code) +{ + ElementName element("deviceId", "bundleName", "abilityName"); + Want *want = Want::MakeMainAbility(element); + bool result = want != nullptr; + if (want != nullptr) { + result = result && want->GetAction() == Want::ACTION_HOME; + result = result && want->HasEntity(Want::ENTITY_HOME); + result = result && want->GetElement() == element; + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall empty Want +void SecondAbility::WantMarshallingCase1(int code) +{ + Want want; + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (CompareWantNoParams(want, *unmarshallWant)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with action +void SecondAbility::WantMarshallingCase2(int code) +{ + Want want; + want.SetAction("action"); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetAction() == unmarshallWant->GetAction()); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with type +void SecondAbility::WantMarshallingCase3(int code) +{ + Want want; + want.SetType("type"); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetType() == unmarshallWant->GetType()); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with flags +void SecondAbility::WantMarshallingCase4(int code) +{ + Want want; + auto flag = 99; + want.SetFlags(flag); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetFlags() == unmarshallWant->GetFlags()); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with entity +void SecondAbility::WantMarshallingCase5(int code) +{ + Want want; + want.AddEntity("first entity"); + want.AddEntity("second entity"); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetEntities() == unmarshallWant->GetEntities()); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with element +void SecondAbility::WantMarshallingCase6(int code) +{ + Want want; + ElementName element("deviceId", "bundleName", "abilityName"); + want.SetElement(element); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetElement() == unmarshallWant->GetElement()); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with bool parameter +void SecondAbility::WantMarshallingCase7(int code) +{ + Want want; + std::string key = "key"; + bool value = true; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetBoolParam(key, !value) == unmarshallWant->GetBoolParam(key, !value)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with bool array parameter +void SecondAbility::WantMarshallingCase8(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {true, true, false, true}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetBoolArrayParam(key) == unmarshallWant->GetBoolArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with byte parameter +void SecondAbility::WantMarshallingCase9(int code) +{ + Want want; + std::string key = "key"; + byte value = 9; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetByteParam(key, 0) == unmarshallWant->GetByteParam(key, 1)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with byte array parameter +void SecondAbility::WantMarshallingCase10(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {1, 2, 3, 4}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetByteArrayParam(key) == unmarshallWant->GetByteArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with char parameter +void SecondAbility::WantMarshallingCase11(int code) +{ + Want want; + std::string key = "key"; + zchar value = 'a'; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetCharParam(key, 0) == unmarshallWant->GetCharParam(key, 1)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with char array parameter +void SecondAbility::WantMarshallingCase12(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {'a', 'b', 'c', 'd'}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetCharArrayParam(key) == unmarshallWant->GetCharArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with int parameter +void SecondAbility::WantMarshallingCase13(int code) +{ + Want want; + std::string key = "key"; + int value = 99; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetIntParam(key, 0) == unmarshallWant->GetIntParam(key, 1)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with int array parameter +void SecondAbility::WantMarshallingCase14(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {99, 999, 9999, 99999}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetIntArrayParam(key) == unmarshallWant->GetIntArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with double parameter +void SecondAbility::WantMarshallingCase15(int code) +{ + Want want; + std::string key = "key"; + double value = 99.9; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetDoubleParam(key, 0) == unmarshallWant->GetDoubleParam(key, 1)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with double array parameter +void SecondAbility::WantMarshallingCase16(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {99.9, 999.9, 9999.9, 99999.9}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetDoubleArrayParam(key) == unmarshallWant->GetDoubleArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with float parameter +void SecondAbility::WantMarshallingCase17(int code) +{ + Want want; + std::string key = "key"; + float value = 99.9f; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetFloatParam(key, 0) == unmarshallWant->GetFloatParam(key, 1)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with float array parameter +void SecondAbility::WantMarshallingCase18(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {99.9f, 999.9f, 9999.9f, 99999.9f}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetFloatArrayParam(key) == unmarshallWant->GetFloatArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with long parameter +void SecondAbility::WantMarshallingCase19(int code) +{ + Want want; + std::string key = "key"; + long value = 99L; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetLongParam(key, 0) == unmarshallWant->GetLongParam(key, 1)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with long array parameter +void SecondAbility::WantMarshallingCase20(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {99L, 999L, 9999L, 99999L}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetLongArrayParam(key) == unmarshallWant->GetLongArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with short parameter +void SecondAbility::WantMarshallingCase21(int code) +{ + Want want; + std::string key = "key"; + short value = 98; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetShortParam(key, 0) == unmarshallWant->GetShortParam(key, 1)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with short array parameter +void SecondAbility::WantMarshallingCase22(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {98, 998, 998, 998}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetShortArrayParam(key) == unmarshallWant->GetShortArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with string parameter +void SecondAbility::WantMarshallingCase23(int code) +{ + Want want; + std::string key = "key"; + string value = "value"; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetStringParam(key) == unmarshallWant->GetStringParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// marshall and unmarshall Want with string array parameter +void SecondAbility::WantMarshallingCase24(int code) +{ + Want want; + std::string key = "key"; + std::vector value = {"aa", "bb", "cc", "dd"}; + want.SetParam(key, value); + Parcel parcel; + bool result = want.Marshalling(parcel); + Want *unmarshallWant = Want::Unmarshalling(parcel); + result = result && (unmarshallWant != nullptr); + if (unmarshallWant) { + result = result && (want.GetStringArrayParam(key) == unmarshallWant->GetStringArrayParam(key)); + delete unmarshallWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// remove entity from empty Want +void SecondAbility::WantRemoveEntityCase1(int code) +{ + Want want; + std::string entity("entity"); + bool result = want.HasEntity(entity) == false; + result = result && (want.CountEntities() == 0); + want.RemoveEntity(entity); + result = result && (want.HasEntity(entity) == false); + result = result && (want.GetEntities().size() == 0); + result = result && (want.CountEntities() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add and remove normal entity +void SecondAbility::WantRemoveEntityCase2(int code) +{ + Want want; + std::string entity("entity"); + want.AddEntity(entity); + bool result = want.HasEntity(entity) == true; + result = result && (want.CountEntities() == 1); + want.RemoveEntity(entity); + result = result && (want.HasEntity(entity) == false); + result = result && (want.CountEntities() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add and remove entity alternative +void SecondAbility::WantRemoveEntityCase3(int code) +{ + Want want; + std::vector entities {"entity1", "entity2", "entity3"}; + bool result = true; + for (const auto &entity : entities) { + want.AddEntity(entity); + result = result && (want.HasEntity(entity) == true); + } + result = result && (want.GetEntities() == entities); + result = result && (want.CountEntities() == (int)entities.size()); + for (const auto &entity : entities) { + want.RemoveEntity(entity); + result = result && (want.HasEntity(entity) == false); + } + result = result && (want.CountEntities() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add and remove entity with special character +void SecondAbility::WantRemoveEntityCase4(int code) +{ + std::string entity = "~!@#$%^&*()_+`-={}|[]\\:\";\'<>?,./ \t"; + Want want; + want.AddEntity(entity); + bool result = want.HasEntity(entity) == true; + want.RemoveEntity(entity); + result = result && (want.HasEntity(entity) == false); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add entity repeatedly +void SecondAbility::WantRemoveEntityCase5(int code) +{ + std::string entity = "entity"; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.AddEntity(entity + std::to_string(i)); + } + bool result = (want.CountEntities() == pressureTimes); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// remove flags from empty Want +void SecondAbility::WantRemoveFlagsCase1(int code) +{ + unsigned flags = 1; + Want want; + bool result = (want.GetFlags() == 0); + want.RemoveFlags(flags); + result = result && (want.GetFlags() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add and remove flags +void SecondAbility::WantRemoveFlagsCase2(int code) +{ + unsigned flags = 1; + Want want; + bool result = (want.GetFlags() == 0); + want.AddFlags(flags); + result = result && (want.GetFlags() == flags); + want.RemoveFlags(flags); + result = result && (want.GetFlags() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and remove flags +void SecondAbility::WantRemoveFlagsCase3(int code) +{ + unsigned flags = std::numeric_limits::max(); + unsigned removedFlags = 1; + Want want; + bool result = (want.GetFlags() == 0); + want.SetFlags(flags); + result = result && (want.GetFlags() == flags); + want.RemoveFlags(removedFlags); + result = result && (want.GetFlags() == flags - removedFlags); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set, add and remove flags +void SecondAbility::WantRemoveFlagsCase4(int code) +{ + unsigned flags = 32; + unsigned addFlags = 1024; + unsigned notExistFlags = 1; + Want want; + bool result = (want.GetFlags() == 0); + want.SetFlags(flags); + want.AddFlags(addFlags); + result = result && (want.GetFlags() == flags + addFlags); + want.RemoveFlags(notExistFlags); + result = result && (want.GetFlags() == flags + addFlags); + want.RemoveFlags(addFlags); + result = result && (want.GetFlags() == flags); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// remove flags repeatedly +void SecondAbility::WantRemoveFlagsCase5(int code) +{ + Want want; + unsigned flags = std::numeric_limits::max(); + unsigned removedFlags = 0; + want.SetFlags(flags); + for (unsigned i = 0; i < pressureTimes; i++) { + want.RemoveFlags(i); + removedFlags |= i; + } + bool result = (want.GetFlags() == flags - removedFlags); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse uri that has only key, no equals sign and value +void SecondAbility::WantParseUriCase1(int code) +{ + std::string uri = WANT_HEADER + "action;end"; + Want *want = Want::ParseUri(uri); + bool result = (want == nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "entity;end"; + want = Want::ParseUri(uri); + result = result && (want == nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "device;end"; + want = Want::ParseUri(uri); + result = result && (want == nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "bundle;end"; + want = Want::ParseUri(uri); + result = result && (want == nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "ability;end"; + want = Want::ParseUri(uri); + result = result && (want == nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "flag;end"; + want = Want::ParseUri(uri); + result = result && (want == nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "param;end"; + want = Want::ParseUri(uri); + result = result && (want == nullptr); + if (want) { + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse string parameters +void SecondAbility::WantParseUriCase2(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyString"; + std::string value = "valueString"; + std::string uriKey = AAFwk::String::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + value + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetStringParam(key) == value); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse uri that has special character +void SecondAbility::WantParseUriCase3(int code) +{ + std::string action = "\\"; + std::string entity = "../../../jj/j=075/./.;;/07507399/\\\\;;--==.com.\a\b\tfoobar.vide\073\\075"; + unsigned int flag = 0x0f0f0f0f; + std::string key = "\\kkk=.=;"; + std::string value = "==\\\\\\.;\\;\\;\\=\\\073075\\\\075073"; + + Want wantOrigin; + wantOrigin.SetAction(action); + wantOrigin.AddEntity(entity); + wantOrigin.AddFlags(flag); + wantOrigin.SetParam(key, value); + std::string uri = wantOrigin.ToUri(); + + Want *wantNew = Want::ParseUri(uri); + bool result = (wantNew != nullptr); + if (wantNew != nullptr) { + result = result && (wantNew->GetAction().compare(action) == 0); + for (auto entityItem : wantNew->GetEntities()) { + result = result && (entityItem.compare(entity) == 0); + } + result = result && (wantNew->GetFlags() == flag); + result = result && (wantNew->GetStringParam(key).compare(value) == 0); + delete wantNew; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse flag that is a hexadecimal starting with "0X" +void SecondAbility::WantParseUriCase4(int code) +{ + unsigned int flag = 0X12345678; + std::string uri = WANT_HEADER + "flag=0X12345678;end"; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetFlags() == flag); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse flag that has no value +void SecondAbility::WantParseUriCase5(int code) +{ + std::string uri = WANT_HEADER + "flag=;end"; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetFlags() == static_cast(0)); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse uri that has no head WANT_HEADER + "" +void SecondAbility::WantParseUriCase6(int code) +{ + std::string uri = "action=want.action.VIEW;end"; + Want *want = Want::ParseUri(uri); + bool result = (want == nullptr); + if (want != nullptr) { + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse uri that flag type is string +void SecondAbility::WantParseUriCase7(int code) +{ + std::string uri = WANT_HEADER + "action=want.action.VIEW;flag=\"123\";end"; + Want *want = Want::ParseUri(uri); + bool result = (want == nullptr); + if (want != nullptr) { + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse uri that has only all keys and equals sign, no value +void SecondAbility::WantParseUriCase8(int code) +{ + std::string empty; + std::string uri = WANT_HEADER + "action=;entity=;device=;bundle=;ability=;flag=;end"; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + + if (want) { + result = result && (want->GetAction() == empty); + for (auto entityItem : want->GetEntities()) { + result = result && (entityItem == empty); + } + result = result && (want->GetFlags() == (unsigned int)0); + OHOS::AppExecFwk::ElementName element; + result = result && (want->GetElement() == element); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse empty string +void SecondAbility::WantParseUriCase9(int code) +{ + std::string uri; + Want *want = Want::ParseUri(uri); + bool result = (want == nullptr); + if (want) { + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse parameter of float array and string array +void SecondAbility::WantParseUriCase10(int code) +{ + Want wantOrigin; + std::string keyFloatArray = "keyFloatArray"; + std::string keyStringArray = "keyStringArray"; + std::vector valueFloatArrayOrigin = {1.1f, 2.1f, 3.1f}; + std::vector valueStringArrayOrigin = {"aa", "bb", "cc"}; + wantOrigin.SetParam(keyFloatArray, valueFloatArrayOrigin); + wantOrigin.SetParam(keyStringArray, valueStringArrayOrigin); + + std::string uri = wantOrigin.ToUri(); + Want *wantNew = Want::ParseUri(uri); + bool result = (wantNew != nullptr); + + if (wantNew != nullptr) { + std::vector arrayFloatNew = wantNew->GetFloatArrayParam(keyFloatArray); + std::vector arrayFloatOld = wantOrigin.GetFloatArrayParam(keyFloatArray); + result = result && (arrayFloatNew == arrayFloatOld); + + std::vector arrayStringNew = wantNew->GetStringArrayParam(keyStringArray); + std::vector arrayStringOld = wantOrigin.GetStringArrayParam(keyStringArray); + result = result && (arrayStringNew == arrayStringOld); + delete wantNew; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse parameter of float array +void SecondAbility::WantParseUriCase11(int code) +{ + Want wantOrigin; + std::string keyFloatArray = "keyFloatArray"; + std::vector valueFloatArrayOrigin = {1.1f, 2.1f, 3.1f}; + wantOrigin.SetParam(keyFloatArray, valueFloatArrayOrigin); + + std::string uri = wantOrigin.ToUri(); + Want *wantNew = Want::ParseUri(uri); + bool result = (wantNew != nullptr); + + if (wantNew != nullptr) { + std::vector arrayNew = wantNew->GetFloatArrayParam(keyFloatArray); + std::vector arrayOld = wantOrigin.GetFloatArrayParam(keyFloatArray); + result = result && (arrayNew == arrayOld); + delete wantNew; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse parameter of float and string +void SecondAbility::WantParseUriCase12(int code) +{ + Want wantOrigin; + std::string keyFloat = "keyFloat"; + std::string keyString = "keyString"; + float valueFloatOrigin = 123.4f; + std::string valueStringOrigin = "abcd"; + wantOrigin.SetParam(keyFloat, valueFloatOrigin); + wantOrigin.SetParam(keyString, valueStringOrigin); + std::string uri = wantOrigin.ToUri(); + Want *wantNew = Want::ParseUri(uri); + bool result = (wantNew != nullptr); + + if (wantNew) { + float floatNew = wantNew->GetFloatParam(keyFloat, 0); + float floatOld = wantOrigin.GetFloatParam(keyFloat, 1); + result = result && (floatNew == floatOld); + + std::string stringNew = wantNew->GetStringParam(keyString); + std::string stringOld = wantOrigin.GetStringParam(keyString); + result = result && (stringNew == stringOld); + delete wantNew; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse action, entity, flags, element +void SecondAbility::WantParseUriCase13(int code) +{ + std::string action = Want::ACTION_PLAY; + std::string entity = Want::ENTITY_VIDEO; + unsigned int flag = 0x0f0f0f0f; + std::string device = "device1"; + std::string bundle = "bundle1"; + std::string ability = "ability1"; + OHOS::AppExecFwk::ElementName element(device, bundle, ability); + + Want wantOrigin; + wantOrigin.SetAction(action); + wantOrigin.AddEntity(entity); + wantOrigin.AddFlags(flag); + wantOrigin.SetElement(element); + std::string uri = wantOrigin.ToUri(); + Want *wantNew = Want::ParseUri(uri); + bool result = (wantNew != nullptr); + + if (wantNew) { + result = result && (wantNew->GetAction() == action); + for (auto entityItem : wantNew->GetEntities()) { + result = result && (entityItem == entity); + } + result = result && (wantNew->GetElement().GetDeviceID() == device); + result = result && (wantNew->GetElement().GetBundleName() == bundle); + result = result && (wantNew->GetElement().GetAbilityName() == ability); + result = result && (wantNew->GetFlags() == flag); + delete wantNew; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse uri that make empty Want +void SecondAbility::WantParseUriCase14(int code) +{ + // "=" + std::string uri = WANT_HEADER + "=;end"; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want) { + delete want; + } + + // "key=" + uri = WANT_HEADER + "abc=;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + // "=value" + uri = WANT_HEADER + "=abc;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + // "param=value" + uri = WANT_HEADER + "xxxx=yyy;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + // empty string + uri = WANT_HEADER + ";;;;;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse uri that has only key and euqals sign, no value +void SecondAbility::WantParseUriCase15(int code) +{ + std::string uri = WANT_HEADER + "action=;end"; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "entity=;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "device=;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "bundle=;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "ability=;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "flag=;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + + uri = WANT_HEADER + "param=;end"; + want = Want::ParseUri(uri); + result = result && (want != nullptr); + if (want) { + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Boolean parameters +void SecondAbility::WantParseUriCase16(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyBoolean"; + std::string value = "true"; + std::string uriKey = AAFwk::Boolean::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + value + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetBoolParam(key, false) == true); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Char parameters +void SecondAbility::WantParseUriCase17(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyChar"; + AAFwk::zchar zcharValue = 'A'; + std::string uriKey = AAFwk::Char::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + "A" + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetCharParam(key, 'B') == zcharValue); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Byte parameters +void SecondAbility::WantParseUriCase18(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyByte"; + AAFwk::byte byteValue = 8; + const AAFwk::byte defaultValue = 7; + std::string uriKey = AAFwk::Byte::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + std::to_string(byteValue) + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetByteParam(key, defaultValue) == byteValue); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Short parameters +void SecondAbility::WantParseUriCase19(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyShort"; + short shortValue = 1; + const short defaultValue = 2; + std::string uriKey = AAFwk::Short::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + std::to_string(shortValue) + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetShortParam(key, defaultValue) == shortValue); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Integer parameters +void SecondAbility::WantParseUriCase20(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyInteger"; + int integerValue = 10; + const short defaultValue = 20; + std::string uriKey = AAFwk::Integer::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + std::to_string(integerValue) + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetIntParam(key, defaultValue) == integerValue); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Float parameters +void SecondAbility::WantParseUriCase21(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyFloat"; + float floatValue = 1000.9f; + const float defaultValue = 20.0; + const float diffValue = 0.000001; + std::string uriKey = AAFwk::Float::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + std::to_string(floatValue) + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetFloatParam(key, defaultValue) - floatValue <= diffValue); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Double parameters +void SecondAbility::WantParseUriCase22(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyDouble"; + double doubleValue = 10000.99; + const float defaultValue = 20.0; + const float diffValue = 0.000001; + std::string uriKey = AAFwk::Double::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + std::to_string(doubleValue) + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + result = result && (want->GetDoubleParam(key, defaultValue) - doubleValue <= diffValue); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parse Array parameters +void SecondAbility::WantParseUriCase23(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string key = "keyArray"; + std::string value = AAFwk::String::SIGNATURE + std::string("3{aa,bb,cc}"); + std::string uriKey = AAFwk::Array::SIGNATURE + std::string(".") + key + std::string("="); + std::string uri = head + uriKey + value + end; + Want *want = Want::ParseUri(uri); + bool result = (want != nullptr); + if (want != nullptr) { + auto parsedValue = want->GetStringArrayParam(key); + result = result && (parsedValue == (std::vector {"aa", "bb", "cc"})); + delete want; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty action +void SecondAbility::WantSetActionCase1(int code) +{ + std::string empty; + Want want; + bool result = want.GetAction() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get empty action +void SecondAbility::WantSetActionCase2(int code) +{ + std::string empty; + Want want; + want.SetAction(empty); + bool result = want.GetAction() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get long action +void SecondAbility::WantSetActionCase3(int code) +{ + std::string value(LARGE_STR_LEN, 'a'); + Want want; + want.SetAction(value); + bool result = want.GetAction() == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get action with special character +void SecondAbility::WantSetActionCase4(int code) +{ + std::string value = "~!@#$%^&*()_+`-={}|[]\\:\";\'<>?,./"; + Want want; + want.SetAction(value); + bool result = want.GetAction() == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get action continuously +void SecondAbility::WantSetActionCase5(int code) +{ + std::string value = "value"; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + std::string tmpValue = value + std::to_string(i); + want.SetAction(tmpValue); + result = result && want.GetAction() == tmpValue; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty bundle +void SecondAbility::WantSetBundleCase1(int code) +{ + std::string empty; + Want want; + bool result = want.GetBundle() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get empty bundle +void SecondAbility::WantSetBundleCase2(int code) +{ + std::string empty; + Want want; + want.SetBundle(empty); + bool result = want.GetBundle() == empty; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get long bundle +void SecondAbility::WantSetBundleCase3(int code) +{ + std::string value(LARGE_STR_LEN, 'a'); + Want want; + want.SetBundle(value); + bool result = want.GetBundle() == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get bundle with special character +void SecondAbility::WantSetBundleCase4(int code) +{ + std::string value = "~!@#$%^&*()_+`-={}|[]\\:\";\'<>?,./"; + Want want; + want.SetBundle(value); + bool result = want.GetBundle() == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get bundle continuously +void SecondAbility::WantSetBundleCase5(int code) +{ + std::string value = "value"; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + std::string tmpValue = value + std::to_string(i); + want.SetBundle(tmpValue); + result = result && want.GetBundle() == tmpValue; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get empty element +void SecondAbility::WantSetElementCase1(int code) +{ + ElementName element; + Want want; + bool result = want.GetElement() == element; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get empty element +void SecondAbility::WantSetElementCase2(int code) +{ + ElementName element; + Want want; + want.SetElement(element); + bool result = want.GetElement() == element; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get element continuously +void SecondAbility::WantSetElementCase3(int code) +{ + ElementName element("deviceId", "bundleName", "abilityName"); + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + element.SetDeviceID("deviceId" + std::to_string(i)); + want.SetElement(element); + result = result && want.GetElement() == element; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// SetElementName(string, string) and GetElement +// get empty ElementName +void SecondAbility::WantSetElementNameStringStringCase1(int code) +{ + std::string empty; + Want want; + bool result = want.GetElement().GetBundleName() == empty; + result = result && (want.GetElement().GetAbilityName() == empty); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get empty ElementName +void SecondAbility::WantSetElementNameStringStringCase2(int code) +{ + std::string empty; + Want want; + want.SetElementName(empty, empty); + bool result = want.GetElement().GetBundleName() == empty; + result = result && (want.GetElement().GetAbilityName() == empty); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get long ElementName +void SecondAbility::WantSetElementNameStringStringCase3(int code) +{ + std::string bundleName(LARGE_STR_LEN, 'a'); + std::string abilityName(LARGE_STR_LEN, 'b'); + Want want; + want.SetElementName(bundleName, abilityName); + bool result = want.GetElement().GetBundleName() == bundleName; + result = result && (want.GetElement().GetAbilityName() == abilityName); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get ElementName including special character +void SecondAbility::WantSetElementNameStringStringCase4(int code) +{ + std::string value = "~!@#$%^&*()_+`-={}|[]\\:\";\'<>?,./"; + Want want; + want.SetElementName(value, value); + bool result = want.GetElement().GetBundleName() == value; + result = result && (want.GetElement().GetAbilityName() == value); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get ElementName continuously +void SecondAbility::WantSetElementNameStringStringCase5(int code) +{ + std::string bundleName; + std::string abilityName; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + bundleName = "bundleName" + std::to_string(i); + abilityName = "abilityName" + std::to_string(i); + want.SetElementName(bundleName, abilityName); + result = result && want.GetElement().GetBundleName() == bundleName; + result = result && (want.GetElement().GetAbilityName() == abilityName); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// SetElementName(string, string, string) and GetElement +// get empty ElementName +void SecondAbility::WantSetElementNameStringStringStringCase1(int code) +{ + std::string empty; + Want want; + bool result = want.GetElement().GetBundleName() == empty; + result = result && (want.GetElement().GetAbilityName() == empty); + result = result && (want.GetElement().GetDeviceID() == empty); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get empty ElementName +void SecondAbility::WantSetElementNameStringStringStringCase2(int code) +{ + std::string empty; + Want want; + want.SetElementName(empty, empty, empty); + bool result = want.GetElement().GetBundleName() == empty; + result = result && (want.GetElement().GetAbilityName() == empty); + result = result && (want.GetElement().GetDeviceID() == empty); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get long ElementName +void SecondAbility::WantSetElementNameStringStringStringCase3(int code) +{ + std::string deviceId(LARGE_STR_LEN, 'a'); + std::string bundleName(LARGE_STR_LEN, 'b'); + std::string abilityName(LARGE_STR_LEN, 'c'); + Want want; + want.SetElementName(deviceId, bundleName, abilityName); + bool result = want.GetElement().GetBundleName() == bundleName; + result = result && (want.GetElement().GetAbilityName() == abilityName); + result = result && (want.GetElement().GetDeviceID() == deviceId); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get ElementName including special character +void SecondAbility::WantSetElementNameStringStringStringCase4(int code) +{ + std::string value = "~!@#$%^&*()_+`-={}|[]\\:\";\'<>?,./"; + Want want; + want.SetElementName(value, value, value); + bool result = want.GetElement().GetBundleName() == value; + result = result && (want.GetElement().GetAbilityName() == value); + result = result && (want.GetElement().GetDeviceID() == value); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get ElementName continuously +void SecondAbility::WantSetElementNameStringStringStringCase5(int code) +{ + std::string bundleName; + std::string abilityName; + std::string deviceId; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + bundleName = "bundleName" + std::to_string(i); + abilityName = "abilityName" + std::to_string(i); + deviceId = "deviceId" + std::to_string(i); + want.SetElementName(deviceId, bundleName, abilityName); + result = result && want.GetElement().GetBundleName() == bundleName; + result = result && (want.GetElement().GetAbilityName() == abilityName); + result = result && (want.GetElement().GetDeviceID() == deviceId); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// GetFlags, SetFlags, AddFlags, RemoveFlags +// get empty flags +void SecondAbility::WantSetFlagsCase1(int code) +{ + Want want; + bool result = want.GetFlags() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set max unsigned flags +void SecondAbility::WantSetFlagsCase2(int code) +{ + Want want; + want.SetFlags(std::numeric_limits::max()); + bool result = want.GetFlags() == std::numeric_limits::max(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// remove max unsigned flags +void SecondAbility::WantSetFlagsCase3(int code) +{ + Want want; + want.RemoveFlags(std::numeric_limits::max()); + bool result = want.GetFlags() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and remove max unsigned flags +void SecondAbility::WantSetFlagsCase4(int code) +{ + Want want; + want.SetFlags(std::numeric_limits::max()); + bool result = want.GetFlags() == std::numeric_limits::max(); + want.RemoveFlags(std::numeric_limits::max()); + result = result && (want.GetFlags() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add max unsigned flags +void SecondAbility::WantSetFlagsCase5(int code) +{ + Want want; + want.AddFlags(std::numeric_limits::max()); + bool result = want.GetFlags() == std::numeric_limits::max(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add and remove max unsigned flags +void SecondAbility::WantSetFlagsCase6(int code) +{ + Want want; + want.AddFlags(std::numeric_limits::max()); + bool result = want.GetFlags() == std::numeric_limits::max(); + want.RemoveFlags(std::numeric_limits::max()); + result = result && (want.GetFlags() == 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and add flags +void SecondAbility::WantSetFlagsCase7(int code) +{ + Want want; + want.SetFlags(setValue); + want.AddFlags(addValue); + bool result = want.GetFlags() == (setValue | addValue); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add and set flags +void SecondAbility::WantSetFlagsCase8(int code) +{ + Want want; + want.AddFlags(addValue); + want.SetFlags(setValue); + bool result = want.GetFlags() == setValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add one flags and remove another flags +void SecondAbility::WantSetFlagsCase9(int code) +{ + Want want; + want.AddFlags(addValue); + want.RemoveFlags(removeValue); + bool result = want.GetFlags() == addValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// add and remove flags continuously +void SecondAbility::WantSetFlagsCase10(int code) +{ + Want want; + bool result = true; + unsigned flags = want.GetFlags(); + for (unsigned i = 0; i < pressureTimes; i++) { + want.AddFlags(i); + flags |= i; + result = result && (want.GetFlags() == flags); + } + unsigned expectValue = want.GetFlags(); + for (unsigned i = 0; i < pressureTimes; i++) { + want.RemoveFlags(i); + expectValue &= ~i; + result = result && (want.GetFlags() == expectValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set flags continuously +void SecondAbility::WantSetFlagsCase11(int code) +{ + Want want; + bool result = true; + for (unsigned i = 0; i < pressureTimes; i++) { + want.SetFlags(i); + result = result && (want.GetFlags() == i); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set empty type +void SecondAbility::WantSetTypeCase1(int code) +{ + std::string type; + Want want; + want.SetType(type); + bool result = (want.GetType() == type); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set twice and get once +void SecondAbility::WantSetTypeCase2(int code) +{ + std::string type1("type1"); + std::string type2("type2"); + Want want; + want.SetType(type1); + want.SetType(type2); + bool result = (want.GetType() == type2); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set type with special character +void SecondAbility::WantSetTypeCase3(int code) +{ + std::string type = "~!@#$%^&*()_+`-={}|[]\\:\";'<>?,./ \t"; + Want want; + want.SetType(type); + bool result = (want.GetType() == type); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set type repeatedly +void SecondAbility::WantSetTypeCase4(int code) +{ + std::string type("type"); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetType(type + std::to_string(i)); + } + bool result = (want.GetType() == (type + std::to_string(pressureTimes - 1))); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set empty uri +void SecondAbility::WantSetUriCase1(int code) +{ + std::string uriString; + Want want; + want.SetUri(uriString); + bool result = (want.GetUri().ToString() == uriString); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set uri with property action +void SecondAbility::WantSetUriCase2(int code) +{ + std::string uriString = WANT_HEADER + "action=action;end"; + Uri uri(uriString); + Want want; + want.SetUri(uriString); + bool result = want.GetUri().Equals(uri); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set uri with string parameter +void SecondAbility::WantSetUriCase3(int code) +{ + std::string strUri = "https://john.doe@www.example.com:123/forum/questions/?tag=networking#top"; + std::string paramString = "a;b:c;d=e;"; + Want want; + want.SetUri(strUri); + Want newWant; + newWant.SetUri(want.GetUri()); + bool result = (newWant.GetUri().ToString() == strUri); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set uri continuously +void SecondAbility::WantSetUriCase4(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = ";end"; + std::string propAction = "action=action"; + std::string uriString; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + uriString = head + propAction + std::to_string(i) + end; + want.SetUri(uriString); + result = result && (want.GetUri().ToString() == uriString); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set empty uri and type +void SecondAbility::WantSetUriAndTypeCase1(int code) +{ + Uri empty(""); + std::string type; + Want want; + want.SetUriAndType(empty, type); + bool result = (want.GetUri().ToString() == ""); + result = result && (want.GetType() == type); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set bad format uri and type +void SecondAbility::WantSetUriAndTypeCase2(int code) + +{ + std::string empty; + Uri uri("!@!#:adf;"); + std::string type(LARGE_STR_LEN, 'a'); + Want want; + want.SetUriAndType(uri, type); + bool result = (want.GetUri().Equals(uri)); + result = result && (want.GetType() == type); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set uri with ElementName and type +void SecondAbility::WantSetUriAndTypeCase3(int code) +{ + std::string empty; + Uri uri(WANT_HEADER + "device=device;end"); + std::string type = "type"; + Want want; + want.SetUriAndType(uri, type); + bool result = (want.GetUri().Equals(uri)); + result = result && (want.GetType() == type); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set uri and type repeatedly +void SecondAbility::WantSetUriAndTypeCase4(int code) +{ + std::string type = "type"; + std::string uriString = "https://john.doe@www.example.com:123/forum/questions/?tag=networking#top"; + std::string typeValue; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + typeValue = type + std::to_string(i); + Uri uri(uriString); + want.SetUriAndType(uri, typeValue); + result = result && (want.GetUri().Equals(uri)); + result = result && (want.GetType() == typeValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty Want to uri +void SecondAbility::WantToUriCase1(int code) +{ + std::string head = WANT_HEADER + ""; + std::string end = "end"; + std::string uriString = head + end; + Want want; + bool result = (want.ToUri() == uriString); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with action to uri +void SecondAbility::WantToUriCase2(int code) +{ + std::string value = WANT_HEADER + "action=\"\\b\\\";end"; + Want want; + want.SetAction(value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetAction() == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with entities to uri +void SecondAbility::WantToUriCase3(int code) +{ + std::string value = WANT_HEADER + "entity=\"\\b\\\";end"; + Want want; + want.AddEntity(value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->HasEntity(value)); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with flags to uri +void SecondAbility::WantToUriCase4(int code) +{ + unsigned value = std::numeric_limits::max(); + Want want; + want.SetFlags(value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetFlags() == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with ElementName to uri +void SecondAbility::WantToUriCase5(int code) +{ + std::string device = WANT_HEADER + "device=\"\\b\\\";end"; + std::string bundle = WANT_HEADER + "bundle=\"\\b\\\";end"; + std::string ability = WANT_HEADER + "ability=\"\\b\\\";end"; + ElementName value(device, bundle, ability); + Want want; + want.SetElement(value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetElement() == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with string parameter to uri +void SecondAbility::WantToUriCase6(int code) +{ + std::string key = std::to_string(String::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + std::string value = WANT_HEADER + "value=\"\\b\\\";end"; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetStringParam(key) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with bool parameter to uri +void SecondAbility::WantToUriCase7(int code) +{ + std::string key = std::to_string(Boolean::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + bool value = true; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetBoolParam(key, false) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with char parameter to uri +void SecondAbility::WantToUriCase8(int code) +{ + std::string key = std::to_string(Char::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + zchar value = '.'; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetCharParam(key, '=') == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with byte parameter to uri +void SecondAbility::WantToUriCase9(int code) +{ + std::string key = std::to_string(Byte::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + byte value = 9; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetByteParam(key, 0) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with short parameter to uri +void SecondAbility::WantToUriCase10(int code) +{ + std::string key = std::to_string(Short::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + short value = 99; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetShortParam(key, 0) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with int parameter to uri +void SecondAbility::WantToUriCase11(int code) +{ + std::string key = std::to_string(Integer::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + int value = 999; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetIntParam(key, 0) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with long parameter to uri +void SecondAbility::WantToUriCase12(int code) +{ + std::string key = std::to_string(Long::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + long value = 9999L; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetLongParam(key, 0l) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with float parameter to uri +void SecondAbility::WantToUriCase13(int code) +{ + std::string key = std::to_string(Float::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + float value = 9999.9f; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetFloatParam(key, 0) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with double parameter to uri +void SecondAbility::WantToUriCase14(int code) +{ + std::string key = std::to_string(Double::SIGNATURE) + ".#Intent;key=\"\\b\\\";end"; + double value = 9999.9; + Want want; + want.SetParam(key, value); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetDoubleParam(key, 0) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with string array parameter to uri +void SecondAbility::WantToUriCase15(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::string value = std::to_string(String::SIGNATURE) + "3{#Intent;value=\"\\b\\\";end"; + std::vector arrayValue = {value, value, value}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetStringArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with bool array parameter to uri +void SecondAbility::WantToUriCase16(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {true, true, false}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetBoolArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with char array parameter to uri +void SecondAbility::WantToUriCase17(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {'.', '=', ';'}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetCharArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with byte array parameter to uri +void SecondAbility::WantToUriCase18(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {1, 2, 3}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetByteArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with short array parameter to uri +void SecondAbility::WantToUriCase19(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {1, 2, 3}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetShortArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with int array parameter to uri +void SecondAbility::WantToUriCase20(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {1, 2, 3}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetIntArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with long array parameter to uri +void SecondAbility::WantToUriCase21(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {1l, 2l, 3l}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetLongArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with float array parameter to uri +void SecondAbility::WantToUriCase22(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {1, 2, 3}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetFloatArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with double array parameter to uri +void SecondAbility::WantToUriCase23(int code) +{ + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; + std::vector arrayValue = {1.1, 2.2, 3.3}; + Want want; + want.SetParam(key, arrayValue); + Want *newWant = nullptr; + newWant = Want::ParseUri(want.ToUri()); + bool result = false; + if (newWant != nullptr) { + result = (newWant->GetDoubleArrayParam(key) == arrayValue); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty Want to and from uri +void SecondAbility::WantWantParseUriCase1(int code) +{ + Want want; + std::string uriString = want.WantToUri(want); + Want *newWant = Want::WantParseUri(uriString.c_str()); + bool result = (newWant != nullptr); + std::string empty; + if (newWant) { + result = result && (newWant->GetAction() == empty); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with property to and from uri +void SecondAbility::WantWantParseUriCase2(int code) +{ + Want want; + std::string action = "action"; + want.SetAction(action); + std::string uriString = want.WantToUri(want); + Want *newWant = Want::WantParseUri(uriString.c_str()); + bool result = (newWant != nullptr); + if (newWant) { + result = result && (newWant->GetAction() == action); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// Want with parameter to and from uri +void SecondAbility::WantWantParseUriCase3(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + want.SetParam(key, value); + std::string uriString = want.WantToUri(want); + Want *newWant = Want::WantParseUri(uriString.c_str()); + bool result = (newWant != nullptr); + if (newWant) { + result = result && (newWant->GetStringParam(key) == value); + delete newWant; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get params from empty Want +void SecondAbility::WantGetParamsCase1(int code) +{ + Want want; + auto params = want.GetParams(); + bool result = params.IsEmpty(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get params +void SecondAbility::WantGetParamsCase2(int code) +{ + std::string key = "key"; + std::string value = "value"; + WantParams params; + params.SetParam(key, String::Box(value)); + Want want; + want.SetParams(params); + bool result = want.GetParams().HasParam(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get params repeatedly +void SecondAbility::WantGetParamsCase3(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + WantParams params; + std::string tmpKey = key + std::to_string(i); + params.SetParam(tmpKey, String::Box(value)); + want.SetParams(params); + result = result && (want.GetParams().HasParam(tmpKey)); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get byte on empty Want +void SecondAbility::WantGetByteParamCase1(int code) +{ + std::string key = "key"; + byte defaultValue = 7; + Want want; + bool result = want.GetByteParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed byte param +void SecondAbility::WantGetByteParamCase2(int code) +{ + std::string key = "key"; + byte value = 10; + byte defaultValue = 7; + Want want; + want.SetParam(key, value); + bool result = want.GetByteParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get byte param repeatedly +void SecondAbility::WantGetByteParamCase3(int code) +{ + std::string key = "key"; + byte value; + byte defaultValue = 7; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = i % setValue; + want.SetParam(key, value); + result = result && want.GetByteParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get byte array on empty Want +void SecondAbility::WantGetByteArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetByteArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed byte array param +void SecondAbility::WantGetByteArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {1, 12, 127}; + Want want; + want.SetParam(key, value); + bool result = want.GetByteArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get byte array param repeatedly +void SecondAbility::WantGetByteArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {1, 12, 127}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = i % setValue; + want.SetParam(key, value); + result = result && want.GetByteArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get bool on empty Want +void SecondAbility::WantGetBoolParamCase1(int code) +{ + std::string key = "key"; + bool defaultValue = true; + Want want; + bool result = want.GetBoolParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed bool param +void SecondAbility::WantGetBoolParamCase2(int code) +{ + std::string key = "key"; + bool value = true; + bool defaultValue = false; + Want want; + want.SetParam(key, value); + bool result = want.GetBoolParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get bool param repeatedly +void SecondAbility::WantGetBoolParamCase3(int code) +{ + std::string key = "key"; + bool value = false; + bool defaultValue = false; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = i % even == 0; + want.SetParam(key, value); + result = result && want.GetBoolParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get bool array on empty Want +void SecondAbility::WantGetBoolArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetBoolArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed bool array param +void SecondAbility::WantGetBoolArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {true, true, false}; + Want want; + want.SetParam(key, value); + bool result = want.GetBoolArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get bool array param repeatedly +void SecondAbility::WantGetBoolArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {true, true, false}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = !value.at(0); + want.SetParam(key, value); + result = result && want.GetBoolArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get char on empty Want +void SecondAbility::WantGetCharParamCase1(int code) +{ + std::string key = "key"; + zchar defaultValue = 'a'; + Want want; + bool result = want.GetCharParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed char param +void SecondAbility::WantGetCharParamCase2(int code) +{ + std::string key = "key"; + zchar value = 'a'; + zchar defaultValue = 'b'; + Want want; + want.SetParam(key, value); + bool result = want.GetCharParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get char param repeatedly +void SecondAbility::WantGetCharParamCase3(int code) +{ + std::string key = "key"; + zchar value; + zchar defaultValue = 'a'; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = (zchar)i; + want.SetParam(key, value); + result = result && want.GetCharParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get char array on empty Want +void SecondAbility::WantGetCharArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetCharArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed char array param +void SecondAbility::WantGetCharArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {'z', 'a', 'b'}; + Want want; + want.SetParam(key, value); + bool result = want.GetCharArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get char array param repeatedly +void SecondAbility::WantGetCharArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {'z', 'a', 'b'}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = (zchar)i; + want.SetParam(key, value); + result = result && want.GetCharArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get int on empty Want +void SecondAbility::WantGetIntParamCase1(int code) +{ + std::string key = "key"; + int defaultValue = 7; + Want want; + bool result = want.GetIntParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed int param +void SecondAbility::WantGetIntParamCase2(int code) +{ + std::string key = "key"; + int value = 10; + int defaultValue = 7; + Want want; + want.SetParam(key, value); + bool result = want.GetIntParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get int param repeatedly +void SecondAbility::WantGetIntParamCase3(int code) +{ + std::string key = "key"; + int value; + int defaultValue = 7; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = i; + want.SetParam(key, value); + result = result && want.GetIntParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get int array on empty Want +void SecondAbility::WantGetIntArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetIntArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed int array param +void SecondAbility::WantGetIntArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {1, 12, 127}; + Want want; + want.SetParam(key, value); + bool result = want.GetIntArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get int array param repeatedly +void SecondAbility::WantGetIntArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {1, 12, 127}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = i; + want.SetParam(key, value); + result = result && want.GetIntArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get double on empty Want +void SecondAbility::WantGetDoubleParamCase1(int code) +{ + std::string key = "key"; + double defaultValue = 7.99; + Want want; + bool result = want.GetDoubleParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed double param +void SecondAbility::WantGetDoubleParamCase2(int code) +{ + std::string key = "key"; + double value = 10.99; + double defaultValue = 7.99; + Want want; + want.SetParam(key, value); + bool result = want.GetDoubleParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get double param repeatedly +void SecondAbility::WantGetDoubleParamCase3(int code) +{ + std::string key = "key"; + double value; + double defaultValue = 7.99; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = i; + want.SetParam(key, value); + result = result && want.GetDoubleParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get double array on empty Want +void SecondAbility::WantGetDoubleArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetDoubleArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed double array param +void SecondAbility::WantGetDoubleArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {1.99, 12.99, 127.99}; + Want want; + want.SetParam(key, value); + bool result = want.GetDoubleArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get double array param repeatedly +void SecondAbility::WantGetDoubleArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {1.99, 12.99, 127.99}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = i; + want.SetParam(key, value); + result = result && want.GetDoubleArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get float on empty Want +void SecondAbility::WantGetFloatParamCase1(int code) +{ + std::string key = "key"; + float defaultValue = 7.99f; + Want want; + bool result = want.GetFloatParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed float param +void SecondAbility::WantGetFloatParamCase2(int code) +{ + std::string key = "key"; + float value = 10.99f; + float defaultValue = 7.99f; + Want want; + want.SetParam(key, value); + bool result = want.GetFloatParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get float param repeatedly +void SecondAbility::WantGetFloatParamCase3(int code) +{ + std::string key = "key"; + float value; + float defaultValue = 7.99f; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = i; + want.SetParam(key, value); + result = result && want.GetFloatParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get float array on empty Want +void SecondAbility::WantGetFloatArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetFloatArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed float array param +void SecondAbility::WantGetFloatArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {1.99f, 12.99f, 127.99f}; + Want want; + want.SetParam(key, value); + bool result = want.GetFloatArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get float array param repeatedly +void SecondAbility::WantGetFloatArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {1.99f, 12.99f, 127.99f}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = i; + want.SetParam(key, value); + result = result && want.GetFloatArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get long on empty Want +void SecondAbility::WantGetLongParamCase1(int code) +{ + std::string key = "key"; + long defaultValue = 7l; + Want want; + bool result = want.GetLongParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed long param +void SecondAbility::WantGetLongParamCase2(int code) +{ + std::string key = "key"; + long value = 10L; + long defaultValue = 7L; + Want want; + want.SetParam(key, value); + bool result = want.GetLongParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get long param repeatedly +void SecondAbility::WantGetLongParamCase3(int code) +{ + std::string key = "key"; + long value; + long defaultValue = 7L; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = i; + want.SetParam(key, value); + result = result && want.GetLongParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get long array on empty Want +void SecondAbility::WantGetLongArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetLongArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed long array param +void SecondAbility::WantGetLongArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {1L, 12L, 127L}; + Want want; + want.SetParam(key, value); + bool result = want.GetLongArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get long array param repeatedly +void SecondAbility::WantGetLongArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {1L, 12L, 127L}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = i; + want.SetParam(key, value); + result = result && want.GetLongArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get short on empty Want +void SecondAbility::WantGetShortParamCase1(int code) +{ + std::string key = "key"; + short defaultValue = 7; + Want want; + bool result = want.GetShortParam(key, defaultValue) == defaultValue; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed short param +void SecondAbility::WantGetShortParamCase2(int code) +{ + std::string key = "key"; + short value = 10; + short defaultValue = 7; + Want want; + want.SetParam(key, value); + bool result = want.GetShortParam(key, defaultValue) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get short param repeatedly +void SecondAbility::WantGetShortParamCase3(int code) +{ + std::string key = "key"; + short value; + short defaultValue = 7; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value = i; + want.SetParam(key, value); + result = result && want.GetShortParam(key, defaultValue) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get short array on empty Want +void SecondAbility::WantGetShortArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetShortArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed short array param +void SecondAbility::WantGetShortArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {1, 12, 127}; + Want want; + want.SetParam(key, value); + bool result = want.GetShortArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get short array param repeatedly +void SecondAbility::WantGetShortArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {1, 12, 127}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = i; + want.SetParam(key, value); + result = result && want.GetShortArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get string on empty Want +void SecondAbility::WantGetStringParamCase1(int code) +{ + std::string key = "key"; + std::string value; + Want want; + bool result = want.GetStringParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed string param +void SecondAbility::WantGetStringParamCase2(int code) +{ + std::string key = "key"; + std::string value = "zxc"; + Want want; + want.SetParam(key, value); + bool result = want.GetStringParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get string param repeatedly +void SecondAbility::WantGetStringParamCase3(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + bool result = true; + std::string tmpValue; + for (int i = 0; i < pressureTimes; i++) { + tmpValue = value + std::to_string(i); + want.SetParam(key, tmpValue); + result = result && want.GetStringParam(key) == tmpValue; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get string array on empty Want +void SecondAbility::WantGetStringArrayParamCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = want.GetStringArrayParam(key).size() == 0; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get existed string array param +void SecondAbility::WantGetStringArrayParamCase2(int code) +{ + std::string key = "key"; + std::vector value = {"1", "12", "127"}; + Want want; + want.SetParam(key, value); + bool result = want.GetStringArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get string array param repeatedly +void SecondAbility::WantGetStringArrayParamCase3(int code) +{ + std::string key = "key"; + std::vector value = {"1", "12", "127"}; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + value[0] = std::to_string(i); + want.SetParam(key, value); + result = result && want.GetStringArrayParam(key) == value; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// max byte +void SecondAbility::WantSetParamByteCase1(int code) +{ + std::string key = "key"; + byte value = 127; + Want want; + want.SetParam(key, value); + bool result = want.GetByteParam(key, 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// min byte +void SecondAbility::WantSetParamByteCase2(int code) +{ + std::string key = "key"; + byte value = -128; + Want want; + want.SetParam(key, value); + bool result = want.GetByteParam(key, 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different byte value set on one key +void SecondAbility::WantSetParamByteCase3(int code) +{ + std::string key = "key"; + byte value = 5; + Want want; + for (byte i = 0; i <= value; i++) { + want.SetParam(key, i); + } + bool result = want.GetByteParam(key, 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different byte value set on different key +void SecondAbility::WantSetParamByteCase4(int code) +{ + std::string key = "key"; + byte value = 5; + Want want; + for (byte i = 0; i <= value; i++) { + want.SetParam(key + std::to_string(i), i); + } + bool result = true; + for (byte i = 0; i <= value; i++) { + result = result && (want.GetByteParam(key + std::to_string(i), -1) == i); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure of byte +void SecondAbility::WantSetParamByteCase5(int code) +{ + std::string key = "key"; + byte value = 5; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetByteParam(key + std::to_string(pressureTimes - 1), 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty byte array +void SecondAbility::WantSetParamByteArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetByteArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big byte array +void SecondAbility::WantSetParamByteArrayCase2(int code) +{ + std::string key = "key"; + byte value = 5; + std::vector vec(ARRAY_SIZE, value); + Want want; + want.SetParam(key, vec); + bool result = want.GetByteArrayParam(key) == vec; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different byte array set on one key +void SecondAbility::WantSetParamByteArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, size); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i); + want.SetParam(key, tmpValue); + } + bool result = want.GetByteArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different byte array set on different key +void SecondAbility::WantSetParamByteArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, size); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i); + result = result && (want.GetByteArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure of byte array +void SecondAbility::WantSetParamByteArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, size); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetByteArrayParam(key + std::to_string(pressureTimes - 1)) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// bool value false +void SecondAbility::WantSetParamBoolCase1(int code) +{ + std::string key = "key"; + bool value = false; + Want want; + want.SetParam(key, value); + bool result = want.GetBoolParam(key, true) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// bool value true +void SecondAbility::WantSetParamBoolCase2(int code) +{ + std::string key = "key"; + bool value = true; + Want want; + want.SetParam(key, value); + bool result = want.GetBoolParam(key, false) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different bool value set on one key +void SecondAbility::WantSetParamBoolCase3(int code) +{ + std::string key = "key"; + int size = 5; + bool value = true; + Want want; + for (int i = 0; i < size; i++) { + value = !value; + want.SetParam(key, value); + } + bool result = want.GetBoolParam(key, !value) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different bool value set on different key +void SecondAbility::WantSetParamBoolCase4(int code) +{ + std::string key = "key"; + int size = 5; + bool value = true; + Want want; + for (int i = 0; i < size; i++) { + value = !value; + want.SetParam(key + std::to_string(i), value); + } + bool result = true; + value = true; + for (int i = 0; i < size; i++) { + value = !value; + result = result && (want.GetBoolParam(key + std::to_string(i), !value) == value); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure of bool +void SecondAbility::WantSetParamBoolCase5(int code) +{ + std::string key = "key"; + bool value = true; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = (want.GetBoolParam(key + std::to_string(pressureTimes - 1), !value) == value); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty bool array +void SecondAbility::WantSetParamBoolArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = (want.GetBoolArrayParam(key) == value); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big bool array +void SecondAbility::WantSetParamBoolArrayCase2(int code) +{ + std::string key = "key"; + std::vector value(ARRAY_SIZE, true); + Want want; + want.SetParam(key, value); + bool result = want.GetBoolArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different bool array set on one key +void SecondAbility::WantSetParamBoolArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, true); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, true); + want.SetParam(key, tmpValue); + } + bool result = want.GetBoolArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different bool array set on different key +void SecondAbility::WantSetParamBoolArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, true); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, true); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, true); + result = result && (want.GetBoolArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure of bool array +void SecondAbility::WantSetParamBoolArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, true); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = (want.GetBoolArrayParam(key + std::to_string(pressureTimes - 1)) == value); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty char +void SecondAbility::WantSetParamCharCase1(int code) +{ + std::string key = "key"; + zchar value = ' '; + Want want; + want.SetParam(key, value); + bool result = want.GetCharParam(key, 'z') == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// char default value +void SecondAbility::WantSetParamCharCase2(int code) +{ + std::string key = "key"; + zchar value = '0'; + zchar defaultValue = U'文'; + Want want; + bool result = (want.GetCharParam(key, defaultValue) == defaultValue); + want.SetParam(key, value); + result = result && (want.GetCharParam(key, defaultValue) == value); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different char value set on one key +void SecondAbility::WantSetParamCharCase3(int code) +{ + std::string key = "key"; + std::vector value = {'a', 'b', ',', '&', U'中'}; + Want want; + for (size_t i = 0; i < value.size(); i++) { + want.SetParam(key, value.at(i)); + } + bool result = want.GetCharParam(key, '0') == value.back(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different char value set on different key +void SecondAbility::WantSetParamCharCase4(int code) +{ + std::string key = "key"; + std::vector value = {'a', 'b', ',', '&', U'中'}; + Want want; + for (size_t i = 0; i < value.size(); i++) { + want.SetParam(key + std::to_string(i), value.at(i)); + } + bool result = true; + for (size_t i = 0; i < value.size(); i++) { + result = result && (want.GetCharParam(key + std::to_string(i), '0') == value.at(i)); + APP_LOGI("WantSetParamCharCase4 (%{public}c)", (char)want.GetCharParam(key + std::to_string(i), '0')); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure char +void SecondAbility::WantSetParamCharCase5(int code) +{ + std::string key = "key"; + zchar value = '5'; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetCharParam(key + std::to_string(pressureTimes - 1), 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty char array +void SecondAbility::WantSetParamCharArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetCharArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big char array +void SecondAbility::WantSetParamCharArrayCase2(int code) +{ + std::string key = "key"; + std::vector value(ARRAY_SIZE, '5'); + Want want; + want.SetParam(key, value); + bool result = want.GetCharArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different char array set on one key +void SecondAbility::WantSetParamCharArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, zchar(size)); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, zchar(i)); + want.SetParam(key, tmpValue); + } + bool result = want.GetCharArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different char array set on different key +void SecondAbility::WantSetParamCharArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, zchar(i)); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, zchar(i)); + result = result && (want.GetCharArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure char array +void SecondAbility::WantSetParamCharArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, 'z'); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = (want.GetCharArrayParam(key + std::to_string(pressureTimes - 1)) == value); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// max int +void SecondAbility::WantSetParamIntCase1(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::max()); + bool result = want.GetIntParam(key, 0) == std::numeric_limits::max(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// min int +void SecondAbility::WantSetParamIntCase2(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::min()); + bool result = want.GetIntParam(key, 0) == std::numeric_limits::min(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different int value set on one key +void SecondAbility::WantSetParamIntCase3(int code) +{ + std::string key = "key"; + int value = 5; + Want want; + for (int i = 0; i <= value; i++) { + want.SetParam(key, i); + } + bool result = want.GetIntParam(key, 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different int value set on different key +void SecondAbility::WantSetParamIntCase4(int code) +{ + std::string key = "key"; + int value = 5; + Want want; + for (int i = 0; i <= value; i++) { + want.SetParam(key + std::to_string(i), i); + } + bool result = true; + for (int i = 0; i <= value; i++) { + result = result && (want.GetIntParam(key + std::to_string(i), -1) == i); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure int +void SecondAbility::WantSetParamIntCase5(int code) +{ + std::string key = "key"; + int value = 5; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetIntParam(key + std::to_string(pressureTimes - 1), 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty int array +void SecondAbility::WantSetParamIntArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetIntArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big int array +void SecondAbility::WantSetParamIntArrayCase2(int code) +{ + std::string key = "key"; + std::vector value(ARRAY_SIZE, SMALL_INT); + Want want; + want.SetParam(key, value); + bool result = want.GetIntArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different int array set on one key +void SecondAbility::WantSetParamIntArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, size); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i); + want.SetParam(key, tmpValue); + } + bool result = want.GetIntArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different int array set on different key +void SecondAbility::WantSetParamIntArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i); + result = result && (want.GetIntArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure byte array +void SecondAbility::WantSetParamIntArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, size); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetIntArrayParam(key + std::to_string(pressureTimes - 1)) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// max double +void SecondAbility::WantSetParamDoubleCase1(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::max()); + bool result = want.GetDoubleParam(key, 0) == std::numeric_limits::max(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// min double +void SecondAbility::WantSetParamDoubleCase2(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::min()); + bool result = want.GetDoubleParam(key, 0) == std::numeric_limits::min(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different double value set on one key +void SecondAbility::WantSetParamDoubleCase3(int code) +{ + std::string key = "key"; + double value = 99.9; + int size = 5; + Want want; + for (int i = 0; i < size; i++) { + want.SetParam(key, i * value); + } + bool result = want.GetDoubleParam(key, 0) == value * (size - 1); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different double value set on different key +void SecondAbility::WantSetParamDoubleCase4(int code) +{ + std::string key = "key"; + double value = 99.9; + int size = 5; + Want want; + for (int i = 0; i < size; i++) { + want.SetParam(key + std::to_string(i), i * value); + } + bool result = true; + for (int i = 0; i < size; i++) { + result = result && (want.GetDoubleParam(key + std::to_string(i), -1) == i * value); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure double +void SecondAbility::WantSetParamDoubleCase5(int code) +{ + std::string key = "key"; + double value = 99.9; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetDoubleParam(key + std::to_string(pressureTimes - 1), 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty double array +void SecondAbility::WantSetParamDoubleArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetDoubleArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big double array +void SecondAbility::WantSetParamDoubleArrayCase2(int code) +{ + std::string key = "key"; + double value = 99.9; + std::vector vec(ARRAY_SIZE, value); + Want want; + want.SetParam(key, vec); + bool result = want.GetDoubleArrayParam(key) == vec; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different double array set on one key +void SecondAbility::WantSetParamDoubleArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + double dValue = 99.9; + std::vector value(size, size * dValue); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * dValue); + want.SetParam(key, tmpValue); + } + bool result = want.GetDoubleArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different double array set on different key +void SecondAbility::WantSetParamDoubleArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + double value = 99.9; + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + result = result && (want.GetDoubleArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure double array +void SecondAbility::WantSetParamDoubleArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + double value = 99.9; + std::vector vec(size, value); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), vec); + } + bool result = want.GetDoubleArrayParam(key + std::to_string(pressureTimes - 1)) == vec; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// max float +void SecondAbility::WantSetParamFloatCase1(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::max()); + bool result = want.GetFloatParam(key, 0) == std::numeric_limits::max(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// min float +void SecondAbility::WantSetParamFloatCase2(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::min()); + bool result = want.GetFloatParam(key, 0) == std::numeric_limits::min(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different float value set on one key +void SecondAbility::WantSetParamFloatCase3(int code) +{ + std::string key = "key"; + float value = 99.9f; + int size = 5; + Want want; + for (int i = 0; i < size; i++) { + want.SetParam(key, i * value); + } + bool result = want.GetFloatParam(key, 0) == value * (size - 1); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different float value set on different key +void SecondAbility::WantSetParamFloatCase4(int code) +{ + std::string key = "key"; + float value = 99.9f; + int size = 5; + Want want; + for (int i = 0; i < size; i++) { + want.SetParam(key + std::to_string(i), i * value); + } + bool result = true; + for (int i = 0; i < size; i++) { + result = result && (want.GetFloatParam(key + std::to_string(i), -1) == i * value); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure float +void SecondAbility::WantSetParamFloatCase5(int code) +{ + std::string key = "key"; + float value = 99.9f; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetFloatParam(key + std::to_string(pressureTimes - 1), 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty float array +void SecondAbility::WantSetParamFloatArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetFloatArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big float array +void SecondAbility::WantSetParamFloatArrayCase2(int code) +{ + std::string key = "key"; + std::vector value(ARRAY_SIZE, 99.9f); + Want want; + want.SetParam(key, value); + bool result = want.GetFloatArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different float array set on one key +void SecondAbility::WantSetParamFloatArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + float fValue = 99.9f; + std::vector value(size, fValue * size); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * fValue); + want.SetParam(key, tmpValue); + } + bool result = want.GetFloatArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different float array set on different key +void SecondAbility::WantSetParamFloatArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + float value = 99.9f; + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + result = result && (want.GetFloatArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure float array +void SecondAbility::WantSetParamFloatArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + std::vector value(size, 99.9f); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetFloatArrayParam(key + std::to_string(pressureTimes - 1)) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// max long +void SecondAbility::WantSetParamLongCase1(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::max()); + bool result = want.GetLongParam(key, 0) == std::numeric_limits::max(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// min long +void SecondAbility::WantSetParamLongCase2(int code) +{ + std::string key = "key"; + Want want; + want.SetParam(key, std::numeric_limits::min()); + bool result = want.GetLongParam(key, 0) == std::numeric_limits::min(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different long value set on one key +void SecondAbility::WantSetParamLongCase3(int code) +{ + std::string key = "key"; + long value = 999; + int size = 5; + Want want; + for (int i = 0; i < size; i++) { + want.SetParam(key, i * value); + } + bool result = want.GetLongParam(key, 0) == value * (size - 1); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different long value set on different key +void SecondAbility::WantSetParamLongCase4(int code) +{ + std::string key = "key"; + long value = 999; + int size = 5; + Want want; + for (int i = 0; i < size; i++) { + want.SetParam(key + std::to_string(i), i * value); + } + bool result = true; + for (int i = 0; i < size; i++) { + result = result && (want.GetLongParam(key + std::to_string(i), -1) == i * value); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure long +void SecondAbility::WantSetParamLongCase5(int code) +{ + std::string key = "key"; + long value = 999; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetLongParam(key + std::to_string(pressureTimes - 1), 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty long array +void SecondAbility::WantSetParamLongArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetLongArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big long array +void SecondAbility::WantSetParamLongArrayCase2(int code) +{ + std::string key = "key"; + long value = 999; + std::vector vec(ARRAY_SIZE, value); + Want want; + want.SetParam(key, vec); + bool result = want.GetLongArrayParam(key) == vec; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different long array set on one key +void SecondAbility::WantSetParamLongArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + long lValue = 999; + std::vector value(size, lValue * size); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * lValue); + want.SetParam(key, tmpValue); + } + bool result = want.GetLongArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different long array set on different key +void SecondAbility::WantSetParamLongArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + long value = 999; + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + result = result && (want.GetLongArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure long array +void SecondAbility::WantSetParamLongArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + long value = 999; + std::vector vec(size, value); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), vec); + } + bool result = want.GetLongArrayParam(key + std::to_string(pressureTimes - 1)) == vec; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// max short +void SecondAbility::WantSetParamShortCase1(int code) +{ + std::string key = "key"; + short value = std::numeric_limits::max(); + Want want; + want.SetParam(key, value); + bool result = want.GetShortParam(key, 0) == std::numeric_limits::max(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// min short +void SecondAbility::WantSetParamShortCase2(int code) +{ + std::string key = "key"; + short value = std::numeric_limits::min(); + Want want; + want.SetParam(key, value); + bool result = want.GetShortParam(key, 0) == std::numeric_limits::min(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different short value set on one key +void SecondAbility::WantSetParamShortCase3(int code) +{ + std::string key = "key"; + short value = 999; + int size = 5; + Want want; + for (short i = 0; i < size; i++) { + want.SetParam(key, static_cast(i * value)); + } + bool result = want.GetShortParam(key, 0) == value * (size - 1); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different short value set on different key +void SecondAbility::WantSetParamShortCase4(int code) +{ + std::string key = "key"; + short value = 999; + int size = 5; + Want want; + for (short i = 0; i < size; i++) { + want.SetParam(key + std::to_string(i), static_cast(i * value)); + } + bool result = true; + for (short i = 0; i < size; i++) { + result = result && (want.GetShortParam(key + std::to_string(i), -1) == i * value); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure short +void SecondAbility::WantSetParamShortCase5(int code) +{ + std::string key = "key"; + short value = 999; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetShortParam(key + std::to_string(pressureTimes - 1), 0) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty short array +void SecondAbility::WantSetParamShortArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetShortArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big short array +void SecondAbility::WantSetParamShortArrayCase2(int code) +{ + std::string key = "key"; + short value = 999; + std::vector vec(ARRAY_SIZE, value); + Want want; + want.SetParam(key, vec); + bool result = want.GetShortArrayParam(key) == vec; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different short array set on one key +void SecondAbility::WantSetParamShortArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + short sValue = 999; + std::vector value(size, sValue * size); + Want want; + for (short i = 1; i <= size; i++) { + std::vector tmpValue(i, i * sValue); + want.SetParam(key, tmpValue); + } + bool result = want.GetShortArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different short array set on different key +void SecondAbility::WantSetParamShortArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + short value = 999; + Want want; + for (short i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (short i = 1; i <= size; i++) { + std::vector tmpValue(i, i * value); + result = result && (want.GetShortArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure short array +void SecondAbility::WantSetParamShortArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + short value = 999; + std::vector vec(size, value); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), vec); + } + bool result = want.GetShortArrayParam(key + std::to_string(pressureTimes - 1)) == vec; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty string +void SecondAbility::WantSetParamStringCase1(int code) +{ + std::string key = "key"; + std::string value; + Want want; + want.SetParam(key, value); + bool result = want.GetStringParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// long string +void SecondAbility::WantSetParamStringCase2(int code) +{ + std::string key = "key"; + std::string value(LARGE_STR_LEN, 'a'); + Want want; + want.SetParam(key, value); + bool result = want.GetStringParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different string value set on one key +void SecondAbility::WantSetParamStringCase3(int code) +{ + std::string key = "key"; + int size = 5; + std::string value(size, 'a'); + Want want; + for (int i = 1; i <= size; i++) { + std::string tmpValue(i, 'a'); + want.SetParam(key, tmpValue); + } + bool result = want.GetStringParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different string value set on different key +void SecondAbility::WantSetParamStringCase4(int code) +{ + std::string key = "key"; + int size = 5; + Want want; + for (int i = 1; i <= size; i++) { + std::string tmpValue(i, 'a'); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::string tmpValue(i, 'a'); + result = result && (want.GetStringParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure string +void SecondAbility::WantSetParamStringCase5(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetStringParam(key + std::to_string(pressureTimes - 1)) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty string array +void SecondAbility::WantSetParamStringArrayCase1(int code) +{ + std::string key = "key"; + std::vector value; + Want want; + want.SetParam(key, value); + bool result = want.GetStringArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// big string array +void SecondAbility::WantSetParamStringArrayCase2(int code) +{ + std::string key = "key"; + std::string strValue = "value"; + std::vector value(ARRAY_SIZE, strValue); + Want want; + want.SetParam(key, value); + bool result = want.GetStringArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different string array set on one key +void SecondAbility::WantSetParamStringArrayCase3(int code) +{ + std::string key = "key"; + int size = 5; + std::string strValue = "value"; + std::vector value(size, strValue); + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, strValue); + want.SetParam(key, tmpValue); + } + bool result = want.GetStringArrayParam(key) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// different string array set on different key +void SecondAbility::WantSetParamStringArrayCase4(int code) +{ + std::string key = "key"; + int size = 5; + std::string value = "value"; + Want want; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, value); + want.SetParam(key + std::to_string(i), tmpValue); + } + bool result = true; + for (int i = 1; i <= size; i++) { + std::vector tmpValue(i, value); + result = result && (want.GetStringArrayParam(key + std::to_string(i)) == tmpValue); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// pressure string array +void SecondAbility::WantSetParamStringArrayCase5(int code) +{ + std::string key = "key"; + int size = 5; + std::string strValue = "value"; + std::vector value(size, strValue); + Want want; + for (int i = 0; i < pressureTimes; i++) { + want.SetParam(key + std::to_string(i), value); + } + bool result = want.GetStringArrayParam(key + std::to_string(pressureTimes - 1)) == value; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// empty Want +void SecondAbility::WantHasParameterCase1(int code) +{ + std::string key = "key"; + Want want; + bool result = !want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// no parameter +void SecondAbility::WantHasParameterCase2(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + want.SetParam("key1", value); + bool result = !want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// parameter exits +void SecondAbility::WantHasParameterCase3(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + want.SetParam(key, value); + bool result = want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// after remove parameter +void SecondAbility::WantHasParameterCase4(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + want.SetParam(key, value); + bool result = want.HasParameter(key); + want.RemoveParam(key); + result = result && !want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// whether exists parameter repeatedly +void SecondAbility::WantHasParameterCase5(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + std::string tmpKey = key + std::to_string(i); + want.SetParam(tmpKey, value); + result = result && want.HasParameter(tmpKey); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params on empty Want by empty WantParams +void SecondAbility::WantReplaceParamsWantParamsCase1(int code) +{ + Want want; + WantParams wParams; + want.ReplaceParams(wParams); + bool result = want.GetParams().IsEmpty(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set param and then replace it by empty WantParams +void SecondAbility::WantReplaceParamsWantParamsCase2(int code) +{ + std::string key = "key"; + std::string value = "value"; + WantParams wParams; + wParams.SetParam(key, AAFwk::String::Box(value)); + Want want; + want.SetParams(wParams); + bool result = want.HasParameter(key); + WantParams emptyParams; + want.ReplaceParams(emptyParams); + result = result && !want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params on empty Want by not empty WantParams +void SecondAbility::WantReplaceParamsWantParamsCase3(int code) +{ + std::string key = "key"; + std::string value = "value"; + WantParams wParams; + wParams.SetParam(key, AAFwk::String::Box(value)); + Want want; + want.ReplaceParams(wParams); + bool result = want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params twice by different WantParams +void SecondAbility::WantReplaceParamsWantParamsCase4(int code) +{ + WantParams wParamsOne; + wParamsOne.SetParam("key1", AAFwk::String::Box("value1")); + WantParams wParamsTwo; + wParamsTwo.SetParam("key2", AAFwk::String::Box("value2")); + Want want; + want.ReplaceParams(wParamsOne); + want.ReplaceParams(wParamsTwo); + bool result = !want.HasParameter("key1"); + result = result && want.HasParameter("key2"); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params repeatedly +void SecondAbility::WantReplaceParamsWantParamsCase5(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + WantParams wParams; + std::string tmpKey = key + std::to_string(i); + wParams.SetParam(tmpKey, AAFwk::String::Box(value)); + want.ReplaceParams(wParams); + result = result && want.HasParameter(tmpKey); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params on empty Want by another empty Want +void SecondAbility::WantReplaceParamsWantCase1(int code) +{ + Want wantOne; + Want wantTwo; + wantOne.ReplaceParams(wantTwo); + bool result = wantOne.GetParams().IsEmpty(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params on empty Want by another not empty Want +void SecondAbility::WantReplaceParamsWantCase2(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want wantOne; + Want wantTwo; + wantTwo.SetParam(key, value); + wantOne.ReplaceParams(wantTwo); + bool result = wantOne.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params by another empty Want +void SecondAbility::WantReplaceParamsWantCase3(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want wantOne; + Want wantTwo; + wantOne.SetParam(key, value); + wantOne.ReplaceParams(wantTwo); + bool result = !wantOne.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params by another Want +void SecondAbility::WantReplaceParamsWantCase4(int code) +{ + std::string value = "value"; + Want wantOne; + Want wantTwo; + wantOne.SetParam("key1", value); + wantTwo.SetParam("key2", value); + wantOne.ReplaceParams(wantTwo); + bool result = !wantOne.HasParameter("key1"); + result = result && wantOne.HasParameter("key2"); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// replace params repeatedly +void SecondAbility::WantReplaceParamsWantCase5(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want wantOne; + Want wantTwo; + bool result = true; + std::string tmpKey; + for (int i = 0; i < pressureTimes; i++) { + tmpKey = key + std::to_string(i); + wantTwo.SetParam(tmpKey, value); + wantOne.ReplaceParams(wantTwo); + result = result && wantOne.HasParameter(tmpKey); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// remove param from empty Want +void SecondAbility::WantRemoveParamCase1(int code) +{ + std::string key = "key"; + Want want; + want.RemoveParam(key); + bool result = !want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// remove existed param +void SecondAbility::WantRemoveParamCase2(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + want.SetParam(key, value); + bool result = want.HasParameter(key); + want.RemoveParam(key); + result = result && !want.HasParameter(key); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and remove param repeatedly +void SecondAbility::WantRemoveParamCase3(int code) +{ + std::string key = "key"; + std::string value = "value"; + Want want; + std::string tmpKey; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + tmpKey = key + std::to_string(i); + want.SetParam(tmpKey, value); + result = result && want.HasParameter(tmpKey); + want.RemoveParam(tmpKey); + result = result && !want.HasParameter(tmpKey); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get operation from empty Want +void SecondAbility::WantGetOperationCase1(int code) +{ + Want want; + Operation emptyOperation; + bool result = want.GetOperation() == emptyOperation; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// set and get operation +void SecondAbility::WantGetOperationCase2(int code) +{ + Want want; + OperationBuilder opBuilder; + auto operation = opBuilder.WithAbilityName("abilityName").WithBundleName("bundleName").build(); + want.SetOperation(*operation); + bool result = want.GetOperation() == *operation; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// get operation repeatedly +void SecondAbility::WantGetOperationCase3(int code) +{ + Want want; + OperationBuilder opBuilder; + std::shared_ptr operation; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + operation = opBuilder.WithAbilityName("abilityName" + std::to_string(i)).build(); + want.SetOperation(*operation); + result = result && want.GetOperation() == *operation; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// compare empty Want operation +void SecondAbility::WantOperationEqualsCase1(int code) +{ + Want wantOne; + Want wantTwo; + bool result = wantOne.OperationEquals(wantTwo); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// compare Want operation not equal +void SecondAbility::WantOperationEqualsCase2(int code) +{ + OperationBuilder opBuilder; + std::vector vec = {"entities1", "entities2"}; + auto operation = opBuilder.WithAbilityName("abilityName") + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); + Want wantOne; + wantOne.SetOperation(*operation); + OperationBuilder opBuilderTwo; + auto operationTwo = opBuilderTwo.WithAbilityName("abilityName2") + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); + Want wantTwo; + wantTwo.SetOperation(*operationTwo); + bool result = !wantOne.OperationEquals(wantTwo); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// compare Want operation equal +void SecondAbility::WantOperationEqualsCase3(int code) +{ + OperationBuilder opBuilder; + auto operation = opBuilder.WithAbilityName("abilityName") + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); + Want wantOne; + wantOne.SetOperation(*operation); + OperationBuilder opBuilderTwo; + auto operationTwo = opBuilderTwo.WithAbilityName("abilityName") + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); + Want wantTwo; + wantTwo.SetOperation(*operationTwo); + bool result = wantOne.OperationEquals(wantTwo); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// compare Want operation repeatedly +void SecondAbility::WantOperationEqualsCase4(int code) +{ + OperationBuilder opBuilder; + auto operation = opBuilder.WithAbilityName("abilityName" + std::to_string(pressureTimes - 1)) + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); + Want wantOne; + wantOne.SetOperation(*operation); + Want wantTwo; + std::shared_ptr operationTwo; + OperationBuilder opBuilderTwo; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + operationTwo = opBuilderTwo.WithAbilityName("abilityName" + std::to_string(i)) + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); + wantTwo.SetOperation(*operationTwo); + if (i == pressureTimes - 1) { + result = result && wantOne.OperationEquals(wantTwo); + } else { + result = result && !wantOne.OperationEquals(wantTwo); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// clone operation on empty Want +void SecondAbility::WantCloneOperationCase1(int code) +{ + Want want; + Want *wantClone = want.CloneOperation(); + bool result = false; + if (wantClone) { + result = wantClone->OperationEquals(want); + delete wantClone; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// clone not empty operation +void SecondAbility::WantCloneOperationCase2(int code) +{ + OperationBuilder opBuilder; + auto operation = opBuilder.WithAbilityName("abilityName") + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); + Want want; + want.SetOperation(*operation); + Want *wantClone = want.CloneOperation(); + bool result = false; + if (wantClone != nullptr) { + result = wantClone->OperationEquals(want); + delete wantClone; + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +// clone operation repeatedly +void SecondAbility::WantCloneOperationCase3(int code) +{ + OperationBuilder opBuilder; + Want want; + std::shared_ptr operation; + bool result = true; + for (int i = 0; i < pressureTimes; i++) { + operation = opBuilder.WithAbilityName("abilityName" + std::to_string(i)) + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); + want.SetOperation(*operation); + Want *wantClone = want.CloneOperation(); + result = result && wantClone->OperationEquals(want); + if (wantClone) { + delete wantClone; + } + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e47f52510313182dac419e7c7eb224ab34391b03 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp @@ -0,0 +1,781 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "sixth_ability.h" +#include +#include +#include +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +namespace { +const int cycleCount = 1000; +const int paramCnt = 3; +const int caseIndx = 2; +} // namespace + +#define APPREGISTERABILITYLIFECYCALLBACK(onAbilityFunctionName, getAbilityCountFunction, expected, code) \ + auto callback = std::make_shared(); \ + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); \ + std::shared_ptr ability = std::make_shared(); \ + Ability::GetApplication()->onAbilityFunctionName(ability); \ + bool result = (callback->GetCallbackCount().getAbilityCountFunction() == expected); \ + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); \ + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback) + +#define APPUNREGISTERABILITYLIFECYCALLBACK(onAbilityFunctionName, getAbilityCountFunction, expected, code) \ + auto callback = std::make_shared(); \ + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); \ + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback); \ + std::shared_ptr ability = std::make_shared(); \ + Ability::GetApplication()->onAbilityFunctionName(ability); \ + bool result = (callback->GetCallbackCount().getAbilityCountFunction() == expected); \ + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)) + +void SixthAbility::SubscribeEvent(const vector_conststr &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + subscriber->sixthAbility_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void SixthAbility::ApplicationStByCode(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SixthAbility::ApplicationStByCode"); + if (mapStKitFunc_.find(apiIndex) != mapStKitFunc_.end() && + static_cast(mapStKitFunc_[apiIndex].size()) > caseIndex) { + mapStKitFunc_[apiIndex][caseIndex](code); + } else { + APP_LOGI("ApplicationStByCode error"); + } +} + +// KitTest Start +// RegisterAbilityLifecycleCallbacks ST case +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase1(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase1"); + APPREGISTERABILITYLIFECYCALLBACK(OnAbilityStart, GetOnAbilityStartCount, 1, code); +} + +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase2(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase2"); + APPREGISTERABILITYLIFECYCALLBACK(OnAbilityInactive, GetOnAbilityInactiveCount, 1, code); +} + +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase3(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase3"); + APPREGISTERABILITYLIFECYCALLBACK(OnAbilityBackground, GetOnAbilityBackgroundCount, 1, code); +} + +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase4(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase4"); + APPREGISTERABILITYLIFECYCALLBACK(OnAbilityForeground, GetOnAbilityForegroundCount, 1, code); +} + +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase5(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase5"); + APPREGISTERABILITYLIFECYCALLBACK(OnAbilityActive, GetOnAbilityActiveCount, 1, code); +} + +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase6(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase5"); + APPREGISTERABILITYLIFECYCALLBACK(OnAbilityStop, GetOnAbilityStopCount, 1, code); +} + +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase7(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase7"); + auto callback = std::make_shared(); + for (int i = 0; i < cycleCount; i++) { + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + } + std::shared_ptr ability = std::make_shared(); + Ability::GetApplication()->OnAbilityStart(ability); + bool result = (callback->GetCallbackCount().GetOnAbilityStartCount() == cycleCount); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback); +} + +void SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase8(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterAbilityLifecycleCallbacksCase8"); + auto callback1 = std::make_shared(); + auto callback2 = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback1); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback2); + std::shared_ptr ability = std::make_shared(); + Ability::GetApplication()->OnAbilityStart(ability); + bool result = ((callback1->GetCallbackCount().GetOnAbilityStartCount() == 1) && + (callback2->GetCallbackCount().GetOnAbilityStartCount() == 1)); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback1); + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback2); +} + +// UnregisterAbilityLifecycleCallbacks +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase1(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase1"); + APPUNREGISTERABILITYLIFECYCALLBACK(OnAbilityStart, GetOnAbilityStartCount, 0, code); +} + +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase2(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase2"); + APPUNREGISTERABILITYLIFECYCALLBACK(OnAbilityInactive, GetOnAbilityInactiveCount, 0, code); +} + +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase3(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase3"); + APPUNREGISTERABILITYLIFECYCALLBACK(OnAbilityBackground, GetOnAbilityBackgroundCount, 0, code); +} + +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase4(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase4"); + APPUNREGISTERABILITYLIFECYCALLBACK(OnAbilityForeground, GetOnAbilityForegroundCount, 0, code); +} + +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase5(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase5"); + APPUNREGISTERABILITYLIFECYCALLBACK(OnAbilityActive, GetOnAbilityActiveCount, 0, code); +} + +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase6(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase6"); + APPUNREGISTERABILITYLIFECYCALLBACK(OnAbilityStop, GetOnAbilityStopCount, 0, code); +} + +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase7(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase7"); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + for (int i = 0; i < cycleCount; i++) { + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback); + } + std::shared_ptr ability = std::make_shared(); + Ability::GetApplication()->OnAbilityStart(ability); + bool result = (callback->GetCallbackCount().GetOnAbilityStartCount() == 0); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); +} + +void SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase8(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterAbilityLifecycleCallbacksCase8"); + auto callback1 = std::make_shared(); + auto callback2 = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback1); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback2); + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback1); + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback2); + std::shared_ptr ability = std::make_shared(); + Ability::GetApplication()->OnAbilityStart(ability); + bool result = ((callback1->GetCallbackCount().GetOnAbilityStartCount() == 0) && + (callback2->GetCallbackCount().GetOnAbilityStartCount() == 0)); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); +} + +// DispatchAbilitySavedState ST case +void SixthAbility::SkillDispatchAbilitySavedStateCase1(int code) +{ + APP_LOGI("SixthAbility::SkillDispatchAbilitySavedStateCase1"); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + PacMap outState; + Ability::GetApplication()->OnAbilitySaveState(outState); + bool result = (callback->GetCallbackCount().GetOnAbilitySaveStateCount() == 1); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback); +} + +void SixthAbility::SkillDispatchAbilitySavedStateCase2(int code) +{ + APP_LOGI("SixthAbility::SkillDispatchAbilitySavedStateCase2"); + auto callback = std::make_shared(); + for (int i = 0; i < cycleCount; i++) { + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + } + PacMap outState; + Ability::GetApplication()->OnAbilitySaveState(outState); + bool result = (callback->GetCallbackCount().GetOnAbilitySaveStateCount() == cycleCount); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterAbilityLifecycleCallbacks(callback); +} + +// RegisterElementsCallbacks +void SixthAbility::SkillRegisterElementsCallbacksCase1(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterElementsCallbacksCase1"); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterElementsCallbacks(callback); + Configuration configuration; + Ability::GetApplication()->OnConfigurationUpdated(configuration); + bool result = (callback->GetCallbackCount().GetOnConfigurationCount() == 1); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterElementsCallbacks(callback); +} + +void SixthAbility::SkillRegisterElementsCallbacksCase2(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterElementsCallbacksCase2"); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterElementsCallbacks(callback); + Ability::GetApplication()->OnMemoryLevel(1); + bool result = (callback->GetCallbackCount().GetOnMemoryLevelCount() == 1); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterElementsCallbacks(callback); +} + +void SixthAbility::SkillRegisterElementsCallbacksCase3(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterElementsCallbacksCase3"); + auto callback = std::make_shared(); + for (int i = 0; i < cycleCount; i++) { + Ability::GetApplication()->RegisterElementsCallbacks(callback); + } + Configuration configuration; + Ability::GetApplication()->OnConfigurationUpdated(configuration); + bool result = (callback->GetCallbackCount().GetOnConfigurationCount() == cycleCount); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterElementsCallbacks(callback); +} + +void SixthAbility::SkillRegisterElementsCallbacksCase4(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterElementsCallbacksCase4"); + auto callback1 = std::make_shared(); + auto callback2 = std::make_shared(); + Ability::GetApplication()->RegisterElementsCallbacks(callback1); + Ability::GetApplication()->RegisterElementsCallbacks(callback2); + Ability::GetApplication()->OnMemoryLevel(1); + bool result = ((callback1->GetCallbackCount().GetOnMemoryLevelCount() == 1) && + (callback2->GetCallbackCount().GetOnMemoryLevelCount() == 1)); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); + Ability::GetApplication()->UnregisterElementsCallbacks(callback1); + Ability::GetApplication()->UnregisterElementsCallbacks(callback2); +} + +// UnregisterElementsCallbacks +void SixthAbility::SkillUnregisterElementsCallbacksCase1(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterElementsCallbacksCase1"); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterElementsCallbacks(callback); + Ability::GetApplication()->UnregisterElementsCallbacks(callback); + Configuration configuration; + Ability::GetApplication()->OnConfigurationUpdated(configuration); + bool result = (callback->GetCallbackCount().GetOnConfigurationCount() == 0); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); +} + +void SixthAbility::SkillUnregisterElementsCallbacksCase2(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterElementsCallbacksCase2"); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterElementsCallbacks(callback); + Ability::GetApplication()->UnregisterElementsCallbacks(callback); + Ability::GetApplication()->OnMemoryLevel(1); + bool result = (callback->GetCallbackCount().GetOnMemoryLevelCount() == 0); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); +} + +void SixthAbility::SkillUnregisterElementsCallbacksCase3(int code) +{ + APP_LOGI("SixthAbility::SkillRegisterElementsCallbacksCase3"); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterElementsCallbacks(callback); + for (int i = 0; i < cycleCount; i++) { + Ability::GetApplication()->UnregisterElementsCallbacks(callback); + } + Configuration configuration; + Ability::GetApplication()->OnConfigurationUpdated(configuration); + bool result = (callback->GetCallbackCount().GetOnConfigurationCount() == 0); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); +} + +void SixthAbility::SkillUnregisterElementsCallbacksCase4(int code) +{ + APP_LOGI("SixthAbility::SkillUnregisterElementsCallbacksCase4"); + auto callback1 = std::make_shared(); + auto callback2 = std::make_shared(); + Ability::GetApplication()->RegisterElementsCallbacks(callback1); + Ability::GetApplication()->RegisterElementsCallbacks(callback2); + Ability::GetApplication()->UnregisterElementsCallbacks(callback1); + Ability::GetApplication()->UnregisterElementsCallbacks(callback2); + Ability::GetApplication()->OnMemoryLevel(1); + bool result = ((callback1->GetCallbackCount().GetOnMemoryLevelCount() == 0) && + (callback2->GetCallbackCount().GetOnMemoryLevelCount() == 0)); + TestUtils::PublishEvent(g_respPageSixthAbilityST, code, std::to_string(result)); +} + +// KitTest End +void SixthAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SixthAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); + auto callback = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); +} + +void SixthAbility::OnStart(const Want &want) +{ + APP_LOGI("SixthAbility::onStart"); + GetWantInfo(want); + Ability::OnStart(want); + SubscribeEvent(g_requPageSixthAbilitySTVector); + std::string eventData = GetAbilityName() + g_abilityStateOnStart; + TestUtils::PublishEvent(g_respPageSixthAbilityST, 0, eventData); +} + +void SixthAbility::OnStop() +{ + APP_LOGI("SixthAbility::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + std::string eventData = GetAbilityName() + g_abilityStateOnStop; + TestUtils::PublishEvent(g_respPageSixthAbilityST, 0, eventData); +} + +void SixthAbility::OnActive() +{ + APP_LOGI("SixthAbility::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAabilityName = this->Split(targetAbility_, ","); + if (!startBundleName.empty() && !startAabilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAabilityName); + want.SetParam("shouldReturn", shouldReturn_); + if (!targetBundle_.empty() && !targetAbility_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn_.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + g_abilityStateOnActive; + TestUtils::PublishEvent(g_respPageSixthAbilityST, 0, eventData); +} + +void SixthAbility::OnInactive() +{ + APP_LOGI("SixthAbility::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + g_abilityStateOnInactive; + TestUtils::PublishEvent(g_respPageSixthAbilityST, 0, eventData); +} + +void SixthAbility::OnBackground() +{ + APP_LOGI("SixthAbility::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + g_abilityStateOnBackground; + TestUtils::PublishEvent(g_respPageSixthAbilityST, 0, eventData); +} + +void SixthAbility::OnForeground(const Want &want) +{ + APP_LOGI("SixthAbility::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + g_abilityStateOnForeground; + TestUtils::PublishEvent(g_respPageSixthAbilityST, 0, eventData); +} + +void SixthAbility::OnNewWant(const Want &want) +{ + APP_LOGI("SixthAbility::OnNewWant"); + GetWantInfo(want); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + g_abilityStateOnNewWant; + TestUtils::PublishEvent(g_respPageSixthAbilityST, 0, eventData); +} + +void SixthAbility::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void SixthAbility::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string SixthAbility::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void KitTestSixEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (g_requPageSixthAbilityST == eventName) { + auto target = data.GetData(); + vector_str splitResult = TestUtils::split(target, "_"); + auto keyMap = splitResult.at(0); + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && splitResult.size() >= paramCnt) { + auto apiIndex = atoi(splitResult.at(1).c_str()); + auto caseIndex = atoi(splitResult.at(caseIndx).c_str()); + mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); + } else { + if (keyMap == "TerminateAbility") { + KitTerminateAbility(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } + } +} + +void KitTestSixEventSubscriber::ApplicationStByCode(int apiIndex, int caseIndex, int code) +{ + if (sixthAbility_ != nullptr) { + sixthAbility_->ApplicationStByCode(apiIndex, caseIndex, code); + } +} + +void KitTestSixEventSubscriber::KitTerminateAbility() +{ + if (sixthAbility_ != nullptr) { + sixthAbility_->TerminateAbility(); + } +} + +// Record the number of callback function exec +int CallbackCount::GetOnAbilityStartCount() +{ + return onAbilityStartCount; +} + +int CallbackCount::GetOnAbilityInactiveCount() +{ + return onAbilityInactiveCount; +} + +int CallbackCount::GetOnAbilityBackgroundCount() +{ + return onAbilityBackgroundCount; +} + +int CallbackCount::GetOnAbilityForegroundCount() +{ + return onAbilityForegroundCount; +} + +int CallbackCount::GetOnAbilityActiveCount() +{ + return onAbilityActiveCount; +} + +int CallbackCount::GetOnAbilityStopCount() +{ + return onAbilityStopCount; +} + +int CallbackCount::GetOnAbilitySaveStateCount() +{ + return onAbilitySaveStateCount; +} + +int CallbackCount::GetOnConfigurationCount() +{ + return onConfigurationCount; +} + +int CallbackCount::GetOnMemoryLevelCount() +{ + return onMemoryLevelCount; +} + +void CallbackCount::SetOnAbilityStartCount() +{ + onAbilityStartCount++; +} + +void CallbackCount::SetOnAbilityInactiveCount() +{ + onAbilityInactiveCount++; +} + +void CallbackCount::SetOnAbilityBackgroundCount() +{ + onAbilityBackgroundCount++; +} + +void CallbackCount::SetOnAbilityForegroundCount() +{ + onAbilityForegroundCount++; +} + +void CallbackCount::SetOnAbilityActiveCount() +{ + onAbilityActiveCount++; +} + +void CallbackCount::SetOnAbilityStopCount() +{ + onAbilityStopCount++; +} + +void CallbackCount::SetOnAbilitySaveStateCount() +{ + onAbilitySaveStateCount++; +} + +void CallbackCount::SetOnConfigurationCount() +{ + onConfigurationCount++; +} + +void CallbackCount::SetOnMemoryLevelCount() +{ + onMemoryLevelCount++; +} + +// The Lifecycle callback function class (First) +void KitTestFirstLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestFirstLifecycleCallbacks::OnAbilityStart"); + callbackCount_.SetOnAbilityStartCount(); +} + +void KitTestFirstLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestFirstLifecycleCallbacks::OnAbilityInactive"); + callbackCount_.SetOnAbilityInactiveCount(); +} + +void KitTestFirstLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestFirstLifecycleCallbacks::OnAbilityBackground"); + callbackCount_.SetOnAbilityBackgroundCount(); +} + +void KitTestFirstLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestFirstLifecycleCallbacks::OnAbilityForeground"); + callbackCount_.SetOnAbilityForegroundCount(); +} + +void KitTestFirstLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestFirstLifecycleCallbacks::OnAbilityActive"); + callbackCount_.SetOnAbilityActiveCount(); +} + +void KitTestFirstLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestFirstLifecycleCallbacks::OnAbilityStop"); + callbackCount_.SetOnAbilityStopCount(); +} + +void KitTestFirstLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("KitTestFirstLifecycleCallbacks::OnAbilitySaveState"); + callbackCount_.SetOnAbilitySaveStateCount(); +} + +CallbackCount KitTestFirstLifecycleCallbacks::GetCallbackCount() +{ + return callbackCount_; +} + +// The Lifecycle callback function class (Second) +void KitTestSecondLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestSecondLifecycleCallbacks::OnAbilityStart"); + callbackCount_.SetOnAbilityStartCount(); +} + +void KitTestSecondLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestSecondLifecycleCallbacks::OnAbilityInactive"); + callbackCount_.SetOnAbilityInactiveCount(); +} + +void KitTestSecondLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestSecondLifecycleCallbacks::OnAbilityBackground"); + callbackCount_.SetOnAbilityBackgroundCount(); +} + +void KitTestSecondLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestSecondLifecycleCallbacks::OnAbilityForeground"); + callbackCount_.SetOnAbilityForegroundCount(); +} + +void KitTestSecondLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestSecondLifecycleCallbacks::OnAbilityActive"); + callbackCount_.SetOnAbilityActiveCount(); +} + +void KitTestSecondLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestSecondLifecycleCallbacks::OnAbilityStop"); + callbackCount_.SetOnAbilityStopCount(); +} + +void KitTestSecondLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("KitTestSecondLifecycleCallbacks::OnAbilitySaveState"); + callbackCount_.SetOnAbilitySaveStateCount(); +} + +CallbackCount KitTestSecondLifecycleCallbacks::GetCallbackCount() +{ + return callbackCount_; +} + +// The Lifecycle callback function class (Third) +void KitTestThirdLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestThirdLifecycleCallbacks::OnAbilityStart"); + std::string eventData = ability->GetAbilityName() + g_onAbilityStart; + TestUtils::PublishEvent(g_respPageSixthAbilityLifecycleCallbacks, 0, eventData); +} + +void KitTestThirdLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestThirdLifecycleCallbacks::OnAbilityInactive"); + std::string eventData = ability->GetAbilityName() + g_onAbilityInactive; + TestUtils::PublishEvent(g_respPageSixthAbilityLifecycleCallbacks, 0, eventData); +} + +void KitTestThirdLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestThirdLifecycleCallbacks::OnAbilityBackground"); + std::string eventData = ability->GetAbilityName() + g_onAbilityBackground; + TestUtils::PublishEvent(g_respPageSixthAbilityLifecycleCallbacks, 0, eventData); +} + +void KitTestThirdLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestThirdLifecycleCallbacks::OnAbilityForeground"); + std::string eventData = ability->GetAbilityName() + g_onAbilityForeground; + TestUtils::PublishEvent(g_respPageSixthAbilityLifecycleCallbacks, 0, eventData); +} + +void KitTestThirdLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestThirdLifecycleCallbacks::OnAbilityActive"); + std::string eventData = ability->GetAbilityName() + g_onAbilityActive; + TestUtils::PublishEvent(g_respPageSixthAbilityLifecycleCallbacks, 0, eventData); +} + +void KitTestThirdLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("KitTestThirdLifecycleCallbacks::OnAbilityStop"); + std::string eventData = ability->GetAbilityName() + g_onAbilityStop; + TestUtils::PublishEvent(g_respPageSixthAbilityLifecycleCallbacks, 0, eventData); +} + +void KitTestThirdLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("KitTestThirdLifecycleCallbacks::OnAbilitySaveState"); + std::string eventData = g_onAbilitySaveState; + TestUtils::PublishEvent(g_respPageSixthAbilityLifecycleCallbacks, 0, eventData); +} + +CallbackCount KitTestThirdLifecycleCallbacks::GetCallbackCount() +{ + return callbackCount_; +} + +// The Elements callback function class (First) +void KitTestFirstElementsCallback::OnConfigurationUpdated( + const std::shared_ptr &ability, const Configuration &config) +{ + APP_LOGI("KitTestFirstElementsCallback::OnConfigurationUpdated"); + callbackCount_.SetOnConfigurationCount(); +} + +void KitTestFirstElementsCallback::OnMemoryLevel(int level) +{ + APP_LOGI("KitTestFirstElementsCallback::OnMemoryLevel"); + callbackCount_.SetOnMemoryLevelCount(); +} + +CallbackCount KitTestFirstElementsCallback::GetCallbackCount() +{ + return callbackCount_; +} + +// The Elements callback function class (Second) +void KitTestSecondElementsCallback::OnConfigurationUpdated( + const std::shared_ptr &ability, const Configuration &config) +{ + APP_LOGI("KitTestSecondElementsCallback::OnConfigurationUpdated"); + callbackCount_.SetOnConfigurationCount(); +} + +void KitTestSecondElementsCallback::OnMemoryLevel(int level) +{ + APP_LOGI("KitTestSecondElementsCallback::OnMemoryLevel"); + callbackCount_.SetOnMemoryLevelCount(); +} + +CallbackCount KitTestSecondElementsCallback::GetCallbackCount() +{ + return callbackCount_; +} + +REGISTER_AA(SixthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f7fa556737647aecddbe3a8190286ad772fbb23 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg(delim); + std::vector res = { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; + return res; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/third_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/third_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3cf209df3b594d28a21c6b2d06e7bfb3a632462 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/third_ability.cpp @@ -0,0 +1,503 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "third_ability.h" +#include +#include +#include +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +namespace { +const std::string bundleName = "com.ohos.amsst.AppKit"; +const std::string specialProcessName = "//\\@#$%^&*!~;:,."; +const std::string normalProcessName = "com.ohos.amsst.AppKit"; +} // namespace + +void ThirdAbility::SubscribeEvent(const vector_conststr &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void ThirdAbility::ProcessInfoStByCode(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("ThirdAbility::ProcessInfoStByCode"); + if (mapStKitFunc_.find(apiIndex) != mapStKitFunc_.end() && + static_cast(mapStKitFunc_[apiIndex].size()) > caseIndex) { + mapStKitFunc_[apiIndex][caseIndex](code); + } else { + APP_LOGI("ProcessInfoStByCode error"); + } +} + +bool ThirdAbility::CompareProcessInfo(const ProcessInfo &processInfo1, const ProcessInfo &processInfo2) +{ + bool equalProcessName = (processInfo1.GetProcessName() == processInfo2.GetProcessName()); + bool equalPid = (processInfo1.GetPid() == processInfo2.GetPid()); + if (equalProcessName && equalPid) { + return true; + } else { + return false; + } +} + +void ThirdAbility::GetParcelByProcessName(ProcessInfo &processInfo, const std::string &expectedString, int code) +{ + Parcel parcel; + processInfo.Marshalling(parcel); + bool result = (expectedString == Str16ToStr8(parcel.ReadString16())); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::GetParcelByProcessID(ProcessInfo &processInfo, const int expectedInt, int code) +{ + Parcel parcel; + processInfo.Marshalling(parcel); + bool result = + (processInfo.GetProcessName() == Str16ToStr8(parcel.ReadString16())) && (expectedInt == parcel.ReadInt32()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::GetProcessNameByParcel(const std::string &processName, int processID, int code) +{ + Parcel parcel; + parcel.WriteString16(Str8ToStr16(processName)); + parcel.WriteInt32(processID); + ProcessInfo *processInfo = ProcessInfo::Unmarshalling(parcel); + bool result = (processName == processInfo->GetProcessName()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); + delete processInfo; + processInfo = nullptr; +} + +void ThirdAbility::GetProcessIDByParcel(const std::string &processName, int processID, int code) +{ + Parcel parcel; + parcel.WriteString16(Str8ToStr16(processName)); + parcel.WriteInt32(processID); + ProcessInfo *processInfo = ProcessInfo::Unmarshalling(parcel); + bool result = processInfo != nullptr; + if (processInfo) { + result = (processID == processInfo->GetPid()); + delete processInfo; + processInfo = nullptr; + } + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ComparePidProcessName( + ProcessInfo &processInfo, int expectedPid, const std::string &expectedName, int code) +{ + bool resultPid = (expectedPid == processInfo.GetPid()); + bool resultName = (expectedName == processInfo.GetProcessName()); + bool result = (resultPid && resultName); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetPidCase1(int code) +{ + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + bool result = processInfo != nullptr; + if (processInfo) { + result = (processInfo->GetPid() > 0); + } + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetPidCase2(int code) +{ + ProcessInfo processInfo; + bool result = (processInfo.GetPid() == 0); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetPidCase3(int code) +{ + ProcessInfo processInfo(normalProcessName, std::numeric_limits::min()); + bool result = (processInfo.GetPid() == std::numeric_limits::min()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetPidCase4(int code) +{ + ProcessInfo processInfo(normalProcessName, std::numeric_limits::max()); + bool result = (processInfo.GetPid() == std::numeric_limits::max()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetProcessNameCase1(int code) +{ + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + bool result = (bundleName == processInfo->GetProcessName()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetProcessNameCase2(int code) +{ + ProcessInfo processInfo; + bool result = (std::string() == processInfo.GetProcessName()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetProcessNameCase3(int code) +{ + ProcessInfo processInfo("", 0); + bool result = (processInfo.GetProcessName() == ""); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoGetProcessNameCase4(int code) +{ + ProcessInfo processInfo(specialProcessName, 0); + bool result = (specialProcessName == processInfo.GetProcessName()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoMarshallingCase1(int code) +{ + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + Parcel parcel; + processInfo->Marshalling(parcel); + std::string processName = Str16ToStr8(parcel.ReadString16()); + bool result = (processName == bundleName); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoMarshallingCase2(int code) +{ + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + Parcel parcel; + processInfo->Marshalling(parcel); + bool result = (parcel.ReadInt32() > 0); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoMarshallingCase3(int code) +{ + ProcessInfo processInfo(specialProcessName, 0); + GetParcelByProcessName(processInfo, specialProcessName, code); +} + +void ThirdAbility::ProcessInfoMarshallingCase4(int code) +{ + ProcessInfo processInfo(normalProcessName, std::numeric_limits::min()); + GetParcelByProcessID(processInfo, std::numeric_limits::min(), code); +} + +void ThirdAbility::ProcessInfoMarshallingCase5(int code) +{ + ProcessInfo processInfo("", 0); + GetParcelByProcessName(processInfo, "", code); +} + +void ThirdAbility::ProcessInfoMarshallingCase6(int code) +{ + ProcessInfo processInfo(normalProcessName, std::numeric_limits::max()); + GetParcelByProcessID(processInfo, std::numeric_limits::max(), code); +} + +void ThirdAbility::ProcessInfoUnmarshallingCase1(int code) +{ + GetProcessNameByParcel(specialProcessName, 0, code); +} + +void ThirdAbility::ProcessInfoUnmarshallingCase2(int code) +{ + GetProcessNameByParcel(normalProcessName, 0, code); +} + +void ThirdAbility::ProcessInfoUnmarshallingCase3(int code) +{ + GetProcessNameByParcel("", 0, code); +} + +void ThirdAbility::ProcessInfoUnmarshallingCase4(int code) +{ + GetProcessIDByParcel(normalProcessName, 0, code); +} + +void ThirdAbility::ProcessInfoUnmarshallingCase5(int code) +{ + GetProcessIDByParcel(normalProcessName, std::numeric_limits::min(), code); +} + +void ThirdAbility::ProcessInfoUnmarshallingCase6(int code) +{ + GetProcessIDByParcel(normalProcessName, std::numeric_limits::max(), code); +} + +void ThirdAbility::ProcessInfoUnmarshallingCase7(int code) +{ + ProcessInfo processInfoIn(normalProcessName, std::numeric_limits::max()); + ProcessInfo *processInfoOut = nullptr; + Parcel in; + processInfoIn.Marshalling(in); + processInfoOut = ProcessInfo::Unmarshalling(in); + if (processInfoOut == nullptr) { + return; + } + TestUtils::PublishEvent( + g_respPageThirdAbilityST, code, std::to_string(CompareProcessInfo(processInfoIn, *processInfoOut))); + delete processInfoOut; + processInfoOut = nullptr; +} + +void ThirdAbility::ProcessInfoUnmarshallingCase8(int code) +{ + ProcessInfo processInfoIn(specialProcessName, std::numeric_limits::max()); + ProcessInfo *processInfoOut = nullptr; + Parcel in; + processInfoIn.Marshalling(in); + processInfoOut = ProcessInfo::Unmarshalling(in); + if (processInfoOut == nullptr) { + return; + } + TestUtils::PublishEvent( + g_respPageThirdAbilityST, code, std::to_string(CompareProcessInfo(processInfoIn, *processInfoOut))); + delete processInfoOut; + processInfoOut = nullptr; +} + +void ThirdAbility::ProcessInfoUnmarshallingCase9(int code) +{ + ProcessInfo processInfoIn(specialProcessName, std::numeric_limits::min()); + ProcessInfo *processInfoOut = nullptr; + Parcel in; + processInfoIn.Marshalling(in); + processInfoOut = ProcessInfo::Unmarshalling(in); + if (processInfoOut == nullptr) { + return; + } + TestUtils::PublishEvent( + g_respPageThirdAbilityST, code, std::to_string(CompareProcessInfo(processInfoIn, *processInfoOut))); + delete processInfoOut; + processInfoOut = nullptr; +} + +void ThirdAbility::ProcessInfoProcessInfoCase1(int code) +{ + ProcessInfo processInfo; + bool result = (processInfo.GetPid() == 0); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoProcessInfoCase2(int code) +{ + ProcessInfo processInfo; + bool result = (processInfo.GetProcessName().empty()); + TestUtils::PublishEvent(g_respPageThirdAbilityST, code, std::to_string(result)); +} + +void ThirdAbility::ProcessInfoProcessInfoStringintCase1(int code) +{ + ProcessInfo processInfo(normalProcessName, 0); + ComparePidProcessName(processInfo, 0, normalProcessName, code); +} + +void ThirdAbility::ProcessInfoProcessInfoStringintCase2(int code) +{ + ProcessInfo processInfo(normalProcessName, std::numeric_limits::min()); + ComparePidProcessName(processInfo, std::numeric_limits::min(), normalProcessName, code); +} + +void ThirdAbility::ProcessInfoProcessInfoStringintCase3(int code) +{ + ProcessInfo processInfo(normalProcessName, std::numeric_limits::max()); + ComparePidProcessName(processInfo, std::numeric_limits::max(), normalProcessName, code); +} + +void ThirdAbility::ProcessInfoProcessInfoStringintCase4(int code) +{ + ProcessInfo processInfo(specialProcessName, 0); + ComparePidProcessName(processInfo, 0, specialProcessName, code); +} + +void ThirdAbility::ProcessInfoProcessInfoStringintCase5(int code) +{ + ProcessInfo processInfo(specialProcessName, std::numeric_limits::min()); + ComparePidProcessName(processInfo, std::numeric_limits::min(), specialProcessName, code); +} + +void ThirdAbility::ProcessInfoProcessInfoStringintCase6(int code) +{ + ProcessInfo processInfo(specialProcessName, std::numeric_limits::max()); + ComparePidProcessName(processInfo, std::numeric_limits::max(), specialProcessName, code); +} + +void ThirdAbility::OnStart(const Want &want) +{ + APP_LOGI("ThirdAbility::onStart"); + GetWantInfo(want); + Ability::OnStart(want); + SubscribeEvent(g_requPageThirdAbilitySTVector); + std::string eventData = GetAbilityName() + g_abilityStateOnStart; + TestUtils::PublishEvent(g_respPageThirdAbilityST, 0, eventData); +} + +void ThirdAbility::OnStop() +{ + APP_LOGI("ThirdAbility::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + std::string eventData = GetAbilityName() + g_abilityStateOnStop; + TestUtils::PublishEvent(g_respPageThirdAbilityST, 0, eventData); +} + +void ThirdAbility::OnActive() +{ + APP_LOGI("ThirdAbility::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAabilityName = this->Split(targetAbility_, ","); + if (!startBundleName.empty() && !startAabilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAabilityName); + want.SetParam("shouldReturn", shouldReturn_); + if (!targetBundle_.empty() && !targetAbility_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn_.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + g_abilityStateOnActive; + TestUtils::PublishEvent(g_respPageThirdAbilityST, 0, eventData); +} + +void ThirdAbility::OnInactive() +{ + APP_LOGI("ThirdAbility::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + g_abilityStateOnInactive; + TestUtils::PublishEvent(g_respPageThirdAbilityST, 0, eventData); +} + +void ThirdAbility::OnBackground() +{ + APP_LOGI("ThirdAbility::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + g_abilityStateOnBackground; + TestUtils::PublishEvent(g_respPageThirdAbilityST, 0, eventData); +} + +void ThirdAbility::OnForeground(const Want &want) +{ + APP_LOGI("ThirdAbility::OnForeground"); + GetWantInfo(want); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + g_abilityStateOnForeground; + TestUtils::PublishEvent(g_respPageThirdAbilityST, 0, eventData); +} + +void ThirdAbility::OnNewWant(const Want &want) +{ + APP_LOGI("ThirdAbility::OnNewWant"); + GetWantInfo(want); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + g_abilityStateOnNewWant; + TestUtils::PublishEvent(g_respPageThirdAbilityST, 0, eventData); +} + +void ThirdAbility::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void ThirdAbility::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string ThirdAbility::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void KitTestThirdEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (g_requPageThirdAbilityST == eventName) { + auto target = data.GetData(); + auto handle = 0; + auto api = 1; + auto code = 2; + auto paramMinSize = 3; + vector_str splitResult = TestUtils::split(target, "_"); + auto keyMap = splitResult.at(handle); + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && + splitResult.size() >= static_cast(paramMinSize)) { + auto apiIndex = atoi(splitResult.at(api).c_str()); + auto caseIndex = atoi(splitResult.at(code).c_str()); + mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); + } else { + if (keyMap == "TerminateAbility") { + KitTerminateAbility(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } + } +} + +void KitTestThirdEventSubscriber::ProcessInfoStByCode(int apiIndex, int caseIndex, int code) +{ + if (thirdAbility_ != nullptr) { + thirdAbility_->ProcessInfoStByCode(apiIndex, caseIndex, code); + } +} + +void KitTestThirdEventSubscriber::KitTerminateAbility() +{ + if (thirdAbility_ != nullptr) { + thirdAbility_->TerminateAbility(); + } +} + +REGISTER_AA(ThirdAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..c3582cdfed7e197ecff58d04fecdb9e60885486b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsKitSystemTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitSystemTestA\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsKitSystemTestA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + ] + configs = [ ":amsKitSystemTestAConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b6f44b3fbadd5d72b3bf1617ed7c160737bae993 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/config.json @@ -0,0 +1,53 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKitA", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.AmsKitSystemTestA.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Second Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..24234d7332f8ce5c734198b9ad34249d4afb65c9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H +#define AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void GetApplicationInfoCase1(int code); + void GetApplicationInfoCase2(int code); + void GetApplicationInfoCase3(int code); + + void GetCacheDirCase1(int code); + void GetCacheDirCase2(int code); + void GetCacheDirCase3(int code); + + void GetDatabaseDirCase1(int code); + void GetDatabaseDirCase2(int code); + void GetDatabaseDirCase3(int code); + + void GetDataDirCase1(int code); + void GetDataDirCase2(int code); + void GetDataDirCase3(int code); + + void GetDirCase1(int code); + void GetDirCase2(int code); + void GetDirCase3(int code); + + void GetNoBackupFilesDirCase1(int code); + + void GetBundleManagerCase1(int code); + + void VerifyCallingPermissionCase1(int code); + + void VerifyPermissionCase1(int code); + + void VerifySelfPermissionCase1(int code); + + void GetBundleCodePathCase1(int code); + void GetBundleCodePathCase2(int code); + void GetBundleCodePathCase3(int code); + + void GetBundleNameCase1(int code); + void GetBundleNameCase2(int code); + void GetBundleNameCase3(int code); + + void GetBundleResourcePathCase1(int code); + void GetBundleResourcePathCase2(int code); + void GetBundleResourcePathCase3(int code); + + void CanRequestPermissionCase1(int code); + + void GetCallingAbilityCase1(int code); + void GetCallingAbilityCase2(int code); + void GetCallingAbilityCase3(int code); + + void GetContextCase1(int code); + + void GetAbilityManagerCase1(int code); + + void GetProcessInfoCase1(int code); + void GetProcessInfoCase2(int code); + void GetProcessInfoCase3(int code); + + void GetAppTypeCase1(int code); + void GetAppTypeCase2(int code); + void GetAppTypeCase3(int code); + + void GetCallingBundleCase1(int code); + void GetCallingBundleCase2(int code); + void GetCallingBundleCase3(int code); + + void StartAbilityCase1(int code); + void StartAbilityCase2(int code); + + void TerminateAbilityCase1(int code); + + void GetElementNameCase1(int code); + void GetElementNameCase2(int code); + void GetElementNameCase3(int code); + + void GetHapModuleInfoCase1(int code); + void GetHapModuleInfoCase2(int code); + void GetHapModuleInfoCase3(int code); + + void GetCodeCacheDirCase1(int code); + void GetCodeCacheDirCase2(int code); + void GetCodeCacheDirCase3(int code); + + void GetApplicationContextCase1(int code); + + std::unordered_map>> mapCase_; + ~MainAbility(); + + void initCaseFirst() + { + std::unordered_map>> first = { + {(int)AbilityContextApi::GetApplicationInfo, + { + [this](int code) { GetApplicationInfoCase1(code); }, + [this](int code) { GetApplicationInfoCase2(code); }, + [this](int code) { GetApplicationInfoCase3(code); }, + }}, + {(int)AbilityContextApi::GetCacheDir, + { + [this](int code) { GetCacheDirCase1(code); }, + [this](int code) { GetCacheDirCase2(code); }, + [this](int code) { GetCacheDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetCodeCacheDir, + { + [this](int code) { GetCodeCacheDirCase1(code); }, + [this](int code) { GetCodeCacheDirCase2(code); }, + [this](int code) { GetCodeCacheDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetDatabaseDir, + { + [this](int code) { GetDatabaseDirCase1(code); }, + [this](int code) { GetDatabaseDirCase2(code); }, + [this](int code) { GetDatabaseDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetDataDir, + { + [this](int code) { GetDataDirCase1(code); }, + [this](int code) { GetDataDirCase2(code); }, + [this](int code) { GetDataDirCase3(code); }, + }}, + }; + mapCase_.insert(first.begin(), first.end()); + } + + void initCaseSecond() + { + std::unordered_map>> second = { + {(int)AbilityContextApi::GetDir, + { + [this](int code) { GetDirCase1(code); }, + [this](int code) { GetDirCase2(code); }, + [this](int code) { GetDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleManager, + { + [this](int code) { GetBundleManagerCase1(code); }, + }}, + {(int)AbilityContextApi::GetBundleCodePath, + { + [this](int code) { GetBundleCodePathCase1(code); }, + [this](int code) { GetBundleCodePathCase2(code); }, + [this](int code) { GetBundleCodePathCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleName, + { + [this](int code) { GetBundleNameCase1(code); }, + [this](int code) { GetBundleNameCase2(code); }, + [this](int code) { GetBundleNameCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleResourcePath, + { + [this](int code) { GetBundleResourcePathCase1(code); }, + [this](int code) { GetBundleResourcePathCase2(code); }, + [this](int code) { GetBundleResourcePathCase3(code); }, + }}, + {(int)AbilityContextApi::GetApplicationContext, + { + [this](int code) { GetApplicationContextCase1(code); }, + }}, + {(int)AbilityContextApi::GetCallingAbility, + { + [this](int code) { GetCallingAbilityCase1(code); }, + [this](int code) { GetCallingAbilityCase2(code); }, + [this](int code) { GetCallingAbilityCase3(code); }, + }}, + {(int)AbilityContextApi::GetContext, + { + [this](int code) { GetContextCase1(code); }, + }}, + }; + mapCase_.insert(second.begin(), second.end()); + } + + void initCaseThird() + { + std::unordered_map>> third = { + {(int)AbilityContextApi::GetAbilityManager, + { + [this](int code) { GetAbilityManagerCase1(code); }, + }}, + {(int)AbilityContextApi::GetProcessInfo, + { + [this](int code) { GetProcessInfoCase1(code); }, + [this](int code) { GetProcessInfoCase2(code); }, + [this](int code) { GetProcessInfoCase3(code); }, + }}, + {(int)AbilityContextApi::GetAppType, + { + [this](int code) { GetAppTypeCase1(code); }, + [this](int code) { GetAppTypeCase2(code); }, + [this](int code) { GetAppTypeCase3(code); }, + }}, + {(int)AbilityContextApi::GetCallingBundle, + { + [this](int code) { GetCallingBundleCase1(code); }, + [this](int code) { GetCallingBundleCase2(code); }, + [this](int code) { GetCallingBundleCase3(code); }, + }}, + {(int)AbilityContextApi::StartAbility_Want_int, + { + [this](int code) { StartAbilityCase1(code); }, + [this](int code) { StartAbilityCase2(code); }, + }}, + {(int)AbilityContextApi::TerminateAbility, + { + [this](int code) { TerminateAbilityCase1(code); }, + }}, + {(int)AbilityContextApi::GetElementName, + { + [this](int code) { GetElementNameCase1(code); }, + [this](int code) { GetElementNameCase2(code); }, + [this](int code) { GetElementNameCase3(code); }, + }}, + {(int)AbilityContextApi::GetHapModuleInfo, + { + [this](int code) { GetHapModuleInfoCase1(code); }, + [this](int code) { GetHapModuleInfoCase2(code); }, + [this](int code) { GetHapModuleInfoCase3(code); }, + }}, + }; + mapCase_.insert(third.begin(), third.end()); + } + + MainAbility() + { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + virtual void OnBackPressed() override; + virtual void OnNewWant(const Want &want) override; + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Ability", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..e926c2c433551955992e061c58deeb8d77489545 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_KIT_SYSTEM_TEST_A_SECOND_ABILITY_H +#define AMS_KIT_SYSTEM_TEST_A_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void GetApplicationInfoCase1(int code); + void GetApplicationInfoCase2(int code); + void GetApplicationInfoCase3(int code); + + void GetCacheDirCase1(int code); + void GetCacheDirCase2(int code); + void GetCacheDirCase3(int code); + + void GetDatabaseDirCase1(int code); + void GetDatabaseDirCase2(int code); + void GetDatabaseDirCase3(int code); + + void GetDataDirCase1(int code); + void GetDataDirCase2(int code); + void GetDataDirCase3(int code); + + void GetDirCase1(int code); + void GetDirCase2(int code); + void GetDirCase3(int code); + + void GetNoBackupFilesDirCase1(int code); + + void GetBundleManagerCase1(int code); + + void VerifyCallingPermissionCase1(int code); + + void VerifyPermissionCase1(int code); + + void VerifySelfPermissionCase1(int code); + + void GetBundleCodePathCase1(int code); + void GetBundleCodePathCase2(int code); + void GetBundleCodePathCase3(int code); + + void GetBundleNameCase1(int code); + void GetBundleNameCase2(int code); + void GetBundleNameCase3(int code); + + void GetBundleResourcePathCase1(int code); + void GetBundleResourcePathCase2(int code); + void GetBundleResourcePathCase3(int code); + + void CanRequestPermissionCase1(int code); + + void GetCallingAbilityCase1(int code); + void GetCallingAbilityCase2(int code); + void GetCallingAbilityCase3(int code); + + void GetContextCase1(int code); + + void GetAbilityManagerCase1(int code); + + void GetProcessInfoCase1(int code); + void GetProcessInfoCase2(int code); + void GetProcessInfoCase3(int code); + + void GetAppTypeCase1(int code); + void GetAppTypeCase2(int code); + void GetAppTypeCase3(int code); + + void GetCallingBundleCase1(int code); + void GetCallingBundleCase2(int code); + void GetCallingBundleCase3(int code); + + void StartAbilityCase1(int code); + void StartAbilityCase2(int code); + + void TerminateAbilityCase1(int code); + + void GetElementNameCase1(int code); + void GetElementNameCase2(int code); + void GetElementNameCase3(int code); + + void GetHapModuleInfoCase1(int code); + void GetHapModuleInfoCase2(int code); + void GetHapModuleInfoCase3(int code); + + void GetCodeCacheDirCase1(int code); + void GetCodeCacheDirCase2(int code); + void GetCodeCacheDirCase3(int code); + + void GetApplicationContextCase1(int code); + + SecondAbility() + { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } + + void initCaseFirst() + { + std::unordered_map>> first = { + {(int)AbilityContextApi::GetApplicationInfo, + { + [this](int code) { GetApplicationInfoCase1(code); }, + [this](int code) { GetApplicationInfoCase2(code); }, + [this](int code) { GetApplicationInfoCase3(code); }, + }}, + {(int)AbilityContextApi::GetCacheDir, + { + [this](int code) { GetCacheDirCase1(code); }, + [this](int code) { GetCacheDirCase2(code); }, + [this](int code) { GetCacheDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetCodeCacheDir, + { + [this](int code) { GetCodeCacheDirCase1(code); }, + [this](int code) { GetCodeCacheDirCase2(code); }, + [this](int code) { GetCodeCacheDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetDatabaseDir, + { + [this](int code) { GetDatabaseDirCase1(code); }, + [this](int code) { GetDatabaseDirCase2(code); }, + [this](int code) { GetDatabaseDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetDataDir, + { + [this](int code) { GetDataDirCase1(code); }, + [this](int code) { GetDataDirCase2(code); }, + [this](int code) { GetDataDirCase3(code); }, + }}, + }; + mapCase_.insert(first.begin(), first.end()); + } + + void initCaseSecond() + { + std::unordered_map>> second = { + {(int)AbilityContextApi::GetDir, + { + [this](int code) { GetDirCase1(code); }, + [this](int code) { GetDirCase2(code); }, + [this](int code) { GetDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleManager, + { + [this](int code) { GetBundleManagerCase1(code); }, + }}, + {(int)AbilityContextApi::GetBundleCodePath, + { + [this](int code) { GetBundleCodePathCase1(code); }, + [this](int code) { GetBundleCodePathCase2(code); }, + [this](int code) { GetBundleCodePathCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleName, + { + [this](int code) { GetBundleNameCase1(code); }, + [this](int code) { GetBundleNameCase2(code); }, + [this](int code) { GetBundleNameCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleResourcePath, + { + [this](int code) { GetBundleResourcePathCase1(code); }, + [this](int code) { GetBundleResourcePathCase2(code); }, + [this](int code) { GetBundleResourcePathCase3(code); }, + }}, + {(int)AbilityContextApi::GetApplicationContext, + { + [this](int code) { GetApplicationContextCase1(code); }, + }}, + {(int)AbilityContextApi::GetCallingAbility, + { + [this](int code) { GetCallingAbilityCase1(code); }, + [this](int code) { GetCallingAbilityCase2(code); }, + [this](int code) { GetCallingAbilityCase3(code); }, + }}, + {(int)AbilityContextApi::GetContext, + { + [this](int code) { GetContextCase1(code); }, + }}, + }; + mapCase_.insert(second.begin(), second.end()); + } + + void initCaseThird() + { + std::unordered_map>> third = { + {(int)AbilityContextApi::GetAbilityManager, + { + [this](int code) { GetAbilityManagerCase1(code); }, + }}, + {(int)AbilityContextApi::GetProcessInfo, + { + [this](int code) { GetProcessInfoCase1(code); }, + [this](int code) { GetProcessInfoCase2(code); }, + [this](int code) { GetProcessInfoCase3(code); }, + }}, + {(int)AbilityContextApi::GetAppType, + { + [this](int code) { GetAppTypeCase1(code); }, + [this](int code) { GetAppTypeCase2(code); }, + [this](int code) { GetAppTypeCase3(code); }, + }}, + {(int)AbilityContextApi::GetCallingBundle, + { + [this](int code) { GetCallingBundleCase1(code); }, + [this](int code) { GetCallingBundleCase2(code); }, + [this](int code) { GetCallingBundleCase3(code); }, + }}, + {(int)AbilityContextApi::StartAbility_Want_int, + { + [this](int code) { StartAbilityCase1(code); }, + [this](int code) { StartAbilityCase2(code); }, + }}, + {(int)AbilityContextApi::TerminateAbility, + { + [this](int code) { TerminateAbilityCase1(code); }, + }}, + {(int)AbilityContextApi::GetElementName, + { + [this](int code) { GetElementNameCase1(code); }, + [this](int code) { GetElementNameCase2(code); }, + [this](int code) { GetElementNameCase3(code); }, + }}, + {(int)AbilityContextApi::GetHapModuleInfo, + { + [this](int code) { GetHapModuleInfoCase1(code); }, + [this](int code) { GetHapModuleInfoCase2(code); }, + [this](int code) { GetHapModuleInfoCase3(code); }, + }}, + }; + mapCase_.insert(third.begin(), third.end()); + } + std::unordered_map>> mapCase_; + int callingTime = 0; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + virtual void OnBackPressed() override; + virtual void OnNewWant(const Want &want) override; + std::shared_ptr subscriber_; +}; +class SecondEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Ability", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~SecondEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..241f5a44d2d365ad3eb31f4e323afae00b6bb164 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp @@ -0,0 +1,581 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +const int MainAbilityACode = 100; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MainAbilityACode, "onStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MainAbilityACode, "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MainAbilityACode, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MainAbilityACode, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MainAbilityACode, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_LIFECYCLE, MainAbilityACode, "OnForeground"); +} + +void MainAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("MainAbility::OnAbilityResult"); + Ability::OnAbilityResult(requestCode, resultCode, resultData); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_ON_ABILITY_RESULT, 0, resultData.ToUri()); +} + +void MainAbility::OnBackPressed() +{ + APP_LOGI("MainAbility::OnBackPressed"); + Ability::OnBackPressed(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_ON_BACK_PRESSED, 0, ""); +} + +void MainAbility::OnNewWant(const Want &want) +{ + APP_LOGI("MainAbility::OnNewWant"); + Ability::OnNewWant(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_ON_NEW_WANT, 0, want.ToUri()); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIRST, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void MainAbility::GetApplicationInfoCase1(int code) +{ + auto appInfo = AbilityContext::GetApplicationInfo(); + string result = ""; + if (appInfo != nullptr) { + result = appInfo->name; + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} +void MainAbility::GetApplicationInfoCase2(int code) +{ + auto appInfo = AbilityContext::GetApplicationInfo(); + string result = ""; + if (appInfo != nullptr) { + result = appInfo->name; + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} +void MainAbility::GetApplicationInfoCase3(int code) +{ + auto appInfo = AbilityContext::GetApplicationInfo(); + string result = ""; + if (appInfo != nullptr) { + result = appInfo->name; + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetCacheDirCase1(int code) +{ + string cacheDir = AbilityContext::GetCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, cacheDir); +} +void MainAbility::GetCacheDirCase2(int code) +{ + string cacheDir = AbilityContext::GetCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, cacheDir); +} +void MainAbility::GetCacheDirCase3(int code) +{ + string cacheDir = AbilityContext::GetCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, cacheDir); +} + +void MainAbility::GetDatabaseDirCase1(int code) +{ + string databaseDir = AbilityContext::GetDatabaseDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, databaseDir); +} +void MainAbility::GetDatabaseDirCase2(int code) +{ + string databaseDir = AbilityContext::GetDatabaseDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, databaseDir); +} +void MainAbility::GetDatabaseDirCase3(int code) +{ + string databaseDir = AbilityContext::GetDatabaseDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, databaseDir); +} + +void MainAbility::GetDataDirCase1(int code) +{ + string dataDir = AbilityContext::GetDataDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, dataDir); +} + +void MainAbility::GetDataDirCase2(int code) +{ + string dataDir = AbilityContext::GetDataDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, dataDir); +} + +void MainAbility::GetDataDirCase3(int code) +{ + string dataDir = AbilityContext::GetDataDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, dataDir); +} + +void MainAbility::GetDirCase1(int code) +{ + string name = "getDir"; + string dir = AbilityContext::GetDir(name, 0); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, dir); +} + +void MainAbility::GetDirCase2(int code) +{ + string name = "getDir"; + string dir = AbilityContext::GetDir(name, 0); + dir = AbilityContext::GetDir(name, 0); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, dir); +} + +void MainAbility::GetDirCase3(int code) +{ + string name = "getDir"; + string dir = AbilityContext::GetDir(name, 0); + dir = AbilityContext::GetDir(name, 0); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, dir); +} + +void MainAbility::GetNoBackupFilesDirCase1(int code) +{} + +void MainAbility::GetBundleManagerCase1(int code) +{ + auto bundleManger = AbilityContext::GetBundleManager(); + int result = 1; + if (bundleManger == nullptr) + result = 0; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::VerifyCallingPermissionCase1(int code) +{} + +void MainAbility::VerifyPermissionCase1(int code) +{} + +void MainAbility::VerifySelfPermissionCase1(int code) +{} + +void MainAbility::GetBundleCodePathCase1(int code) +{ + string bundleCodePath = AbilityContext::GetBundleCodePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleCodePath); +} + +void MainAbility::GetBundleCodePathCase2(int code) +{ + string bundleCodePath = AbilityContext::GetBundleCodePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleCodePath); +} + +void MainAbility::GetBundleCodePathCase3(int code) +{ + string bundleCodePath = AbilityContext::GetBundleCodePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleCodePath); +} + +void MainAbility::GetBundleNameCase1(int code) +{ + string bundleName = AbilityContext::GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleName); +} + +void MainAbility::GetBundleNameCase2(int code) +{ + string bundleName = AbilityContext::GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleName); +} + +void MainAbility::GetBundleNameCase3(int code) +{ + string bundleName = AbilityContext::GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleName); +} + +void MainAbility::GetBundleResourcePathCase1(int code) +{ + string bundleResourcePath = AbilityContext::GetBundleResourcePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleResourcePath); +} + +void MainAbility::GetBundleResourcePathCase2(int code) +{ + string bundleResourcePath = AbilityContext::GetBundleResourcePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleResourcePath); +} + +void MainAbility::GetBundleResourcePathCase3(int code) +{ + string bundleResourcePath = AbilityContext::GetBundleResourcePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, bundleResourcePath); +} + +void MainAbility::CanRequestPermissionCase1(int code) +{} + +void MainAbility::GetCallingAbilityCase1(int code) +{ + string targetBundle = "com.ohos.amsst.AppKitA"; + string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::GetCallingAbilityCase2(int code) +{ + string targetBundle1 = "com.ohos.amsst.AppKitA"; + string targetAbility1 = "SecondAbility"; + Want want; + want.SetElementName(targetBundle1, targetAbility1); + want.SetParam("operator", 0); + StartAbility(want); + + string targetBundle2 = "com.ohos.amsst.AppKitB"; + string targetAbility2 = "MainAbility"; + want.SetElementName(targetBundle2, targetAbility2); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::GetCallingAbilityCase3(int code) +{ + string targetBundle = "com.ohos.amsst.AppKitA"; + string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::GetContextCase1(int code) +{ + auto context = AbilityContext::GetContext(); + string result = "0"; + if (context != nullptr) + result = "1"; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetAbilityManagerCase1(int code) +{ + auto abilityManger = AbilityContext::GetAbilityManager(); + string result = "0"; + if (abilityManger != nullptr) + result = "1"; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetProcessInfoCase1(int code) +{ + auto processInfo = AbilityContext::GetProcessInfo(); + string result = ""; + if (processInfo != nullptr) { + result = processInfo->GetProcessName(); + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetProcessInfoCase2(int code) +{ + auto processInfo = AbilityContext::GetProcessInfo(); + string result = ""; + if (processInfo != nullptr) { + result = processInfo->GetProcessName(); + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetProcessInfoCase3(int code) +{ + auto processInfo = AbilityContext::GetProcessInfo(); + string result = ""; + if (processInfo != nullptr) { + result = processInfo->GetProcessName(); + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetAppTypeCase1(int code) +{ + string appType = AbilityContext::GetAppType(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, appType); +} + +void MainAbility::GetAppTypeCase2(int code) +{ + string appType = AbilityContext::GetAppType(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, appType); +} + +void MainAbility::GetAppTypeCase3(int code) +{ + string appType = AbilityContext::GetAppType(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, appType); +} + +void MainAbility::GetCallingBundleCase1(int code) +{ + string targetBundle = "com.ohos.amsst.AppKitA"; + string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::GetCallingBundleCase2(int code) +{ + string targetBundle1 = "com.ohos.amsst.AppKitA"; + string targetAbility1 = "SecondAbility"; + Want want; + want.SetElementName(targetBundle1, targetAbility1); + want.SetParam("operator", 0); + StartAbility(want); + + string targetBundle2 = "com.ohos.amsst.AppKitB"; + string targetAbility2 = "MainAbility"; + want.SetElementName(targetBundle2, targetAbility2); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::GetCallingBundleCase3(int code) +{ + string targetBundle = "com.ohos.amsst.AppKitA"; + string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::StartAbilityCase1(int code) +{ + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.AppKitA", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, "startAbility"); +} + +void MainAbility::StartAbilityCase2(int code) +{ + std::map params; + Want want = TestUtils::MakeWant("", "MainAbility", "com.ohos.amsst.AppKitB", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, "startAbility"); +} + +void MainAbility::TerminateAbilityCase1(int code) +{ + AbilityContext::TerminateAbility(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, "TerminateAbility"); +} + +void MainAbility::GetElementNameCase1(int code) +{ + auto elementName = AbilityContext::GetElementName(); + string result = ""; + if (elementName != nullptr) + result = elementName->GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetElementNameCase2(int code) +{ + auto elementName = AbilityContext::GetElementName(); + string result = ""; + if (elementName != nullptr) + result = elementName->GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetElementNameCase3(int code) +{ + auto elementName = AbilityContext::GetElementName(); + string result = ""; + if (elementName != nullptr) + result = elementName->GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetHapModuleInfoCase1(int code) +{ + auto elementName = AbilityContext::GetHapModuleInfo(); + string result = ""; + if (elementName != nullptr) + result = elementName->moduleName; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetHapModuleInfoCase2(int code) +{ + auto elementName = AbilityContext::GetHapModuleInfo(); + string result = ""; + if (elementName != nullptr) + result = elementName->moduleName; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetHapModuleInfoCase3(int code) +{ + auto elementName = AbilityContext::GetHapModuleInfo(); + string result = ""; + if (elementName != nullptr) + result = elementName->moduleName; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +void MainAbility::GetCodeCacheDirCase1(int code) +{ + string codeCacheDir = AbilityContext::GetCodeCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, codeCacheDir); +} +void MainAbility::GetCodeCacheDirCase2(int code) +{ + string codeCacheDir = AbilityContext::GetCodeCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, codeCacheDir); +} +void MainAbility::GetCodeCacheDirCase3(int code) +{ + string codeCacheDir = AbilityContext::GetCodeCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, codeCacheDir); +} + +void MainAbility::GetApplicationContextCase1(int code) +{ + auto elementName = AbilityContext::GetApplicationContext(); + string result = ""; + if (elementName != nullptr) + result = "1"; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, result); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70aa48177ed9dcee0083fe94206c63455d30d707 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp @@ -0,0 +1,410 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +const int SecondAbilityACode = 200; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SecondAbilityACode, "onStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SecondAbilityACode, "OnStop"); +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SecondAbilityACode, "OnActive"); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SecondAbilityACode, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SecondAbilityACode, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SecondAbilityACode, "OnForeground"); +} + +void SecondAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("SecondAbility::OnAbilityResult"); + Ability::OnAbilityResult(requestCode, resultCode, resultData); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, 0, resultData.ToUri()); +} + +void SecondAbility::OnBackPressed() +{ + APP_LOGI("SecondAbility::OnBackPressed"); + Ability::OnBackPressed(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, 0, ""); +} + +void SecondAbility::OnNewWant(const Want &want) +{ + APP_LOGI("SecondAbility::OnNewWant"); + Ability::OnNewWant(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, 0, want.ToUri()); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::GetApplicationInfoCase1(int code) +{} +void SecondAbility::GetApplicationInfoCase2(int code) +{ + auto appInfo = AbilityContext::GetApplicationInfo(); + string result = ""; + if (appInfo != nullptr) { + result = appInfo->name; + } + + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, result); +} +void SecondAbility::GetApplicationInfoCase3(int code) +{} + +void SecondAbility::GetCacheDirCase1(int code) +{} +void SecondAbility::GetCacheDirCase2(int code) +{ + string cacheDir = AbilityContext::GetCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, cacheDir); +} +void SecondAbility::GetCacheDirCase3(int code) +{} + +void SecondAbility::GetDatabaseDirCase1(int code) +{} +void SecondAbility::GetDatabaseDirCase2(int code) +{ + string databaseDir = AbilityContext::GetDatabaseDir(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, databaseDir); +} +void SecondAbility::GetDatabaseDirCase3(int code) +{} + +void SecondAbility::GetDataDirCase1(int code) +{} + +void SecondAbility::GetDataDirCase2(int code) +{ + string dataDir = AbilityContext::GetDataDir(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, dataDir); +} + +void SecondAbility::GetDataDirCase3(int code) +{} + +void SecondAbility::GetDirCase1(int code) +{} + +void SecondAbility::GetDirCase2(int code) +{ + string name = "getDir"; + string dir = AbilityContext::GetDir(name, 0); + dir = AbilityContext::GetDir(name, 0); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, dir); +} + +void SecondAbility::GetDirCase3(int code) +{} + +void SecondAbility::GetNoBackupFilesDirCase1(int code) +{} + +void SecondAbility::GetBundleManagerCase1(int code) +{} + +void SecondAbility::VerifyCallingPermissionCase1(int code) +{} + +void SecondAbility::VerifyPermissionCase1(int code) +{} + +void SecondAbility::VerifySelfPermissionCase1(int code) +{} + +void SecondAbility::GetBundleCodePathCase1(int code) +{} + +void SecondAbility::GetBundleCodePathCase2(int code) +{ + string bundleCodePath = AbilityContext::GetBundleCodePath(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, bundleCodePath); +} + +void SecondAbility::GetBundleCodePathCase3(int code) +{} + +void SecondAbility::GetBundleNameCase1(int code) +{} + +void SecondAbility::GetBundleNameCase2(int code) +{ + string bundleName = AbilityContext::GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, bundleName); +} + +void SecondAbility::GetBundleNameCase3(int code) +{} + +void SecondAbility::GetBundleResourcePathCase1(int code) +{} + +void SecondAbility::GetBundleResourcePathCase2(int code) +{ + string bundleResourcePath = AbilityContext::GetBundleResourcePath(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, bundleResourcePath); +} + +void SecondAbility::GetBundleResourcePathCase3(int code) +{} + +void SecondAbility::CanRequestPermissionCase1(int code) +{} + +void SecondAbility::GetCallingAbilityCase1(int code) +{ + auto callingAbility = AbilityContext::GetCallingAbility(); + string result = ""; + if (callingAbility != nullptr) + result = callingAbility->GetURI(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, result); +} + +void SecondAbility::GetCallingAbilityCase2(int code) +{ + auto callingAbility = AbilityContext::GetCallingAbility(); + string result = ""; + if (callingAbility != nullptr) + result = callingAbility->GetURI(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, result); +} + +void SecondAbility::GetCallingAbilityCase3(int code) +{ + auto callingAbility = AbilityContext::GetCallingAbility(); + string result = ""; + if (callingAbility != nullptr && (callingTime == 0 || callingTime == code)) { + callingTime = code; + result = callingAbility->GetURI(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, result); + } +} + +void SecondAbility::GetContextCase1(int code) +{} + +void SecondAbility::GetAbilityManagerCase1(int code) +{} + +void SecondAbility::GetProcessInfoCase1(int code) +{} + +void SecondAbility::GetProcessInfoCase2(int code) +{ + auto processInfo = AbilityContext::GetProcessInfo(); + string result = ""; + if (processInfo != nullptr) { + result = processInfo->GetProcessName(); + } + + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, result); +} + +void SecondAbility::GetProcessInfoCase3(int code) +{} + +void SecondAbility::GetAppTypeCase1(int code) +{} + +void SecondAbility::GetAppTypeCase2(int code) +{ + string appType = AbilityContext::GetAppType(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, appType); +} + +void SecondAbility::GetAppTypeCase3(int code) +{} + +void SecondAbility::GetCallingBundleCase1(int code) +{ + string callingBundle = AbilityContext::GetCallingBundle(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, callingBundle); +} + +void SecondAbility::GetCallingBundleCase2(int code) +{ + string callingBundle = AbilityContext::GetCallingBundle(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, callingBundle); +} + +void SecondAbility::GetCallingBundleCase3(int code) +{ + string callingBundle = ""; + if (callingTime == 0 || callingTime == code) { + callingTime = code; + callingBundle = AbilityContext::GetCallingBundle(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, callingBundle); + } +} + +void SecondAbility::StartAbilityCase1(int code) +{} + +void SecondAbility::StartAbilityCase2(int code) +{} + +void SecondAbility::TerminateAbilityCase1(int code) +{} + +void SecondAbility::GetElementNameCase1(int code) +{} + +void SecondAbility::GetElementNameCase2(int code) +{ + auto elementName = AbilityContext::GetElementName(); + string result = ""; + if (elementName != nullptr) + result = elementName->GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, result); +} + +void SecondAbility::GetElementNameCase3(int code) +{} + +void SecondAbility::GetHapModuleInfoCase1(int code) +{} + +void SecondAbility::GetHapModuleInfoCase2(int code) +{ + auto elementName = AbilityContext::GetHapModuleInfo(); + string result = ""; + if (elementName != nullptr) + result = elementName->moduleName; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, result); +} + +void SecondAbility::GetHapModuleInfoCase3(int code) +{} + +void SecondAbility::GetCodeCacheDirCase1(int code) +{} +void SecondAbility::GetCodeCacheDirCase2(int code) +{ + string codeCacheDir = AbilityContext::GetCodeCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, codeCacheDir); +} +void SecondAbility::GetCodeCacheDirCase3(int code) +{} + +void SecondAbility::GetApplicationContextCase1(int code) +{} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..4a1d91d63012a653d2e041ef0c7b63be74cac51d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsKitSystemTestBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitSystemTestB\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsKitSystemTestB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + ] + configs = [ ":amsKitSystemTestBConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d872b36d3b8fceb55e7dc7e7bc2a80622c9eee88 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/config.json @@ -0,0 +1,43 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKitB", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.AmsKitSystemTestB.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..b68fb8b68e98a7f228740a8d63dd1791fd6ae511 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_KIT_SYSTEM_TEST_B_MAIN_ABILITY_H +#define AMS_KIT_SYSTEM_TEST_B_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + void GetApplicationInfoCase1(int code); + void GetApplicationInfoCase2(int code); + void GetApplicationInfoCase3(int code); + + void GetCacheDirCase1(int code); + void GetCacheDirCase2(int code); + void GetCacheDirCase3(int code); + + void GetDatabaseDirCase1(int code); + void GetDatabaseDirCase2(int code); + void GetDatabaseDirCase3(int code); + + void GetDataDirCase1(int code); + void GetDataDirCase2(int code); + void GetDataDirCase3(int code); + + void GetCodeCacheDirCase1(int code); + void GetCodeCacheDirCase2(int code); + void GetCodeCacheDirCase3(int code); + + void GetApplicationContextCase1(int code); + + void GetDirCase1(int code); + void GetDirCase2(int code); + void GetDirCase3(int code); + + void GetNoBackupFilesDirCase1(int code); + + void GetBundleManagerCase1(int code); + + void VerifyCallingPermissionCase1(int code); + + void VerifyPermissionCase1(int code); + + void VerifySelfPermissionCase1(int code); + + void GetBundleCodePathCase1(int code); + void GetBundleCodePathCase2(int code); + void GetBundleCodePathCase3(int code); + + void GetBundleNameCase1(int code); + void GetBundleNameCase2(int code); + void GetBundleNameCase3(int code); + + void GetBundleResourcePathCase1(int code); + void GetBundleResourcePathCase2(int code); + void GetBundleResourcePathCase3(int code); + + void CanRequestPermissionCase1(int code); + + void GetCallingAbilityCase1(int code); + void GetCallingAbilityCase2(int code); + void GetCallingAbilityCase3(int code); + + void GetContextCase1(int code); + + void GetAbilityManagerCase1(int code); + + void GetProcessInfoCase1(int code); + void GetProcessInfoCase2(int code); + void GetProcessInfoCase3(int code); + + void GetAppTypeCase1(int code); + void GetAppTypeCase2(int code); + void GetAppTypeCase3(int code); + + void GetCallingBundleCase1(int code); + void GetCallingBundleCase2(int code); + void GetCallingBundleCase3(int code); + + void StartAbilityCase1(int code); + void StartAbilityCase2(int code); + + void TerminateAbilityCase1(int code); + + void GetElementNameCase1(int code); + void GetElementNameCase2(int code); + void GetElementNameCase3(int code); + + void GetHapModuleInfoCase1(int code); + void GetHapModuleInfoCase2(int code); + void GetHapModuleInfoCase3(int code); + + MainAbility() + { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } + + void initCaseFirst() + { + std::unordered_map>> testCase = { + {(int)AbilityContextApi::GetApplicationInfo, + { + [this](int code) { GetApplicationInfoCase1(code); }, + [this](int code) { GetApplicationInfoCase2(code); }, + [this](int code) { GetApplicationInfoCase3(code); }, + }}, + {(int)AbilityContextApi::GetCacheDir, + { + [this](int code) { GetCacheDirCase1(code); }, + [this](int code) { GetCacheDirCase2(code); }, + [this](int code) { GetCacheDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetCodeCacheDir, + { + [this](int code) { GetCodeCacheDirCase1(code); }, + [this](int code) { GetCodeCacheDirCase2(code); }, + [this](int code) { GetCodeCacheDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetDatabaseDir, + { + [this](int code) { GetDatabaseDirCase1(code); }, + [this](int code) { GetDatabaseDirCase2(code); }, + [this](int code) { GetDatabaseDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetDataDir, + { + [this](int code) { GetDataDirCase1(code); }, + [this](int code) { GetDataDirCase2(code); }, + [this](int code) { GetDataDirCase3(code); }, + }}, + }; + mapCase_.insert(testCase.begin(), testCase.end()); + } + + void initCaseSecond() + { + std::unordered_map>> testCase = { + {(int)AbilityContextApi::GetDir, + { + [this](int code) { GetDirCase1(code); }, + [this](int code) { GetDirCase2(code); }, + [this](int code) { GetDirCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleManager, + { + [this](int code) { GetBundleManagerCase1(code); }, + }}, + {(int)AbilityContextApi::GetBundleCodePath, + { + [this](int code) { GetBundleCodePathCase1(code); }, + [this](int code) { GetBundleCodePathCase2(code); }, + [this](int code) { GetBundleCodePathCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleName, + { + [this](int code) { GetBundleNameCase1(code); }, + [this](int code) { GetBundleNameCase2(code); }, + [this](int code) { GetBundleNameCase3(code); }, + }}, + {(int)AbilityContextApi::GetBundleResourcePath, + { + [this](int code) { GetBundleResourcePathCase1(code); }, + [this](int code) { GetBundleResourcePathCase2(code); }, + [this](int code) { GetBundleResourcePathCase3(code); }, + }}, + {(int)AbilityContextApi::GetApplicationContext, + { + [this](int code) { GetApplicationContextCase1(code); }, + }}, + {(int)AbilityContextApi::GetCallingAbility, + { + [this](int code) { GetCallingAbilityCase1(code); }, + [this](int code) { GetCallingAbilityCase2(code); }, + [this](int code) { GetCallingAbilityCase3(code); }, + }}, + {(int)AbilityContextApi::GetContext, + { + [this](int code) { GetContextCase1(code); }, + }}, + }; + mapCase_.insert(testCase.begin(), testCase.end()); + } + + void initCaseThird() + { + std::unordered_map>> testCase = { + {(int)AbilityContextApi::GetAbilityManager, + { + [this](int code) { GetAbilityManagerCase1(code); }, + }}, + {(int)AbilityContextApi::GetProcessInfo, + { + [this](int code) { GetProcessInfoCase1(code); }, + [this](int code) { GetProcessInfoCase2(code); }, + [this](int code) { GetProcessInfoCase3(code); }, + }}, + {(int)AbilityContextApi::GetAppType, + { + [this](int code) { GetAppTypeCase1(code); }, + [this](int code) { GetAppTypeCase2(code); }, + [this](int code) { GetAppTypeCase3(code); }, + }}, + {(int)AbilityContextApi::GetCallingBundle, + { + [this](int code) { GetCallingBundleCase1(code); }, + [this](int code) { GetCallingBundleCase2(code); }, + [this](int code) { GetCallingBundleCase3(code); }, + }}, + {(int)AbilityContextApi::StartAbility_Want_int, + { + [this](int code) { StartAbilityCase1(code); }, + [this](int code) { StartAbilityCase2(code); }, + }}, + {(int)AbilityContextApi::TerminateAbility, + { + [this](int code) { TerminateAbilityCase1(code); }, + }}, + {(int)AbilityContextApi::GetElementName, + { + [this](int code) { GetElementNameCase1(code); }, + [this](int code) { GetElementNameCase2(code); }, + [this](int code) { GetElementNameCase3(code); }, + }}, + {(int)AbilityContextApi::GetHapModuleInfo, + { + [this](int code) { GetHapModuleInfoCase1(code); }, + [this](int code) { GetHapModuleInfoCase2(code); }, + [this](int code) { GetHapModuleInfoCase3(code); }, + }}, + }; + mapCase_.insert(testCase.begin(), testCase.end()); + } + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + ~MainAbility(); + std::unordered_map>> mapCase_; + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + virtual void OnBackPressed() override; + virtual void OnNewWant(const Want &want) override; + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Ability", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_KIT_SYSTEM_TEST_B_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c2411fd614d05c2998f280ec91b46e92bf1fd754 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp @@ -0,0 +1,476 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +const int MainAbilityBCode = 300; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MainAbilityBCode, "onStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MainAbilityBCode, "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MainAbilityBCode, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MainAbilityBCode, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MainAbilityBCode, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, MainAbilityBCode, "OnForeground"); +} + +void MainAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("MainAbility::OnAbilityResult"); + Ability::OnAbilityResult(requestCode, resultCode, resultData); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, 0, resultData.ToUri()); +} + +void MainAbility::OnBackPressed() +{ + APP_LOGI("MainAbility::OnBackPressed"); + Ability::OnBackPressed(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, 0, ""); +} + +void MainAbility::OnNewWant(const Want &want) +{ + APP_LOGI("MainAbility::OnNewWant"); + Ability::OnNewWant(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB_LIFECYCLE, 0, want.ToUri()); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIRSTB, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRSTB.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void MainAbility::GetApplicationInfoCase1(int code) +{ + return; +} +void MainAbility::GetApplicationInfoCase2(int code) +{ + return; +} +void MainAbility::GetApplicationInfoCase3(int code) +{ + auto appInfo = AbilityContext::GetApplicationInfo(); + string result = ""; + if (appInfo != nullptr) { + result = appInfo->name; + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, result); +} + +void MainAbility::GetCacheDirCase1(int code) +{ + return; +} +void MainAbility::GetCacheDirCase2(int code) +{ + return; +} +void MainAbility::GetCacheDirCase3(int code) +{ + string cacheDir = AbilityContext::GetCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, cacheDir); +} + +void MainAbility::GetDatabaseDirCase1(int code) +{ + return; +} +void MainAbility::GetDatabaseDirCase2(int code) +{ + return; +} +void MainAbility::GetDatabaseDirCase3(int code) +{ + string databaseDir = AbilityContext::GetDatabaseDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, databaseDir); +} + +void MainAbility::GetDataDirCase1(int code) +{ + return; +} + +void MainAbility::GetDataDirCase2(int code) +{ + return; +} + +void MainAbility::GetDataDirCase3(int code) +{ + string dataDir = AbilityContext::GetDataDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, dataDir); +} + +void MainAbility::GetDirCase1(int code) +{ + return; +} + +void MainAbility::GetDirCase2(int code) +{ + return; +} + +void MainAbility::GetDirCase3(int code) +{ + string name = "getDir"; + string dir = AbilityContext::GetDir(name, 0); + dir = AbilityContext::GetDir(name, 0); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, dir); +} + +void MainAbility::GetNoBackupFilesDirCase1(int code) +{ + return; +} + +void MainAbility::GetBundleManagerCase1(int code) +{ + return; +} + +void MainAbility::VerifyCallingPermissionCase1(int code) +{ + return; +} + +void MainAbility::VerifyPermissionCase1(int code) +{ + return; +} + +void MainAbility::VerifySelfPermissionCase1(int code) +{ + return; +} + +void MainAbility::GetBundleCodePathCase1(int code) +{ + return; +} + +void MainAbility::GetBundleCodePathCase2(int code) +{ + return; +} + +void MainAbility::GetBundleCodePathCase3(int code) +{ + string bundleCodePath = AbilityContext::GetBundleCodePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, bundleCodePath); +} + +void MainAbility::GetBundleNameCase1(int code) +{ + return; +} + +void MainAbility::GetBundleNameCase2(int code) +{ + return; +} + +void MainAbility::GetBundleNameCase3(int code) +{ + string bundleName = AbilityContext::GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, bundleName); + return; +} + +void MainAbility::GetBundleResourcePathCase1(int code) +{ + return; +} + +void MainAbility::GetBundleResourcePathCase2(int code) +{ + return; +} + +void MainAbility::GetBundleResourcePathCase3(int code) +{ + string bundleResourcePath = AbilityContext::GetBundleResourcePath(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, bundleResourcePath); +} + +void MainAbility::CanRequestPermissionCase1(int code) +{ + return; +} + +void MainAbility::GetCallingAbilityCase1(int code) +{ + return; +} + +void MainAbility::GetCallingAbilityCase2(int code) +{ + auto callingAbility = AbilityContext::GetCallingAbility(); + string result = ""; + if (callingAbility != nullptr) + result = callingAbility->GetURI(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, result); + return; +} + +void MainAbility::GetCallingAbilityCase3(int code) +{ + string targetBundle = "com.ohos.amsst.AppKitA"; + string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::GetContextCase1(int code) +{ + return; +} + +void MainAbility::GetAbilityManagerCase1(int code) +{ + return; +} + +void MainAbility::GetProcessInfoCase1(int code) +{ + return; +} + +void MainAbility::GetProcessInfoCase2(int code) +{ + return; +} + +void MainAbility::GetProcessInfoCase3(int code) +{ + auto processInfo = AbilityContext::GetProcessInfo(); + string result = ""; + if (processInfo != nullptr) { + result = processInfo->GetProcessName(); + } + + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, result); +} + +void MainAbility::GetAppTypeCase1(int code) +{ + return; +} + +void MainAbility::GetAppTypeCase2(int code) +{ + return; +} + +void MainAbility::GetAppTypeCase3(int code) +{ + string appType = AbilityContext::GetAppType(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, appType); +} + +void MainAbility::GetCallingBundleCase1(int code) +{ + return; +} + +void MainAbility::GetCallingBundleCase2(int code) +{ + string callingBundle = AbilityContext::GetCallingBundle(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, callingBundle); +} + +void MainAbility::GetCallingBundleCase3(int code) +{ + string targetBundle = "com.ohos.amsst.AppKitA"; + string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", 0); + StartAbility(want); +} + +void MainAbility::StartAbilityCase1(int code) +{ + return; +} + +void MainAbility::StartAbilityCase2(int code) +{ + return; +} + +void MainAbility::TerminateAbilityCase1(int code) +{ + return; +} + +void MainAbility::GetElementNameCase1(int code) +{ + return; +} + +void MainAbility::GetElementNameCase2(int code) +{ + return; +} + +void MainAbility::GetElementNameCase3(int code) +{ + auto elementName = AbilityContext::GetElementName(); + string result = ""; + if (elementName != nullptr) + result = elementName->GetBundleName(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, result); +} + +void MainAbility::GetHapModuleInfoCase1(int code) +{ + return; +} + +void MainAbility::GetHapModuleInfoCase2(int code) +{ + return; +} + +void MainAbility::GetHapModuleInfoCase3(int code) +{ + auto elementName = AbilityContext::GetHapModuleInfo(); + string result = ""; + if (elementName != nullptr) + result = elementName->moduleName; + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, result); +} + +void MainAbility::GetCodeCacheDirCase1(int code) +{} +void MainAbility::GetCodeCacheDirCase2(int code) +{} +void MainAbility::GetCodeCacheDirCase3(int code) +{ + string codeCacheDir = AbilityContext::GetCodeCacheDir(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRSTB, code, codeCacheDir); +} + +void MainAbility::GetApplicationContextCase1(int code) +{} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..c339cd2260814256d1803715d713defda0248fbc --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsKitSystemTestDataAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitDataSystemTestA\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsKitSystemTestDataA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_data_a1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_data_a2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_data_a3.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_page_a.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_service_a.cpp", + "${SUBST_TOOLS_DIR}/src/event.cpp", + "${SUBST_TOOLS_DIR}/src/stoperator.cpp", + ] + configs = [ ":amsKitSystemTestDataAConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3628b23967ee3b859221257232cb6c106c5c1979 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/config.json @@ -0,0 +1,85 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKitDataA", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.amsst.AppKitDataA.src", + "name":"AmsSystemTestDataA", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "AmsStKitDataAbilityPageA", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "PageA Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStKitDataAbilityServiceA", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "ServiceA Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "AmsStKitDataAbilityDataA1", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "DataA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppKitDataA.AmsStKitDataAbilityDataA1" + }, + { + "name": "AmsStKitDataAbilityDataA2", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "DataA2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppKitDataA.AmsStKitDataAbilityDataA2" + }, + { + "name": "AmsStKitDataAbilityDataA3", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "DataA3 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppKitDataA.AmsStKitDataAbilityDataA3" + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h new file mode 100644 index 0000000000000000000000000000000000000000..1d3595ffeac5f76aa3f168fa4f2ff52d3981fbc7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_DATA_A1_H +#define AMS_ST_KIT_DATA_ABILITY_DATA_A1_H +#include + +#include "ability.h" +#include "ability_lifecycle_callbacks.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; + +class KitTestDataA1EventSubscriber; +class AmsStKitDataAbilityDataA1 : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + FILE *fd1 = nullptr; + void TestLifeCycle(); + ~AmsStKitDataAbilityDataA1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnForeground(const Want &want) override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class AmsStKitDataAbilityDataA1LifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + AmsStKitDataAbilityDataA1LifecycleCallbacks() + { + mainAbility_ = nullptr; + }; + virtual ~AmsStKitDataAbilityDataA1LifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + AmsStKitDataAbilityDataA1 *mainAbility_; +}; + +class AmsStKitDataAbilityDataA1LifecycleObserver : public ILifecycleObserver { +public: + AmsStKitDataAbilityDataA1LifecycleObserver() = default; + virtual ~AmsStKitDataAbilityDataA1LifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; + AmsStKitDataAbilityDataA1 *mainAbility_; +}; + +class KitTestDataA1EventSubscriber : public CommonEventSubscriber { +public: + KitTestDataA1EventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityDataA1 *ability) + : CommonEventSubscriber(sp) + { + mainAbility_ = ability; + }; + + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStKitDataAbilityDataA1 *mainAbility_; + ~KitTestDataA1EventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_DATA_A1_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h new file mode 100644 index 0000000000000000000000000000000000000000..b00844a05ff9894a2f40786fd91c52f49002e9e5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_DATA_A2_H +#define AMS_ST_KIT_DATA_ABILITY_DATA_A2_H +#include + +#include "ability.h" +#include "ability_lifecycle_callbacks.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; + +class KitTestDataA2EventSubscriber; +class AmsStKitDataAbilityDataA2 : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + FILE *fd1 = nullptr; + void TestLifeCycle(); + ~AmsStKitDataAbilityDataA2(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnForeground(const Want &want) override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class AmsStKitDataAbilityDataA2LifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + AmsStKitDataAbilityDataA2LifecycleCallbacks() = default; + virtual ~AmsStKitDataAbilityDataA2LifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + AmsStKitDataAbilityDataA2 *mainAbility_; +}; + +class AmsStKitDataAbilityDataA2LifecycleObserver : public ILifecycleObserver { +public: + AmsStKitDataAbilityDataA2LifecycleObserver() = default; + virtual ~AmsStKitDataAbilityDataA2LifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; + AmsStKitDataAbilityDataA2 *mainAbility_; +}; + +class KitTestDataA2EventSubscriber : public CommonEventSubscriber { +public: + KitTestDataA2EventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityDataA2 *ability) + : CommonEventSubscriber(sp) + { + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStKitDataAbilityDataA2 *mainAbility_; + ~KitTestDataA2EventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_DATA_A2_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h new file mode 100644 index 0000000000000000000000000000000000000000..cf3e758729166c43c7531f32ce48470993e715b0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_DATA_A3_H +#define AMS_ST_KIT_DATA_ABILITY_DATA_A3_H +#include + +#include "ability.h" +#include "ability_lifecycle_callbacks.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; + +class KitTestDataA3EventSubscriber; +class AmsStKitDataAbilityDataA3 : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + FILE *fd1 = nullptr; + void TestLifeCycle(); + ~AmsStKitDataAbilityDataA3(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnForeground(const Want &want) override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class AmsStKitDataAbilityDataA3LifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + AmsStKitDataAbilityDataA3LifecycleCallbacks() = default; + virtual ~AmsStKitDataAbilityDataA3LifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + AmsStKitDataAbilityDataA3 *mainAbility_; +}; + +class AmsStKitDataAbilityDataA3LifecycleObserver : public ILifecycleObserver { +public: + AmsStKitDataAbilityDataA3LifecycleObserver() = default; + virtual ~AmsStKitDataAbilityDataA3LifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; + AmsStKitDataAbilityDataA3 *mainAbility_; +}; + +class KitTestDataA3EventSubscriber : public CommonEventSubscriber { +public: + explicit KitTestDataA3EventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mainAbility_ = nullptr; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStKitDataAbilityDataA3 *mainAbility_; + ~KitTestDataA3EventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_DATA_A3_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_page_a.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_page_a.h new file mode 100644 index 0000000000000000000000000000000000000000..a95d939024565cac7044e6c47ba73d07169e7ab4 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_page_a.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_PAGE_A_H +#define AMS_ST_KIT_DATA_ABILITY_PAGE_A_H +#include +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class KitTestPageAEventSubscriber; + +class AmsStKitDataAbilityPageA : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + ~AmsStKitDataAbilityPageA(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + +private: + void GetWantInfo(const Want &want); + + Want originWant_; + std::shared_ptr subscriber_; +}; + +class KitTestPageAEventSubscriber : public CommonEventSubscriber { +public: + KitTestPageAEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityPageA *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"OnStart", [this]() { TestPost("OnStart"); }}, + {"OnStop", [this]() { TestPost("OnStop"); }}, + {"OnActive", [this]() { TestPost("OnActive"); }}, + {"OnInactive", [this]() { TestPost("OnInactive"); }}, + {"OnBackground", [this]() { TestPost("OnBackground"); }}, + }; + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName); + std::vector vectorOperator_; + AmsStKitDataAbilityPageA *mainAbility_; + std::unordered_map> mapTestFunc_; + ~KitTestPageAEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_PAGE_A_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_service_a.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_service_a.h new file mode 100644 index 0000000000000000000000000000000000000000..f8405ab1ced2e84c465224e9226a480bf21fb01d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_service_a.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_SERVICE_A_H +#define AMS_ST_KIT_DATA_ABILITY_SERVICE_A_H +#include +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class KitTestServiceAEventSubscriber; + +class AmsStKitDataAbilityServiceA : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + ~AmsStKitDataAbilityServiceA(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void GetWantInfo(const Want &want); + + Want originWant_; + std::shared_ptr subscriber_; +}; + +class KitTestServiceAEventSubscriber : public CommonEventSubscriber { +public: + KitTestServiceAEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityServiceA *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"OnStart", [this]() { TestPost("OnStart"); }}, + {"OnStop", [this]() { TestPost("OnStop"); }}, + {"OnActive", [this]() { TestPost("OnActive"); }}, + {"OnInactive", [this]() { TestPost("OnInactive"); }}, + {"OnBackground", [this]() { TestPost("OnBackground"); }}, + }; + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName); + std::vector vectorOperator_; + AmsStKitDataAbilityServiceA *mainAbility_; + std::unordered_map> mapTestFunc_; + ~KitTestServiceAEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_SERVICE_A_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..298ad5f76c4f46a18a9941c0b35a36ec4d5f11bb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_data_a1.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_CODE = 250; +static const int LIFECYCLE_CALLBACKS = 251; +static const int LIFECYCLE_OBSERVER = 252; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +static const std::string OPERATOR_TEST_LIFECYCLE = "TestLifeCycle"; +static const std::string OPERATOR_GET_LIFECYCLE_STATE = "GetLifecycleState"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilityStart"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStart"); + } +} + +void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilityInactive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnInactive"); + } +} + +void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilityBackground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnBackground"); + } +} + +void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilityForeground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnForeground"); + } +} + +void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilityActive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnActive"); + } +} + +void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilityStop"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStop"); + } +} + +void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilitySaveState"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnSaveState"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnActive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnActive"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnBackground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnBackground"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnForeground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnForeground"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnInactive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnInactive"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnStart"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStart"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnStop"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStop"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +void AmsStKitDataAbilityDataA1LifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +bool AmsStKitDataAbilityDataA1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestDataA1EventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestDataA1EventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestDataA1EventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestDataA1EventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_CODE); + } +} + +void AmsStKitDataAbilityDataA1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStKitDataAbilityDataA1::Init called."); + Ability::Init(abilityInfo, application, handler, token); + auto callback = std::make_shared(); + callback->mainAbility_ = this; + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + auto observer = std::make_shared(); + observer->mainAbility_ = this; + Ability::GetLifecycle()->AddObserver(observer); +} + +AmsStKitDataAbilityDataA1::~AmsStKitDataAbilityDataA1() +{ + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataA1::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataA1::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA1 OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStart"); +} + +void AmsStKitDataAbilityDataA1::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataA1 OnStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStop"); +} + +void AmsStKitDataAbilityDataA1::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataA1 OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnActive"); +} + +void AmsStKitDataAbilityDataA1::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataA1 OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityDataA1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA1 OnForeground"); + Ability::OnForeground(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnForeground"); +} + +void AmsStKitDataAbilityDataA1::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataA1 OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnBackground"); +} + +void AmsStKitDataAbilityDataA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA1::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnNewWant"); +} + +int AmsStKitDataAbilityDataA1::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); + return DEFAULT_INSERT_RESULT; +} + +int AmsStKitDataAbilityDataA1::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStKitDataAbilityDataA1::Update( + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStKitDataAbilityDataA1::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock) { + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + } + return resultValue; +} + +std::vector AmsStKitDataAbilityDataA1::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); + std::vector fileType {"filetypes"}; + return fileType; +} + +int AmsStKitDataAbilityDataA1::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 == nullptr) + return -1; + int fd = fileno(fd1); + APP_LOGI("AmsStKitDataAbilityDataA1 fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OpenFile"); + return fd; +} + +void AmsStKitDataAbilityDataA1::TestLifeCycle() +{ + APP_LOGI("AmsStKitDataAbilityDataA1::TestLifeCycle"); + // ability_lifecycle.h + auto lifecycle = Ability::GetLifecycle(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetLifecycle"); + Want want; + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_START, want); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND, want); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND, want); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_STOP); +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityDataA1 &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } else if (child->GetOperatorName() == OPERATOR_TEST_LIFECYCLE) { + mainAbility.TestLifeCycle(); + result = OPERATOR_TEST_LIFECYCLE; + } else if (child->GetOperatorName() == OPERATOR_GET_LIFECYCLE_STATE) { + auto lifecycle = mainAbility.GetLifecycle(); + auto state = lifecycle->GetLifecycleState(); + result = (state != LifeCycle::Event::UNDEFINED) ? OPERATOR_GET_LIFECYCLE_STATE : "UNDEFINED"; + } +} + +void KitTestDataA1EventSubscriber::TestPost(const std::string funName) +{ + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityDataA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78538dfb51197ccb8854913553dbea468c9dd773 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_data_a2.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_CODE = 260; +static const int LIFECYCLE_CALLBACKS = 261; +static const int LIFECYCLE_OBSERVER = 262; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleCallbacks OnAbilityStart"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStart"); + } +} + +void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleCallbacks OnAbilityInactive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnInactive"); + } +} + +void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleCallbacks OnAbilityBackground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnBackground"); + } +} + +void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleCallbacks OnAbilityForeground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnForeground"); + } +} + +void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleCallbacks OnAbilityActive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnActive"); + } +} + +void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleCallbacks OnAbilityStop"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStop"); + } +} + +void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleCallbacks OnAbilitySaveState"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnSaveState"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnActive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnActive"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnBackground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnBackground"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnForeground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnForeground"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnInactive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnInactive"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnStart"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStart"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnStop"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStop"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +void AmsStKitDataAbilityDataA2LifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + APP_LOGI("AmsStKitDataAbilityDataA2LifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +bool AmsStKitDataAbilityDataA2::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestDataA2EventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestDataA2EventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestDataA2EventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestDataA2EventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_CODE); + } +} + +void AmsStKitDataAbilityDataA2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStKitDataAbilityDataA2::Init called."); + Ability::Init(abilityInfo, application, handler, token); + auto callback = std::make_shared(); + callback->mainAbility_ = this; + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + auto observer = std::make_shared(); + observer->mainAbility_ = this; + Ability::GetLifecycle()->AddObserver(observer); +} + +AmsStKitDataAbilityDataA2::~AmsStKitDataAbilityDataA2() +{ + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataA2::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataA2::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA2 OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStart"); +} + +void AmsStKitDataAbilityDataA2::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataA2 OnStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStop"); +} + +void AmsStKitDataAbilityDataA2::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataA2 OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnActive"); +} + +void AmsStKitDataAbilityDataA2::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataA2 OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityDataA2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA2 OnForeground"); + Ability::OnForeground(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnForeground"); +} + +void AmsStKitDataAbilityDataA2::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataA2 OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnBackground"); +} + +void AmsStKitDataAbilityDataA2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA2::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnNewWant"); +} + +int AmsStKitDataAbilityDataA2::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); + return DEFAULT_INSERT_RESULT; +} + +int AmsStKitDataAbilityDataA2::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStKitDataAbilityDataA2::Update( + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStKitDataAbilityDataA2::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock) { + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + } + return resultValue; +} + +std::vector AmsStKitDataAbilityDataA2::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); + std::vector fileType {"filetypes"}; + return fileType; +} + +int AmsStKitDataAbilityDataA2::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 == nullptr) + return -1; + int fd = fileno(fd1); + APP_LOGI("AmsStKitDataAbilityDataA2 fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OpenFile"); + + return fd; +} + +void AmsStKitDataAbilityDataA2::TestLifeCycle() +{ + APP_LOGI("AmsStKitDataAbilityDataA2::TestLifeCycle"); + // ability_lifecycle.h + auto lifecycle = Ability::GetLifecycle(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetLifecycle"); + Want want; + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_START, want); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND, want); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_STOP); + // valueOf + // values +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityDataA2 &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } +} + +void KitTestDataA2EventSubscriber::TestPost(const std::string funName) +{ + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityDataA2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..737e21bb36ea6ce04bfe8966886e17554e5b9e05 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp @@ -0,0 +1,427 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_data_a3.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_CODE = 290; +static const int LIFECYCLE_CALLBACKS = 291; +static const int LIFECYCLE_OBSERVER = 292; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleCallbacks OnAbilityStart"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStart"); + } +} + +void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleCallbacks OnAbilityInactive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnInactive"); + } +} + +void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleCallbacks OnAbilityBackground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnBackground"); + } +} + +void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleCallbacks OnAbilityForeground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnForeground"); + } +} + +void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleCallbacks OnAbilityActive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnActive"); + } +} + +void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleCallbacks OnAbilityStop"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStop"); + } +} + +void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleCallbacks OnAbilitySaveState"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnSaveState"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnActive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnActive"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnBackground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnBackground"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnForeground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnForeground"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnInactive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnInactive"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnStart"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStart"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnStop"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStop"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +void AmsStKitDataAbilityDataA3LifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + APP_LOGI("AmsStKitDataAbilityDataA3LifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +bool AmsStKitDataAbilityDataA3::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestDataA3EventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestDataA3EventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestDataA3EventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestDataA3EventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_CODE); + } +} + +void AmsStKitDataAbilityDataA3::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStKitDataAbilityDataA3::Init called."); + Ability::Init(abilityInfo, application, handler, token); + auto callback = std::make_shared(); + callback->mainAbility_ = this; + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + auto observer = std::make_shared(); + observer->mainAbility_ = this; + Ability::GetLifecycle()->AddObserver(observer); + Ability::GetLifecycle()->RemoveObserver(observer); +} + +AmsStKitDataAbilityDataA3::~AmsStKitDataAbilityDataA3() +{ + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataA3::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataA3::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA3 OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStart"); +} + +void AmsStKitDataAbilityDataA3::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataA3 OnStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStop"); +} + +void AmsStKitDataAbilityDataA3::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataA3 OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnActive"); +} + +void AmsStKitDataAbilityDataA3::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataA3 OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityDataA3::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA3 OnForeground"); + Ability::OnForeground(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnForeground"); +} + +void AmsStKitDataAbilityDataA3::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataA3 OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnBackground"); +} + +void AmsStKitDataAbilityDataA3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataA3::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnNewWant"); +} + +int AmsStKitDataAbilityDataA3::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); + return DEFAULT_INSERT_RESULT; +} + +int AmsStKitDataAbilityDataA3::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStKitDataAbilityDataA3::Update( + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStKitDataAbilityDataA3::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock) { + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + } + return resultValue; +} + +std::vector AmsStKitDataAbilityDataA3::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); + std::vector fileType {"filetypes"}; + return fileType; +} + +int AmsStKitDataAbilityDataA3::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 == nullptr) + return -1; + int fd = fileno(fd1); + APP_LOGI("AmsStKitDataAbilityDataA3 fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OpenFile"); + + return fd; +} + +void AmsStKitDataAbilityDataA3::TestLifeCycle() +{ + APP_LOGI("AmsStKitDataAbilityDataA3::TestLifeCycle"); + // ability_lifecycle.h + auto lifecycle = Ability::GetLifecycle(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetLifecycle"); + Want want; + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_START, want); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND, want); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_STOP); + // valueOf + // values +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityDataA3 &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } +} + +void KitTestDataA3EventSubscriber::TestPost(const std::string funName) +{ + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityDataA3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9f65930b97aae8c5b398cd996f358df46056e14 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_page_a.h" + +#include +#include +#include + +#include "abs_shared_result_set.h" +#include "app_log_wrapper.h" +#include "data_ability_helper.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_PAGE_CODE = 130; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} + +bool AmsStKitDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestPageAEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestPageAEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestPageAEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestPageAEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare("event_data_test_action") == 0 && ABILITY_PAGE_CODE == data.GetCode()) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +AmsStKitDataAbilityPageA::~AmsStKitDataAbilityPageA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityPageA::SubscribeEvent(const Want &want) +{ + Want mwant {want}; + std::vector eventList = { + "event_data_test_action", + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + subscriber_->vectorOperator_ = mwant.GetStringArrayParam("operator"); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityPageA::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityPageA::onStart"); + originWant_ = want; + SubscribeEvent(want); + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "onStart"); +} + +void AmsStKitDataAbilityPageA::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityPageA::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); +} + +void AmsStKitDataAbilityPageA::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityPageA::onStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnStop"); +} + +void AmsStKitDataAbilityPageA::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityPageA::OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnActive"); +} + +void AmsStKitDataAbilityPageA::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityPageA::OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityPageA::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityPageA::OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnBackground"); +} + +void AmsStKitDataAbilityPageA::GetWantInfo(const Want &want) +{ + Want mWant(want); + STtools::StOperator allOperator {}; + std::vector vectorOperator = mWant.GetStringArrayParam("operator"); + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); + + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityPageA &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } +} + +void KitTestPageAEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("KitTestPageAEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == "2") { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == "0") { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityPageA); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..864903fef30039337fd8db17259c798008cce278 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_service_a.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_SERVICE_CODE = 310; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} + +bool AmsStKitDataAbilityServiceA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestServiceAEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestServiceAEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestServiceAEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestServiceAEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare("event_data_test_action") == 0 && ABILITY_SERVICE_CODE == data.GetCode()) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +AmsStKitDataAbilityServiceA::~AmsStKitDataAbilityServiceA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityServiceA::SubscribeEvent(const Want &want) +{ + Want mwant {want}; + std::vector eventList = { + "event_data_test_action", + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + subscriber_->vectorOperator_ = mwant.GetStringArrayParam("operator"); + subscriber_->mainAbility_ = this; + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityServiceA::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityServiceA::onStart"); + originWant_ = want; + SubscribeEvent(want); + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "onStart"); +} + +void AmsStKitDataAbilityServiceA::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityServiceA::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); +} + +void AmsStKitDataAbilityServiceA::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityServiceA::onStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnStop"); +} + +void AmsStKitDataAbilityServiceA::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityServiceA::OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnActive"); +} + +void AmsStKitDataAbilityServiceA::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityServiceA::OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityServiceA::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityServiceA::OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnBackground"); +} + +void AmsStKitDataAbilityServiceA::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityA1::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnCommand"); +} + +sptr AmsStKitDataAbilityServiceA::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnConnect"); + + sptr ret = Ability::OnConnect(want); + PublishEvent(abilityEventName, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnConnect"); + return ret; +} +void AmsStKitDataAbilityServiceA::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(abilityEventName, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} + +void AmsStKitDataAbilityServiceA::GetWantInfo(const Want &want) +{ + Want mWant(want); + STtools::StOperator allOperator {}; + std::vector vectorOperator = mWant.GetStringArrayParam("operator"); + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); + + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityServiceA &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } +} + +void KitTestServiceAEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == "2") { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == "0") { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityServiceA); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..8539bbdcc90676dcddf74a9ce97ae187351b95ed --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsKitSystemTestDataBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitDataSystemTestB\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsKitSystemTestDataB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_data_b.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_page_b.cpp", + "${SUBDEMOSYSTEM_DIR}/src/ams_st_kit_data_ability_service_b.cpp", + "${SUBST_TOOLS_DIR}/src/event.cpp", + "${SUBST_TOOLS_DIR}/src/stoperator.cpp", + ] + configs = [ ":amsKitSystemTestDataBConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f6083e0bd79df69f67bb6484ccc320113e6c5e3c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/config.json @@ -0,0 +1,64 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKitDataB", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.amsst.AppKitDataB.src", + "name":"AmsSystemTestDataA", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "AmsStKitDataAbilityPageB", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "PageB Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStKitDataAbilityServiceB", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "ServiceB Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "AmsStKitDataAbilityDataB", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "DataB Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "visible": true, + "uri": "dataability://com.ohos.amsst.AppKitDataB.AmsStKitDataAbilityDataB" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h new file mode 100644 index 0000000000000000000000000000000000000000..8ce2ea8a7058630207b0e5f6859036d060c1cc13 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_DATA_B_H +#define AMS_ST_KIT_DATA_ABILITY_DATA_B_H +#include + +#include "ability.h" +#include "ability_lifecycle_callbacks.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; + +class KitTestDataBEventSubscriber; +class AmsStKitDataAbilityDataB : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + STtools::Event event; + FILE *fd1 = nullptr; + ~AmsStKitDataAbilityDataB(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnForeground(const Want &want) override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + Want originWant_; + std::shared_ptr subscriber_; +}; + +class AmsStKitDataAbilityDataBLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + AmsStKitDataAbilityDataBLifecycleCallbacks() = default; + virtual ~AmsStKitDataAbilityDataBLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + AmsStKitDataAbilityDataB *mainAbility_; +}; + +class AmsStKitDataAbilityDataBLifecycleObserver : public ILifecycleObserver { +public: + AmsStKitDataAbilityDataBLifecycleObserver() = default; + virtual ~AmsStKitDataAbilityDataBLifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; + AmsStKitDataAbilityDataB *mainAbility_; +}; + +class KitTestDataBEventSubscriber : public CommonEventSubscriber { +public: + KitTestDataBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityDataB *ability) + : CommonEventSubscriber(sp) + { + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName = ""); + std::vector vectorOperator_; + AmsStKitDataAbilityDataB *mainAbility_; + ~KitTestDataBEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_DATA_B_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h new file mode 100644 index 0000000000000000000000000000000000000000..d52b7ef6ce72247748f3b459600f90106a3fed2c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_PAGE_B_H +#define AMS_ST_KIT_DATA_ABILITY_PAGE_B_H +#include +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class KitTestPageBEventSubscriber; + +class AmsStKitDataAbilityPageB : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + ~AmsStKitDataAbilityPageB(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + +private: + void GetWantInfo(const Want &want); + + Want originWant_; + std::shared_ptr subscriber_; +}; + +class KitTestPageBEventSubscriber : public CommonEventSubscriber { +public: + KitTestPageBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityPageB *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"OnStart", [this]() { TestPost("OnStart"); }}, + {"OnStop", [this]() { TestPost("OnStop"); }}, + {"OnActive", [this]() { TestPost("OnActive"); }}, + {"OnInactive", [this]() { TestPost("OnInactive"); }}, + {"OnBackground", [this]() { TestPost("OnBackground"); }} + }; + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName); + std::vector vectorOperator_; + AmsStKitDataAbilityPageB *mainAbility_; + std::unordered_map> mapTestFunc_; + ~KitTestPageBEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_PAGE_B_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_service_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_service_b.h new file mode 100644 index 0000000000000000000000000000000000000000..0021c69800665ccad96296c6a8ba5963a8cde6bc --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_service_b.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_KIT_DATA_ABILITY_SERVICE_B_H +#define AMS_ST_KIT_DATA_ABILITY_SERVICE_B_H +#include +#include + +#include "ability.h" +#include "ability_loader.h" +#include "common_event_manager.h" +#include "event.h" +#include "skills.h" +#include "stoperator.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +const std::string abilityEventName = "event_data_ability_callback"; +const std::string testEventName = "event_data_test_action"; +class KitTestServiceBEventSubscriber; + +class AmsStKitDataAbilityServiceB : public Ability { +public: + void SubscribeEvent(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + ~AmsStKitDataAbilityServiceB(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void GetWantInfo(const Want &want); + + Want originWant_; + std::shared_ptr subscriber_; +}; + +class KitTestServiceBEventSubscriber : public CommonEventSubscriber { +public: + KitTestServiceBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityServiceB *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = {{"OnStart", [this]() { TestPost("OnStart"); }}, + {"OnStop", [this]() { TestPost("OnStop"); }}, + {"OnActive", [this]() { TestPost("OnActive"); }}, + {"OnInactive", [this]() { TestPost("OnInactive"); }}, + {"OnBackground", [this]() { TestPost("OnBackground"); }}}; + mainAbility_ = ability; + }; + virtual void OnReceiveEvent(const CommonEventData &data); + + void TestPost(const std::string funName); + std::vector vectorOperator_; + AmsStKitDataAbilityServiceB *mainAbility_; + std::unordered_map> mapTestFunc_; + ~KitTestServiceBEventSubscriber(){}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_KIT_DATA_ABILITY_SERVICE_B_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af63a275ec7625fc7b4dd156a133c7aa36042636 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp @@ -0,0 +1,411 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_data_b.h" + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_DATA_CODE = 270; +static const int LIFECYCLE_CALLBACKS = 271; +static const int LIFECYCLE_OBSERVER = 272; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +static const int DEFAULT_INSERT_RESULT = 1111; +static const int DEFAULT_DELETE_RESULT = 2222; +static const int DEFAULT_UPDATE_RESULT = 3333; +static const std::string ABILITY_TYPE_PAGE = "0"; +static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} + +void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleCallbacks OnAbilityStart"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStart"); + } +} + +void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleCallbacks OnAbilityInactive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnInactive"); + } +} + +void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleCallbacks OnAbilityBackground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnBackground"); + } +} + +void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataA1LifecycleCallbacks OnAbilityForeground"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnForeground"); + } +} + +void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleCallbacks OnAbilityActive"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnActive"); + } +} + +void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleCallbacks OnAbilityStop"); + std::string abilityName = ability->GetAbilityName(); + if (abilityName == mainAbility_->GetAbilityName()) { + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnStop"); + } +} + +void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleCallbacks OnAbilitySaveState"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_CALLBACKS, "OnSaveState"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnActive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnActive"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnBackground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnBackground"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnForeground"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnForeground"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnInactive"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnInactive"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnStart"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStart"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnStop"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStop"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +void AmsStKitDataAbilityDataBLifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + APP_LOGI("AmsStKitDataAbilityDataBLifecycleObserver OnStateChanged"); + mainAbility_->PublishEvent(abilityEventName, LIFECYCLE_OBSERVER, "OnStateChanged"); +} + +bool AmsStKitDataAbilityDataB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestDataBEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestDataBEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestDataBEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestDataBEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare(testEventName) == 0 && ABILITY_DATA_CODE == data.GetCode()) { + std::string target = data.GetData(); + STtools::Completed(mainAbility_->event, target, ABILITY_DATA_CODE); + } +} + +void AmsStKitDataAbilityDataB::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStKitDataAbilityDataB::Init called."); + Ability::Init(abilityInfo, application, handler, token); + auto callback = std::make_shared(); + callback->mainAbility_ = this; + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + auto observer = std::make_shared(); + observer->mainAbility_ = this; + Ability::GetLifecycle()->AddObserver(observer); +} + +AmsStKitDataAbilityDataB::~AmsStKitDataAbilityDataB() +{ + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataB::SubscribeEvent(const Want &want) +{ + std::vector eventList = { + testEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityDataB::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataB OnStart"); + SubscribeEvent(want); + originWant_ = want; + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStart"); +} + +void AmsStKitDataAbilityDataB::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityDataB OnStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnStop"); +} + +void AmsStKitDataAbilityDataB::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityDataB OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnActive"); +} + +void AmsStKitDataAbilityDataB::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityDataB OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityDataB::OnForeground(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataB OnForeground"); + Ability::OnForeground(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnForeground"); +} + +void AmsStKitDataAbilityDataB::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityDataB::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnNewWant"); +} + +void AmsStKitDataAbilityDataB::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityDataB OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnBackground"); +} + +int AmsStKitDataAbilityDataB::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); + return DEFAULT_INSERT_RESULT; +} + +int AmsStKitDataAbilityDataB::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); + return DEFAULT_DELETE_RESULT; +} + +int AmsStKitDataAbilityDataB::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); + return DEFAULT_UPDATE_RESULT; +} + +std::shared_ptr AmsStKitDataAbilityDataB::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + subscriber_->vectorOperator_ = columns; + APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, OPERATOR_QUERY); + + STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); + subscriber_->TestPost(); + + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + if (pSharedBlock) { + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); + } + return resultValue; +} + +std::vector AmsStKitDataAbilityDataB::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); + std::vector fileType {"filetypes"}; + return fileType; +} + +int AmsStKitDataAbilityDataB::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 == nullptr) + return -1; + int fd = fileno(fd1); + APP_LOGI("AmsStKitDataAbilityDataB fd: %{public}d", fd); + PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OpenFile"); + + return fd; +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityDataB &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } +} + +void KitTestDataBEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("KitTestDataBEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == ABILITY_TYPE_DATA) { + APP_LOGI("---------------------targetAbility_--------------------"); + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == ABILITY_TYPE_PAGE) { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityDataB); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76a5fd0f1a425667e85503224665856f53f4a3b1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_page_b.h" + +#include +#include +#include + +#include "data_ability_helper.h" +#include "app_log_wrapper.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_PAGE_CODE = 140; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} + +bool AmsStKitDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestPageBEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestPageBEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestPageBEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestPageBEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare("event_data_test_action") == 0 && ABILITY_PAGE_CODE == data.GetCode()) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +AmsStKitDataAbilityPageB::~AmsStKitDataAbilityPageB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityPageB::SubscribeEvent(const Want &want) +{ + Want mwant {want}; + std::vector eventList = { + "event_data_test_action", + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + subscriber_->vectorOperator_ = mwant.GetStringArrayParam("operator"); + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityPageB::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityPageB::onStart"); + originWant_ = want; + SubscribeEvent(want); + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "onStart"); +} + +void AmsStKitDataAbilityPageB::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityPageB::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); +} + +void AmsStKitDataAbilityPageB::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityPageB::onStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnStop"); +} + +void AmsStKitDataAbilityPageB::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityPageB::OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnActive"); +} + +void AmsStKitDataAbilityPageB::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityPageB::OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityPageB::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityPageB::OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_PAGE_CODE, "OnBackground"); +} + +void AmsStKitDataAbilityPageB::GetWantInfo(const Want &want) +{ + Want mWant(want); + STtools::StOperator allOperator {}; + std::vector vectorOperator = mWant.GetStringArrayParam("operator"); + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); + + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityPageB &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } +} + +void KitTestPageBEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("KitTestPageBEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == "2") { + APP_LOGI("---------------------targetAbility_--------------------"); + + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == "0") { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_PAGE_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityPageB); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce7942848d12497bb5b5b1750091170e2ed73603 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_kit_data_ability_service_b.h" + +#include +#include +#include + +#include "data_ability_helper.h" +#include "app_log_wrapper.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static const int ABILITY_SERVICE_CODE = 320; +static const std::string OPERATOR_INSERT = "Insert"; +static const std::string OPERATOR_DELETE = "Delete"; +static const std::string OPERATOR_UPDATE = "Update"; +static const std::string OPERATOR_QUERY = "Query"; +static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} + +bool AmsStKitDataAbilityServiceB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void KitTestServiceBEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestServiceBEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestServiceBEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestServiceBEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (eventName.compare("event_data_test_action") == 0 && ABILITY_SERVICE_CODE == data.GetCode()) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +AmsStKitDataAbilityServiceB::~AmsStKitDataAbilityServiceB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityServiceB::SubscribeEvent(const Want &want) +{ + Want mwant {want}; + std::vector eventList = { + "event_data_test_action", + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, this); + subscriber_->vectorOperator_ = mwant.GetStringArrayParam("operator"); + subscriber_->mainAbility_ = this; + + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStKitDataAbilityServiceB::OnStart(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityServiceB::onStart"); + originWant_ = want; + SubscribeEvent(want); + Ability::OnStart(want); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "onStart"); +} + +void AmsStKitDataAbilityServiceB::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityServiceB::OnNewWant"); + originWant_ = want; + Ability::OnNewWant(want); +} + +void AmsStKitDataAbilityServiceB::OnStop() +{ + APP_LOGI("AmsStKitDataAbilityServiceB::onStop"); + Ability::OnStop(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnStop"); +} + +void AmsStKitDataAbilityServiceB::OnActive() +{ + APP_LOGI("AmsStKitDataAbilityServiceB::OnActive"); + Ability::OnActive(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnActive"); +} + +void AmsStKitDataAbilityServiceB::OnInactive() +{ + APP_LOGI("AmsStKitDataAbilityServiceB::OnInactive"); + Ability::OnInactive(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnInactive"); +} + +void AmsStKitDataAbilityServiceB::OnBackground() +{ + APP_LOGI("AmsStKitDataAbilityServiceB::OnBackground"); + Ability::OnBackground(); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnBackground"); +} + +void AmsStKitDataAbilityServiceB::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStKitDataAbilityServiceB::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, "OnCommand"); +} + +sptr AmsStKitDataAbilityServiceB::OnConnect(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityServiceB::OnConnect"); + + sptr ret = Ability::OnConnect(want); + PublishEvent(abilityEventName, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnConnect"); + return ret; +} +void AmsStKitDataAbilityServiceB::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStKitDataAbilityServiceB::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(abilityEventName, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} + +void AmsStKitDataAbilityServiceB::GetWantInfo(const Want &want) +{ + Want mWant(want); + STtools::StOperator allOperator {}; + std::vector vectorOperator = mWant.GetStringArrayParam("operator"); + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); + + for (auto child : allOperator.GetChildOperator()) { + APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); + APP_LOGI("-----------------targetAbility:%{public}s", child->GetAbilityName().c_str()); + APP_LOGI("-----------------targetAbilityType:%{public}s", child->GetAbilityType().c_str()); + APP_LOGI("-----------------operatorName:%{public}s", child->GetOperatorName().c_str()); + APP_LOGI("-----------------childOperatorNum:%{public}zu", child->GetChildOperator().size()); + } +} + +static void GetResult(std::shared_ptr child, std::shared_ptr helper, + AmsStKitDataAbilityServiceB &mainAbility, Uri dataAbilityUri, string &result) +{ + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + result = "failed"; + if (child->GetOperatorName() == OPERATOR_INSERT) { + result = std::to_string(helper->Insert(dataAbilityUri, bucket)); + } else if (child->GetOperatorName() == OPERATOR_DELETE) { + result = std::to_string(helper->Delete(dataAbilityUri, predicates)); + } else if (child->GetOperatorName() == OPERATOR_UPDATE) { + result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); + } else if (child->GetOperatorName() == OPERATOR_QUERY) { + std::vector columns = STtools::SerializationStOperatorToVector(*child); + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = OPERATOR_QUERY; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } + } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { + std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); + result = (types.size() > 0) ? types[0] : "failed"; + } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { + int fd = helper->OpenFile(dataAbilityUri, child->GetMessage()); + if (fd < 0) { + return; + } + FILE *file = fdopen(fd, "r"); + if (file == nullptr) { + return; + } + result = std::to_string(fd); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } + result = str; + fclose(file); + } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { + result = helper->GetType(dataAbilityUri); + result = (result != "") ? OPERATOR_GETTYPE : result; + } +} + +void KitTestServiceBEventSubscriber::TestPost(const std::string funName) +{ + APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); + STtools::StOperator allOperator {}; + STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); + std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); + for (auto child : allOperator.GetChildOperator()) { + /// data ability + if (child->GetAbilityType() == "2") { + APP_LOGI("---------------------targetAbility_--------------------"); + + Uri dataAbilityUri("dataability:///" + child->GetBundleName() + "." + child->GetAbilityName()); + std::string result; + if (helper != nullptr) { + APP_LOGI("---------------------helper--------------------"); + GetResult(child, helper, *mainAbility_, dataAbilityUri, result); + } + mainAbility_->PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, child->GetOperatorName() + " " + result); + } else if (child->GetAbilityType() == "0") { + APP_LOGI("---------------------StartPageAbility--------------------"); + std::vector vectoroperator; + if (child->GetChildOperator().size() != 0) { + vectoroperator = STtools::SerializationStOperatorToVector(*child); + } + std::string targetBundle = child->GetBundleName(); + std::string targetAbility = child->GetAbilityName(); + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("operator", vectoroperator); + mainAbility_->StartAbility(want); + mainAbility_->PublishEvent(abilityEventName, ABILITY_SERVICE_CODE, child->GetOperatorName()); + } + } +} +REGISTER_AA(AmsStKitDataAbilityServiceB); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..5467877ffe04f3a3fc1c8d809f30a7c9dfb5e93b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsKitSystemTestPageA" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitSystemTestPageA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsKitSystemTestPageA") { + sources = [ + "${subdemosystem_path}/src/ability_ability.cpp", + "${subdemosystem_path}/src/ability_context_ability.cpp", + "${subdemosystem_path}/src/ability_life_cycle_ability.cpp", + "${subdemosystem_path}/src/base_ability.cpp", + "${subdemosystem_path}/src/life_cycle_call_backs_ability.cpp", + "${subdemosystem_path}/src/life_cycle_observer_ability.cpp", + "${subdemosystem_path}/src/test_utils.cpp", + ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "${libs_path}/libeventhandler:libeventhandler_target", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e140e853fe24b71e88cd1d71669ec871b1faeb5f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/config.json @@ -0,0 +1,83 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.page.AppKitA", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsKitSystemTestPageA.src", + "name":"AmsKitSystemTestPageA", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "LifecycleCallbacksAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "LifecycleCallbacksAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AbilityContextAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityContextAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AbilityAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AbilityLifeCycleAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "LifeCycleObserverAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + } + ] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..718947b23185185e16edccb4cb22e552b489e69e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_ABILITY_H_ +#define ABILITY_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class AbilityConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t AbilityConnectCallback::onAbilityConnectDoneCount = 0; + +class AbilityAbilityEventSubscriber; +class AbilityAbility : public BaseAbility { +public: + ~AbilityAbility(); + + static std::string sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + void TestStartAbilityWithSetting(); + void TestStartAbilityForResult(); + + void TestAbilityStartAbility(); + void TestAbilityConnectAbility(); + void TestAbilityStopAbility(); + void TestAbilityGetLifecycle(); + void TestAbilityDisconnectAbility(); + + bool SubscribeEvent(); + void DoTestCase(); + void StopSelfAbility(); + void caseIndexOne(); + void caseIndexTwo(); +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + +private: + Want want_ = {}; + sptr stub_ = {}; + sptr connCallback_ = {}; + std::shared_ptr subscriber_ = {}; +}; +std::string AbilityAbility::sequenceNumber_ = "0"; + +class AbilityAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + AbilityAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + {"StartAbilityWithSetting", [this]() { TestStartAbilityWithSetting(); }}, + {"StartAbilityForResult", [this]() { TestStartAbilityForResult(); }}, + + {"AbilityStartAbility", [this]() { TestAbilityStartAbility(); }}, + {"AbilityConnectAbility", [this]() { TestAbilityConnectAbility(); }}, + {"AbilityStopAbility", [this]() { TestAbilityStopAbility(); }}, + {"AbilityGetLifecycle", [this]() { TestAbilityGetLifecycle(); }}, + {"AbilityDisconnectAbility", [this]() { TestAbilityDisconnectAbility(); }}, + {"StopSelfAbility", [this]() { StopSelfAbility(); }}, + }; + } + ~AbilityAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + void TestAbilityStartAbility() + { + mainAbility.TestAbilityStartAbility(); + } + + void TestStartAbilityWithSetting() + { + mainAbility.TestStartAbilityWithSetting(); + } + + void TestStartAbilityForResult() + { + mainAbility.TestStartAbilityForResult(); + } + + void TestAbilityConnectAbility() + { + mainAbility.TestAbilityConnectAbility(); + } + + void TestAbilityStopAbility() + { + mainAbility.TestAbilityStopAbility(); + } + + void TestAbilityGetLifecycle() + { + mainAbility.TestAbilityGetLifecycle(); + } + + void TestAbilityDisconnectAbility() + { + mainAbility.TestAbilityDisconnectAbility(); + } + + void StopSelfAbility() + { + mainAbility.StopSelfAbility(); + } + + Want want = {}; + AbilityAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_context_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_context_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..6e15588d73a574a7077e91cda4969d3a4bd9d5c0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_context_ability.h @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_CONTEXT_ABILITY_H_ +#define ABILITY_CONTEXT_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class AbilityContextConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t AbilityContextConnectCallback::onAbilityConnectDoneCount = 0; + +class AbilityContextAbilityEventSubscriber; +class AbilityContextAbility : public BaseAbility { +public: + ~AbilityContextAbility(); + static int sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + + bool SubscribeEvent(); + +private: + Want want_ = {}; + sptr stub_ = {}; + sptr connCallback_ = {}; + std::shared_ptr subscriber_ = {}; +}; +int AbilityContextAbility::sequenceNumber_ = 0; + +class AbilityContextAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + AbilityContextAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + }; + } + ~AbilityContextAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + Want want = {}; + AbilityContextAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_CONTEXT_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_life_cycle_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_life_cycle_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..801a2b2ddffbfdc4464e2ae328bef6305602188a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_life_cycle_ability.h @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_LIFE_CYCLE_ABILITY_H_ +#define ABILITY_LIFE_CYCLE_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class AbilityLifeCycleConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t AbilityLifeCycleConnectCallback::onAbilityConnectDoneCount = 0; +class AbilityLifeCycleAbilityEventSubscriber; + +class AbilityLifecycleLifecycleObserver : public ILifecycleObserver { +public: + AbilityLifecycleLifecycleObserver() = default; + virtual ~AbilityLifecycleLifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; +}; + +class AbilityLifeCycleAbility : public BaseAbility { +public: + ~AbilityLifeCycleAbility(); + static int sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + + void TestLifeCycleGetLifecycle(); + void TestLifeCycleGetLifecycleState(); + void TestLifeCycleAddObserver(); + void TestLifeCycleDispatchLifecycle(); + void TestLifeCycleDispatchLifecycleOne(); + void TestLifeCycleDispatchLifecycleTwo(); + void TestLifeCycleRemoveObserver(); + void StopSelfAbility(); + bool SubscribeEvent(); + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + Want want_ = {}; + sptr stub_ = {}; + sptr connCallback_ = {}; + std::shared_ptr subscriber_ = {}; +}; +int AbilityLifeCycleAbility::sequenceNumber_ = 0; + +class AbilityLifeCycleAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + AbilityLifeCycleAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + + {"LifeCycleGetLifecycle", [this]() { TestLifeCycleGetLifecycle(); }}, + {"LifeCycleGetLifecycleState", [this]() { TestLifeCycleGetLifecycleState(); }}, + {"LifeCycleAddObserver", [this]() { TestLifeCycleAddObserver(); }}, + {"LifeCycleDispatchLifecycle", [this]() { TestLifeCycleDispatchLifecycle(); }}, + {"LifeCycleRemoveObserver", [this]() { TestLifeCycleRemoveObserver(); }}, + {"StopSelfAbility", [this]() { StopSelfAbility(); }}, + }; + } + ~AbilityLifeCycleAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + void TestLifeCycleGetLifecycle() + { + mainAbility.TestLifeCycleGetLifecycle(); + } + + void TestLifeCycleGetLifecycleState() + { + mainAbility.TestLifeCycleGetLifecycleState(); + } + + void TestLifeCycleAddObserver() + { + mainAbility.TestLifeCycleAddObserver(); + } + + void TestLifeCycleDispatchLifecycle() + { + mainAbility.TestLifeCycleDispatchLifecycle(); + } + + void TestLifeCycleRemoveObserver() + { + mainAbility.TestLifeCycleRemoveObserver(); + } + + void StopSelfAbility() + { + mainAbility.StopSelfAbility(); + } + + Want want = {}; + AbilityLifeCycleAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_LIFE_CYCLE_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/base_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/base_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..265cf04eddbfb993cf239049aca3db281ce00abc --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/base_ability.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 BASE_ABILITY_H_ +#define BASE_ABILITY_H_ +#include "ability.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "event_handler.h" + +namespace OHOS { +namespace AppExecFwk { +constexpr int MAX_LOOP = 10; + +template +void SubscribeEvent(const Want &want, const std::vector &eventList, const G &ability) +{ + EventFwk::MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + subscriber->want = want; + subscriber->mainAbility = ability; + EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber); +} + +template +void DoWhile() +{ + long cnt = 0; + while (cnt <= MAX_LOOP) { + cnt++; + } +} + +template +void PostTask() +{ + auto eventHandler = EventHandler::Current(); + if (!eventHandler) { + return; + } + eventHandler->PostTask([=]() { DoWhile(); }); +} + +class BaseAbility : public Ability { +public: + using EventHandlerPtr = std::shared_ptr; + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; + virtual void OnBackPressed() override; + + std::string GetNoFromWantInfo(const Want &want); + +private: + EventHandlerPtr envenHandler_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // BASE_ABILITY_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..73bd3364feef69df4a5cad290b3f8a9a910faab7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 LIFT_CYCLE_CALL_BACKS_ABILITY_H_ +#define LIFT_CYCLE_CALL_BACKS_ABILITY_H_ + +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class ServiceLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + ServiceLifecycleCallbacks() = default; + virtual ~ServiceLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + + void DoTask(); +}; + +class LifecycleCallbacksEventSubscriber; +class LifecycleCallbacksAbility : public Ability { +public: + ~LifecycleCallbacksAbility(); + static std::string sequenceNumber_; + void StopSelfAbility(); + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + bool SubscribeEvent(); + std::string GetNoFromWantInfo(const Want &want); + +private: + std::shared_ptr lifecycleCallbacks_ = {}; + Want want_ = {}; + std::shared_ptr subscriber_ = {}; +}; +std::string LifecycleCallbacksAbility::sequenceNumber_ = ""; + +class LifecycleCallbacksEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + LifecycleCallbacksEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"StopAbility", [this]() { StopSelfAbility(); }}, + }; + } + ~LifecycleCallbacksEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + Want want = {}; + LifecycleCallbacksAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; + + void StopSelfAbility() + { + mainAbility.StopSelfAbility(); + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // LIFT_CYCLE_CALL_BACKS_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_observer_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_observer_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..1d13aac14cce673b933cbc3f574d8cf5733c32f4 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_observer_ability.h @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 LIFE_CYCLE_OBSERVER_ABILITY_H_ +#define LIFE_CYCLE_OBSERVER_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class LifeCycleObserverConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t LifeCycleObserverConnectCallback::onAbilityConnectDoneCount = 0; + +class LifecycleObserverLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + LifecycleObserverLifecycleCallbacks() = default; + virtual ~LifecycleObserverLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; +}; + +class LifecycleObserverLifecycleObserver : public ILifecycleObserver { +public: + LifecycleObserverLifecycleObserver() = default; + virtual ~LifecycleObserverLifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; + + void DoTask(); +}; + +class LifeCycleObserverAbilityEventSubscriber; +class LifeCycleObserverAbility : public BaseAbility { +public: + ~LifeCycleObserverAbility(); + + static int sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + + void TestLifeCycleGetLifecycle(); + void TestLifeCycleGetLifecycleState(); + void TestLifeCycleAddObserver(); + void TestLifeCycleDispatchLifecycle(); + void TestLifeCycleDispatchLifecycleOne(); + void TestLifeCycleDispatchLifecycleTwo(); + void TestLifeCycleRemoveObserver(); + void StopSelfAbility(); + bool SubscribeEvent(); + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + Want want_ = {}; + sptr stub_ = {}; + sptr connCallback_ = {}; + + std::shared_ptr lifecycleCallbacks_ = {}; + std::shared_ptr lifecycleObserver_ = {}; + std::shared_ptr subscriber_ = {}; +}; +int LifeCycleObserverAbility::sequenceNumber_ = 0; + +class LifeCycleObserverAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + LifeCycleObserverAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + + {"LifeCycleGetLifecycle", [this]() { TestLifeCycleGetLifecycle(); }}, + {"LifeCycleGetLifecycleState", [this]() { TestLifeCycleGetLifecycleState(); }}, + {"LifeCycleAddObserver", [this]() { TestLifeCycleAddObserver(); }}, + {"LifeCycleDispatchLifecycle", [this]() { TestLifeCycleDispatchLifecycle(); }}, + {"LifeCycleRemoveObserver", [this]() { TestLifeCycleRemoveObserver(); }}, + {"StopSelfAbility", [this]() { StopSelfAbility(); }}, + }; + } + ~LifeCycleObserverAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + void TestLifeCycleGetLifecycle() + { + mainAbility.TestLifeCycleGetLifecycle(); + } + + void TestLifeCycleGetLifecycleState() + { + mainAbility.TestLifeCycleGetLifecycleState(); + } + + void TestLifeCycleAddObserver() + { + mainAbility.TestLifeCycleAddObserver(); + } + + void TestLifeCycleDispatchLifecycle() + { + mainAbility.TestLifeCycleDispatchLifecycle(); + } + + void TestLifeCycleRemoveObserver() + { + mainAbility.TestLifeCycleRemoveObserver(); + } + + void StopSelfAbility() + { + mainAbility.StopSelfAbility(); + } + + Want want = {}; + LifeCycleObserverAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // LIFE_CYCLE_OBSERVER_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..36e830d49f8bb73e29ae3fdd4aa7ba988edf9cce --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/test_utils.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H_ +#define TEST_UTILS_H_ +#include "ability_info.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::AAFwk; +const std::string EVENT_RESP_LIFECYCLE_CALLBACK = "resp_com_ohos_amsst_appkit_service_ability_lifecycle_callbacks"; +const std::string EVENT_RESP_LIFECYCLE_OBSERVER = "resp_com_ohos_amsst_appkit_service_lifecycle_observer"; +const std::string EVENT_RESP_FIRST_ABILITY = "resp_com_ohos_amsst_appkit_service_mainabilitydemo"; +const std::string EVENT_RESP_SECOND_ABILITY = "resp_com_ohos_amsst_appkit_service_secondability"; +const std::string EVENT_RESP_KITTEST_COMPLETE = "resp_com_ohos_amsst_appkit_service_kittest_completed"; +const std::string EVENT_REQU_KITTEST = "requ_com_ohos_amsst_appkit_service_kittest"; +const std::string EVENT_RESP_SECOND_ABILITY_CONTEXT = + "resp_com_ohos_amsst_appkit_service_secondability_ability_context"; +const std::string EVENT_REQU_KITTEST_SECOND = "resp_com_ohos_amsst_appkit_service_secondability_kittest"; + +const std::string APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_life_cycle_call_backs"; +const std::string APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_life_cycle_call_backs"; + +const std::string APP_ABILITY_CONTEXT_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_context"; +const std::string APP_ABILITY_CONTEXT_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_context"; + +const std::string APP_ABILITY_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability"; +const std::string APP_ABILITY_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability"; + +const std::string APP_ABILITY_CONNECTION_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_connection"; +const std::string APP_ABILITY_CONNECTION_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_connection"; + +const std::string APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_life_cycle"; +const std::string APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_life_cycle"; + +const std::string APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_life_cycle_observer"; +const std::string APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_life_cycle_observer"; + +enum class CaseIndex { + ONE = 1, + TWO = 2, + THREE = 3, + FOUR = 4, + FIVE = 5, + SIX = 6, + SEVEN = 7, + EIGHT = 8, + NINE = 9, + TEN = 10, + ELEVEN = 11, + TWELVE = 12, + THIRTEEN = 13, + FOURTEEN = 14, + FIFTEEN = 15, + SIXTEEN = 16, + SEVENTEEN = 17, + EIGHTEEN = 18, + NINETEEN = 19, + TWENTY = 20, + HANDRED = 1024, +}; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54c96e090ba5119e918dec2dccbe80bba0a7756b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp @@ -0,0 +1,865 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_ability.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +void AbilityAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AbilityAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); +} + +void AbilityAbility::DoTestCase() +{ + if (!AbilityAbility::sequenceNumber_.empty()) { + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::TWELVE: + OHOS::AppExecFwk::PostTask(); + break; + case CaseIndex::THIRTEEN: + DoWhile(); + break; + case CaseIndex::FOURTEEN: + StopAbility(want_); + break; + case CaseIndex::FIFTEEN: + TerminateAbility(); + break; + default: + break; + } + } +} + +AbilityAbility::~AbilityAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +bool AbilityAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_ABILITY_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AbilityAbility::OnStart(const Want &want) +{ + APP_LOGI("AbilityAbility::OnStart"); + + sequenceNumber_ = GetNoFromWantInfo(want); + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s", sequenceNumber_.c_str()); + want_ = want; + APP_LOGI("AbilityAbility::OnStart"); + BaseAbility::OnStart(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + + DoTestCase(); +} + +void AbilityAbility::OnStop() +{ + APP_LOGI("AbilityAbility::OnStop"); + + BaseAbility::OnStop(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); + + DoTestCase(); +} + +void AbilityAbility::OnActive() +{ + APP_LOGI("AbilityAbility::OnActive"); + + BaseAbility::OnActive(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); + + DoTestCase(); +} + +void AbilityAbility::OnInactive() +{ + APP_LOGI("AbilityAbility::OnInactive"); + + BaseAbility::OnInactive(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); + + DoTestCase(); +} + +void AbilityAbility::OnBackground() +{ + APP_LOGI("AbilityAbility::OnBackground"); + + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); + + DoTestCase(); +} + +void AbilityAbility::OnForeground(const Want &want) +{ + APP_LOGI("AbilityAbility::OnForeground"); + + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnForeground"); + + DoTestCase(); +} + +void AbilityAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("AbilityAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); + + DoTestCase(); +} + +sptr AbilityAbility::OnConnect(const Want &want) +{ + APP_LOGI("AbilityAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + + DoTestCase(); + + return ret; +} + +void AbilityAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AbilityAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); + + DoTestCase(); +} + +void AbilityAbility::OnNewWant(const Want &want) +{ + APP_LOGI("AbilityAbility::OnNewWant"); + + BaseAbility::OnNewWant(want); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnNewWant"); + + DoTestCase(); +} + +void AbilityAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("AbilityAbility::OnNewWant"); + + BaseAbility::OnAbilityResult(requestCode, resultCode, resultData); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, requestCode, "OnAbilityResult"); + + DoTestCase(); +} + +void AbilityAbility::StopSelfAbility() +{ + TerminateAbility(); +} + +void AbilityAbility::TestConnectAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::TWO: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestStopAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.page.AppKitA", params); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityAbility::TestStartAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want, INT_MAX); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want, INT_MIN); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestTerminateAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want, 0); + sleep(1); + StopAbility(want); + sleep(1); + TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want, 0); + sleep(1); + StopAbility(want); + sleep(1); + TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + TerminateAbility(); + sleep(1); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want, 0); + sleep(1); + TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestStartAbilityWithSetting() +{ + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + StartAbility(want_, *AbilityStartSetting::GetEmptySetting().get()); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityWithSetting"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want, *AbilityStartSetting::GetEmptySetting().get()); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityWithSetting"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want, *AbilityStartSetting::GetEmptySetting().get()); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityWithSetting"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + StartAbility(want_, *AbilityStartSetting::GetEmptySetting().get()); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityWithSetting"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want, *AbilityStartSetting::GetEmptySetting().get()); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityWithSetting"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestStartAbilityForResult() +{ + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + StartAbilityForResult(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityForResult"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.page.AppKitA", params); + StartAbilityForResult(want, INT_MAX); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityForResult"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbilityForResult(want, INT_MIN); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityForResult"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + StartAbilityForResult(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityForResult"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbilityForResult(want, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbilityForResult"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityStartAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + StartAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + StartAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityConnectAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + break; + } + case CaseIndex::TWO: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityStopAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want); + sleep(1); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want); + sleep(1); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityGetLifecycle() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::TWO: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + default: + break; + } +} + +void AbilityAbility::caseIndexOne() +{ + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::caseIndexTwo() +{ + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::TestAbilityDisconnectAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + caseIndexOne(); + break; + } + case CaseIndex::TWO: { + caseIndexTwo(); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("AbilityAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("AbilityAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("AbilityAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_ABILITY_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI( + "AbilityAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} +REGISTER_AA(AbilityAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_context_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_context_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..283ac05ac30b8690229059ac53aa56d179491275 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_context_ability.cpp @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_context_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +AbilityContextAbility::~AbilityContextAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AbilityContextAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AbilityContextAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); +} + +bool AbilityContextAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AbilityContextAbility::OnStart(const Want &want) +{ + want_ = want; + sequenceNumber_ = std::stoi(GetNoFromWantInfo(want)); + APP_LOGI("AbilityContextAbility::OnStart"); + + BaseAbility::OnStart(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnStart"); +} + +void AbilityContextAbility::OnStop() +{ + APP_LOGI("AbilityContextAbility::OnStop"); + BaseAbility::OnStop(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnStop"); +} + +void AbilityContextAbility::OnActive() +{ + APP_LOGI("AbilityContextAbility::OnActive"); + BaseAbility::OnActive(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnActive"); +} + +void AbilityContextAbility::OnInactive() +{ + APP_LOGI("AbilityContextAbility::OnInactive"); + BaseAbility::OnInactive(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnInactive"); +} + +void AbilityContextAbility::OnBackground() +{ + APP_LOGI("AbilityContextAbility::OnBackground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnBackground"); +} + +void AbilityContextAbility::OnForeground(const Want &want) +{ + APP_LOGI("AbilityContextAbility::OnForeground"); + BaseAbility::OnForeground(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnForeground"); +} + +void AbilityContextAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("AbilityContextAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnCommand"); +} + +sptr AbilityContextAbility::OnConnect(const Want &want) +{ + APP_LOGI("AbilityContextAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnConnect"); + return ret; +} + +void AbilityContextAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AbilityContextAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityContextAbility::GetState(), "OnDisconnect"); +} + +void AbilityContextAbility::TestConnectAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::TWO: { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } + } break; + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityContextConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + default: + break; + } +} + +void AbilityContextAbility::TestStopAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + default: + break; + } +} + +void AbilityContextAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + default: + break; + } +} + +void AbilityContextAbility::TestStartAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + default: + break; + } +} + +void AbilityContextAbility::TestTerminateAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + sleep(1); + BaseAbility::GetContext()->StopAbility(want); + sleep(1); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + sleep(1); + BaseAbility::GetContext()->StopAbility(want); + sleep(1); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + default: + break; + } +} + +void AbilityContextAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI( + "AbilityContextAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("AbilityContextAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("AbilityContextAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_ABILITY_CONTEXT_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("AbilityContextAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", + target.c_str()); + } + } +} +REGISTER_AA(AbilityContextAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c2552fa710c22685e4eb5522b129f6a26d306081 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp @@ -0,0 +1,718 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_life_cycle_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int loopCnt = 3; +} // namespace + +AbilityLifeCycleAbility::~AbilityLifeCycleAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AbilityLifeCycleAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AbilityLifeCycleAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + SubscribeEvent(); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::StopSelfAbility() +{ + TerminateAbility(); +} + +bool AbilityLifeCycleAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AbilityLifeCycleAbility::OnStart(const Want &want) +{ + sequenceNumber_ = std::stoi(GetNoFromWantInfo(want)); + want_ = want; + APP_LOGI("AbilityLifeCycleAbility::OnStart"); + + BaseAbility::OnStart(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnStart"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnStop() +{ + APP_LOGI("AbilityLifeCycleAbility::OnStop"); + BaseAbility::OnStop(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnStop"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnActive() +{ + APP_LOGI("AbilityLifeCycleAbility::OnActive"); + BaseAbility::OnActive(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnActive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnInactive() +{ + APP_LOGI("AbilityLifeCycleAbility::OnInactive"); + BaseAbility::OnInactive(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnInactive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnBackground() +{ + APP_LOGI("AbilityLifeCycleAbility::OnBackground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnBackground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnForeground(const Want &want) +{ + APP_LOGI("AbilityLifeCycleAbility::OnForeground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnForeground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("AbilityLifeCycleAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnCommand"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +sptr AbilityLifeCycleAbility::OnConnect(const Want &want) +{ + APP_LOGI("AbilityLifeCycleAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnConnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); + return ret; +} + +void AbilityLifeCycleAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AbilityLifeCycleAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "OnDisconnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::TestConnectAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::TWO: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } + } break; + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityLifeCycleConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestStopAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < loopCnt; i++) { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestStartAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestTerminateAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleGetLifecycle() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::TWO: { + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleGetLifecycleState() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::TWO: { + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + default: + break; + } +} + +void AbilityLifecycleLifecycleObserver::OnActive() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnActive"); +} + +void AbilityLifecycleLifecycleObserver::OnBackground() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnBackground"); +} + +void AbilityLifecycleLifecycleObserver::OnForeground(const Want &want) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnForeground"); +} + +void AbilityLifecycleLifecycleObserver::OnInactive() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnInactive"); +} + +void AbilityLifecycleLifecycleObserver::OnStart(const Want &want) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStart"); +} + +void AbilityLifecycleLifecycleObserver::OnStop() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStop"); +} + +void AbilityLifecycleLifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void AbilityLifecycleLifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void AbilityLifeCycleAbility::TestLifeCycleAddObserver() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::ONE; i++) { + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::ONE; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::ONE; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->AddObserver(nullptr); + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleDispatchLifecycleOne() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleDispatchLifecycleTwo() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_START); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_STOP); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::SEVEN: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::EIGHT: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::NINE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleDispatchLifecycle() +{ + TestLifeCycleDispatchLifecycleOne(); + TestLifeCycleDispatchLifecycleTwo(); +} + +void AbilityLifeCycleAbility::TestLifeCycleRemoveObserver() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + default: + break; + } +} + +void AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI( + "AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", + target.c_str()); + } + } +} +REGISTER_AA(AbilityLifeCycleAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/base_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/base_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fbf38eec9290408dfe4c1f9433443ab6b7b3f27 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/base_ability.cpp @@ -0,0 +1,124 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "base_ability.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +void BaseAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("BaseAbility::Init called."); + + Ability::Init(abilityInfo, application, handler, token); +} + +void BaseAbility::OnStart(const Want &want) +{ + APP_LOGI("BaseAbility::OnStart"); + + Ability::OnStart(want); +} + +void BaseAbility::OnStop() +{ + APP_LOGI("BaseAbility::OnStop"); + + Ability::OnStop(); +} + +void BaseAbility::OnActive() +{ + APP_LOGI("BaseAbility::OnActive"); + + Ability::OnActive(); +} + +void BaseAbility::OnInactive() +{ + APP_LOGI("BaseAbility::OnInactive"); + + Ability::OnInactive(); +} + +void BaseAbility::OnBackground() +{ + APP_LOGI("BaseAbility::OnBackground"); + + Ability::OnBackground(); +} + +void BaseAbility::OnForeground(const Want &want) +{ + APP_LOGI("BaseAbility::OnForeground"); + + Ability::OnForeground(want); +} + +void BaseAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("BaseAbility::OnCommand"); + + Ability::OnCommand(want, restart, startId); +} + +sptr BaseAbility::OnConnect(const Want &want) +{ + APP_LOGI("BaseAbility::OnConnect"); + + sptr ret = Ability::OnConnect(want); + return ret; +} + +void BaseAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("BaseAbility::OnDisconnect"); + + Ability::OnDisconnect(want); +} + +void BaseAbility::OnNewWant(const Want &want) +{ + APP_LOGI("BaseAbility::OnNewWant"); + + Ability::OnNewWant(want); +} + +void BaseAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{ + APP_LOGI("BaseAbility::OnAbilityResult"); + + Ability::OnAbilityResult(requestCode, resultCode, resultData); +} + +void BaseAbility::OnBackPressed() +{ + APP_LOGI("BaseAbility::OnBackPressed"); + + Ability::OnBackPressed(); +} + +std::string BaseAbility::GetNoFromWantInfo(const Want &want) +{ + Want wantImpl(want); + return wantImpl.GetStringParam("No."); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_call_backs_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_call_backs_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bc3dcf3a96ba25c347f0d9284bfd5f3172e9939 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_call_backs_ability.cpp @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "life_cycle_call_backs_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +void ServiceLifecycleCallbacks::DoTask() +{ + if (!LifecycleCallbacksAbility::sequenceNumber_.empty()) { + switch ((CaseIndex)std::stoi(LifecycleCallbacksAbility::sequenceNumber_)) { + case CaseIndex::TWO: + PostTask(); + break; + case CaseIndex::THREE: + DoWhile(); + break; + case CaseIndex::SIX: + break; + default: + break; + } + } +} +void ServiceLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityStart"); +} + +void ServiceLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityInactive"); +} + +void ServiceLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityBackground"); +} + +void ServiceLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityForeground"); +} + +void ServiceLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityActive"); +} + +void ServiceLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityStop"); +} + +void ServiceLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilitySaveState"); +} + +LifecycleCallbacksAbility::~LifecycleCallbacksAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void LifecycleCallbacksAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("LifecycleCallbacksAbility::Init called."); + + Ability::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); + lifecycleCallbacks_ = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(lifecycleCallbacks_); +} + +std::string LifecycleCallbacksAbility::GetNoFromWantInfo(const Want &want) +{ + Want wantImpl(want); + return wantImpl.GetStringParam("No."); +} + +void LifecycleCallbacksAbility::OnStart(const Want &want) +{ + APP_LOGI("LifecycleCallbacksAbility::OnStart"); + + sequenceNumber_ = GetNoFromWantInfo(want); + want_ = want; + Ability::OnStart(want); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); +} + +void LifecycleCallbacksAbility::StopSelfAbility() +{ + TerminateAbility(); +} + +void LifecycleCallbacksEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("LifecycleCallbacksEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("LifecycleCallbacksEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("LifecycleCallbacksEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI( + "LifecycleCallbacksEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +bool LifecycleCallbacksAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void LifecycleCallbacksAbility::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("LifecycleCallbacksAbility::OnCommand"); + + Ability::OnCommand(want, restart, startId); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void LifecycleCallbacksAbility::OnNewWant(const Want &want) +{ + APP_LOGI("LifecycleCallbacksAbility::OnNewWant"); + + Ability::OnNewWant(want); +} +void LifecycleCallbacksAbility::OnStop() +{ + APP_LOGI("LifecycleCallbacksAbility::OnStop"); + + Ability::OnStop(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void LifecycleCallbacksAbility::OnActive() +{ + APP_LOGI("LifecycleCallbacksAbility::OnActive"); + + Ability::OnActive(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void LifecycleCallbacksAbility::OnInactive() +{ + APP_LOGI("LifecycleCallbacksAbility::OnInactive"); + + Ability::OnInactive(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void LifecycleCallbacksAbility::OnBackground() +{ + APP_LOGI("LifecycleCallbacksAbility::OnBackground"); + + Ability::OnBackground(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, + AbilityLifecycleExecutor::LifecycleState::BACKGROUND, + "OnBackground"); +} + +void LifecycleCallbacksAbility::OnForeground(const Want &want) +{ + APP_LOGI("LifecycleCallbacksAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnForeground"); +} + +REGISTER_AA(LifecycleCallbacksAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0733fca7729313f2a8e47b7391af9c585df9aac --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp @@ -0,0 +1,783 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "life_cycle_observer_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int loopCnt = 100; +} +void LifecycleObserverLifecycleObserver::DoTask() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::TWO: + PostTask(); + break; + case CaseIndex::THREE: + DoWhile(); + break; + case CaseIndex::SIX: + break; + default: + break; + } +} + +void LifecycleObserverLifecycleObserver::OnActive() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnActive"); +} + +void LifecycleObserverLifecycleObserver::OnBackground() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnBackground"); +} + +void LifecycleObserverLifecycleObserver::OnForeground(const Want &want) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnForeground"); +} + +void LifecycleObserverLifecycleObserver::OnInactive() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnInactive"); +} + +void LifecycleObserverLifecycleObserver::OnStart(const Want &want) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStart"); +} + +void LifecycleObserverLifecycleObserver::OnStop() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStop"); +} + +void LifecycleObserverLifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void LifecycleObserverLifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ability->GetState(), "OnAbilityStart"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ability->GetState(), "OnAbilityInactive"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ability->GetState(), "OnAbilityBackground"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ability->GetState(), "OnAbilityForeground"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ability->GetState(), "OnAbilityActive"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ability->GetState(), "OnAbilityStop"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{} + +LifeCycleObserverAbility::~LifeCycleObserverAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void LifeCycleObserverAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("LifeCycleObserverAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); + + lifecycleCallbacks_ = std::make_shared(); + GetApplication()->RegisterAbilityLifecycleCallbacks(lifecycleCallbacks_); + lifecycleObserver_ = std::make_shared(); + GetLifecycle()->AddObserver(lifecycleObserver_); + + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, + BaseAbility::GetLifecycle()->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::StopSelfAbility() +{ + TerminateAbility(); +} + +bool LifeCycleObserverAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void LifeCycleObserverAbility::OnStart(const Want &want) +{ + sequenceNumber_ = std::stoi(GetNoFromWantInfo(want)); + want_ = want; + APP_LOGI("LifeCycleObserverAbility::OnStart"); + + BaseAbility::OnStart(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnStart"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnStop() +{ + APP_LOGI("LifeCycleObserverAbility::OnStop"); + BaseAbility::OnStop(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnStop"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnActive() +{ + APP_LOGI("LifeCycleObserverAbility::OnActive"); + BaseAbility::OnActive(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnActive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnInactive() +{ + APP_LOGI("LifeCycleObserverAbility::OnInactive"); + BaseAbility::OnInactive(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnInactive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnBackground() +{ + APP_LOGI("LifeCycleObserverAbility::OnBackground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnBackground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnForeground(const Want &want) +{ + APP_LOGI("LifeCycleObserverAbility::OnForeground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnForeground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("LifeCycleObserverAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnCommand"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +sptr LifeCycleObserverAbility::OnConnect(const Want &want) +{ + APP_LOGI("LifeCycleObserverAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnConnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); + return ret; +} + +void LifeCycleObserverAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("LifeCycleObserverAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, LifeCycleObserverAbility::GetState(), "OnDisconnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::TestConnectAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::TWO: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) LifeCycleObserverConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + default: + break; + } +} + +void LifeCycleObserverAbility::TestStopAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestStartAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestTerminateAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleGetLifecycle() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::TWO: { + for (int i = 0; i < loopCnt; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleGetLifecycleState() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::TWO: { + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleAddObserver() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->AddObserver(nullptr); + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleDispatchLifecycleOne() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleDispatchLifecycleTwo() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_START); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_STOP); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::SEVEN: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::EIGHT: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::NINE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleDispatchLifecycle() +{ + TestLifeCycleDispatchLifecycleOne(); + TestLifeCycleDispatchLifecycleTwo(); +} + +void LifeCycleObserverAbility::TestLifeCycleRemoveObserver() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI( + "LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", + target.c_str()); + } + } +} +REGISTER_AA(LifeCycleObserverAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6a74ab78d2ebe0a92e07d36ba8639bb0f2288da --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/test_utils.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..0244c73907932b9cd5b3084d1d3df42a9c00ecee --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsKitSystemTestService" +config("amsKitSystemTestServiceconfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsKitSystemTestService\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsKitSystemTestService") { + sources = [ + "src/ability_ability.cpp", + "src/ability_connection_ability.cpp", + "src/ability_context_ability.cpp", + "src/ability_life_cycle_ability.cpp", + "src/base_ability.cpp", + "src/life_cycle_call_backs_ability.cpp", + "src/life_cycle_observer_ability.cpp", + "src/test_utils.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":amsKitSystemTestServiceconfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "${libs_path}/libeventhandler:libeventhandler_target", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3dd4f317b5780af56a34824ebb989a0678056e9f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/config.json @@ -0,0 +1,93 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.AppKit", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsKitSystemTestService.src", + "name":"AmsKitSystemTestService", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "LifecycleCallbacksAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "AbilityContextAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "AbilityAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "AbilityLifeCycleAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "LifeCycleObserverAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "AbilityConnectionAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Lifecycle Callbacks Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + } + ] + } +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..ef28fca50f763afcf800619f687b6aa6b2d984d6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_ABILITY_H_ +#define ABILITY_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class AbilityConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t AbilityConnectCallback::onAbilityConnectDoneCount = 0; + +class AbilityAbilityEventSubscriber; +class AbilityAbility : public BaseAbility { +public: + ~AbilityAbility(); + + static std::string sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + + void TestAbilityStartAbility(); + void TestAbilityConnectAbility(); + void TestAbilityStopAbility(); + void TestAbilityGetLifecycle(); + void TestAbilityDisconnectAbility(); + + void DoTestCase(); + void CaseIndexOne(); + void CaseIndexTwo(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); + void AbilityDisconnectCaseIndexOne(); + void AbilityDisconnectCaseIndexTwo(); +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + + bool SubscribeEvent(); + +private: + Want want_ = {}; + sptr stub_ = {}; + sptr connCallback_ = {}; + std::shared_ptr subscriber_ = {}; +}; +std::string AbilityAbility::sequenceNumber_ = "0"; + +class AbilityAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + AbilityAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + + {"AbilityStartAbility", [this]() { TestAbilityStartAbility(); }}, + {"AbilityConnectAbility", [this]() { TestAbilityConnectAbility(); }}, + {"AbilityStopAbility", [this]() { TestAbilityStopAbility(); }}, + {"AbilityGetLifecycle", [this]() { TestAbilityGetLifecycle(); }}, + {"AbilityDisconnectAbility", [this]() { TestAbilityDisconnectAbility(); }}, + }; + } + ~AbilityAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + void TestAbilityStartAbility() + { + mainAbility.TestAbilityStartAbility(); + } + + void TestAbilityConnectAbility() + { + mainAbility.TestAbilityConnectAbility(); + } + + void TestAbilityStopAbility() + { + mainAbility.TestAbilityStopAbility(); + } + + void TestAbilityGetLifecycle() + { + mainAbility.TestAbilityGetLifecycle(); + } + + void TestAbilityDisconnectAbility() + { + mainAbility.TestAbilityDisconnectAbility(); + } + + Want want = {}; + AbilityAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..e094e4e8de820cde094d854c6f0bf8aa958ff391 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_CONNECTION_ABILITY_H_ +#define ABILITY_CONNECTION_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class AbilityConnectionConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + +private: + size_t onAbilityConnectDoneCount = 0; +}; + +class AbilityConnectionAbilityEventSubscriber; +class AbilityConnectionAbility : public BaseAbility { +public: + ~AbilityConnectionAbility(); + + static std::string sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); + void ConnectCaseIndexOne(); + void ConnectCaseIndexTwo(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + + bool SubscribeEvent(); + +private: + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; + std::shared_ptr subscriber_ = {}; +}; +std::string AbilityConnectionAbility::sequenceNumber_ = "0"; + +class AbilityConnectionAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + AbilityConnectionAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + }; + } + ~AbilityConnectionAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + Want want = {}; + AbilityConnectionAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_CONNECTION_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..95242ba347f1be9ed20933f0cd0c2d457839f4cf --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_CONTEXT_ABILITY_H_ +#define ABILITY_CONTEXT_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class AbilityContextConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t AbilityContextConnectCallback::onAbilityConnectDoneCount = 0; + +class AbilityContextAbilityEventSubscriber; +class AbilityContextAbility : public BaseAbility { +public: + ~AbilityContextAbility(); + + static int sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + + bool SubscribeEvent(); + void ConnectCaseIndexOne(); + void ConnectCaseIndexTwo(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); +private: + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; + std::shared_ptr subscriber_ = {}; +}; +int AbilityContextAbility::sequenceNumber_ = 0; + +class AbilityContextAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + AbilityContextAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + }; + } + ~AbilityContextAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + Want want = {}; + AbilityContextAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_CONTEXT_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..c52ea2d40fb21a629e02b4fe8b74c2109d575e1a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_LIFE_CYCLE_ABILITY_H_ +#define ABILITY_LIFE_CYCLE_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class AbilityLifeCycleConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t AbilityLifeCycleConnectCallback::onAbilityConnectDoneCount = 0; + +class AbilityLifecycleLifecycleObserver : public ILifecycleObserver { +public: + AbilityLifecycleLifecycleObserver() = default; + virtual ~AbilityLifecycleLifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; +}; + +class AbilityLifeCycleAbilityEventSubscriber; +class AbilityLifeCycleAbility : public BaseAbility { +public: + ~AbilityLifeCycleAbility(); + + static int sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + + void TestLifeCycleGetLifecycle(); + void TestLifeCycleGetLifecycleState(); + void TestLifeCycleAddObserver(); + void TestLifeCycleDispatchLifecycle(); + void TestLifeCycleDispatchLifecycleOne(); + void TestLifeCycleDispatchLifecycleTwo(); + void TestLifeCycleRemoveObserver(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + + bool SubscribeEvent(); + void GetLifecycleStateCaseOne(); +private: + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; + std::shared_ptr subscriber_ = {}; +}; +int AbilityLifeCycleAbility::sequenceNumber_ = 0; + +class AbilityLifeCycleAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + AbilityLifeCycleAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + + {"LifeCycleGetLifecycle", [this]() { TestLifeCycleGetLifecycle(); }}, + {"LifeCycleGetLifecycleState", [this]() { TestLifeCycleGetLifecycleState(); }}, + {"LifeCycleAddObserver", [this]() { TestLifeCycleAddObserver(); }}, + {"LifeCycleDispatchLifecycle", [this]() { TestLifeCycleDispatchLifecycle(); }}, + {"LifeCycleRemoveObserver", [this]() { TestLifeCycleRemoveObserver(); }}, + }; + } + ~AbilityLifeCycleAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + void TestLifeCycleGetLifecycle() + { + mainAbility.TestLifeCycleGetLifecycle(); + } + + void TestLifeCycleGetLifecycleState() + { + mainAbility.TestLifeCycleGetLifecycleState(); + } + + void TestLifeCycleAddObserver() + { + mainAbility.TestLifeCycleAddObserver(); + } + + void TestLifeCycleDispatchLifecycle() + { + mainAbility.TestLifeCycleDispatchLifecycle(); + } + + void TestLifeCycleRemoveObserver() + { + mainAbility.TestLifeCycleRemoveObserver(); + } + + Want want = {}; + AbilityLifeCycleAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_LIFE_CYCLE_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/base_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/base_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..3873cdc62ee916fc87c14afe1bbd238962292af4 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/base_ability.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 BASE_ABILITY_H_ +#define BASE_ABILITY_H_ +#include "ability.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "event_handler.h" + +namespace OHOS { +namespace AppExecFwk { +constexpr int MAX_LOOP = 10; +template +void SubscribeEvent(const Want &want, const std::vector &eventList, const G &ability) +{ + EventFwk::MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + subscriber->want = want; + subscriber->mainAbility = ability; + EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber); +} + +template +void DoWhile() +{ + long cnt = 0; + while (cnt <= MAX_LOOP) { + cnt++; + } +} + +template +void PostTask() +{ + auto eventHandler = EventHandler::Current(); + if (!eventHandler) { + return; + } + eventHandler->PostTask([=]() { DoWhile(); }); +} + +class BaseAbility : public Ability { +public: + using EventHandlerPtr = std::shared_ptr; + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + + std::string GetNoFromWantInfo(const Want &want); + +private: + EventHandlerPtr envenHandler_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // BASE_ABILITY_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..25b50672cc6ccd0204e7778a4a3b9143926d6f86 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 LIFT_CYCLE_CALL_BACKS_ABILITY_H_ +#define LIFT_CYCLE_CALL_BACKS_ABILITY_H_ + +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class ServiceLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + ServiceLifecycleCallbacks() = default; + virtual ~ServiceLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; + + void DoTask(); +}; + +class LifecycleCallbacksEventSubscriber; +class LifecycleCallbacksAbility : public Ability { +public: + ~LifecycleCallbacksAbility(); + + static std::string sequenceNumber_; + void StopSelfAbility(); + +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + bool SubscribeEvent(); + std::string GetNoFromWantInfo(const Want &want); + +private: + std::shared_ptr lifecycleCallbacks_ = {}; + std::shared_ptr subscriber_ = {}; +}; +std::string LifecycleCallbacksAbility::sequenceNumber_ = ""; + +class LifecycleCallbacksEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + LifecycleCallbacksEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"StopAbility", [this]() { StopSelfAbility(); }}, + }; + } + ~LifecycleCallbacksEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + Want want = {}; + LifecycleCallbacksAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; + + void StopSelfAbility() + { + mainAbility.StopSelfAbility(); + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // LIFT_CYCLE_CALL_BACKS_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_observer_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_observer_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..1a5139945a6010b6c85bd0036acd7f646c2fcb5f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_observer_ability.h @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 LIFE_CYCLE_OBSERVER_ABILITY_H_ +#define LIFE_CYCLE_OBSERVER_ABILITY_H_ + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_lifecycle_observer_interface.h" +#include "ability_loader.h" +#include "base_ability.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +typedef std::map MAP_STR_STR; +class LifeCycleObserverConnectCallback : public AAFwk::AbilityConnectionStub { +public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; +}; +size_t LifeCycleObserverConnectCallback::onAbilityConnectDoneCount = 0; + +class LifecycleObserverLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + LifecycleObserverLifecycleCallbacks() = default; + virtual ~LifecycleObserverLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability) override; + virtual void OnAbilityInactive(const std::shared_ptr &ability) override; + virtual void OnAbilityBackground(const std::shared_ptr &ability) override; + virtual void OnAbilityForeground(const std::shared_ptr &ability) override; + virtual void OnAbilityActive(const std::shared_ptr &ability) override; + virtual void OnAbilityStop(const std::shared_ptr &ability) override; + virtual void OnAbilitySaveState(const PacMap &outState) override; +}; + +class LifecycleObserverLifecycleObserver : public ILifecycleObserver { +public: + LifecycleObserverLifecycleObserver() = default; + virtual ~LifecycleObserverLifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; + + void DoTask(); +}; + +class LifeCycleObserverAbilityEventSubscriber; +class LifeCycleObserverAbility : public BaseAbility { +public: + ~LifeCycleObserverAbility(); + + static int sequenceNumber_; + void TestConnectAbility(); + void TestStopAbility(); + void TestDisconnectAbility(); + void TestStartAbility(); + void TestTerminateAbility(); + + void TestLifeCycleGetLifecycle(); + void TestLifeCycleGetLifecycleState(); + void TestLifeCycleAddObserver(); + void TestLifeCycleDispatchLifecycle(); + void TestLifeCycleDispatchLifecycleOne(); + void TestLifeCycleDispatchLifecycleTwo(); + void TestLifeCycleRemoveObserver(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + + bool SubscribeEvent(); + +private: + Want want_ = {}; + sptr stub_ = {}; + sptr connCallback_ = {}; + + std::shared_ptr lifecycleCallbacks_ = {}; + std::shared_ptr lifecycleObserver_ = {}; + std::shared_ptr subscriber_ = {}; +}; +int LifeCycleObserverAbility::sequenceNumber_ = 0; + +class LifeCycleObserverAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + LifeCycleObserverAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"ConnectAbility", [this]() { TestConnectAbility(); }}, + {"StopAbility", [this]() { TestStopAbility(); }}, + {"DisconnectAbility", [this]() { TestDisconnectAbility(); }}, + {"StartAbility", [this]() { TestStartAbility(); }}, + {"TerminateAbility", [this]() { TestTerminateAbility(); }}, + + {"LifeCycleGetLifecycle", [this]() { TestLifeCycleGetLifecycle(); }}, + {"LifeCycleGetLifecycleState", [this]() { TestLifeCycleGetLifecycleState(); }}, + {"LifeCycleAddObserver", [this]() { TestLifeCycleAddObserver(); }}, + {"LifeCycleDispatchLifecycle", [this]() { TestLifeCycleDispatchLifecycle(); }}, + {"LifeCycleRemoveObserver", [this]() { TestLifeCycleRemoveObserver(); }}, + }; + } + ~LifeCycleObserverAbilityEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + void TestConnectAbility() + { + mainAbility.TestConnectAbility(); + } + + void TestStopAbility() + { + mainAbility.TestStopAbility(); + } + + void TestDisconnectAbility() + { + mainAbility.TestDisconnectAbility(); + } + + void TestStartAbility() + { + mainAbility.TestStartAbility(); + } + + void TestTerminateAbility() + { + mainAbility.TestTerminateAbility(); + } + + void TestLifeCycleGetLifecycle() + { + mainAbility.TestLifeCycleGetLifecycle(); + } + + void TestLifeCycleGetLifecycleState() + { + mainAbility.TestLifeCycleGetLifecycleState(); + } + + void TestLifeCycleAddObserver() + { + mainAbility.TestLifeCycleAddObserver(); + } + + void TestLifeCycleDispatchLifecycle() + { + mainAbility.TestLifeCycleDispatchLifecycle(); + } + + void TestLifeCycleRemoveObserver() + { + mainAbility.TestLifeCycleRemoveObserver(); + } + + Want want = {}; + LifeCycleObserverAbility mainAbility = {}; + std::unordered_map> mapTestFunc_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // LIFE_CYCLE_OBSERVER_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..36e830d49f8bb73e29ae3fdd4aa7ba988edf9cce --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/test_utils.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H_ +#define TEST_UTILS_H_ +#include "ability_info.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::AAFwk; +const std::string EVENT_RESP_LIFECYCLE_CALLBACK = "resp_com_ohos_amsst_appkit_service_ability_lifecycle_callbacks"; +const std::string EVENT_RESP_LIFECYCLE_OBSERVER = "resp_com_ohos_amsst_appkit_service_lifecycle_observer"; +const std::string EVENT_RESP_FIRST_ABILITY = "resp_com_ohos_amsst_appkit_service_mainabilitydemo"; +const std::string EVENT_RESP_SECOND_ABILITY = "resp_com_ohos_amsst_appkit_service_secondability"; +const std::string EVENT_RESP_KITTEST_COMPLETE = "resp_com_ohos_amsst_appkit_service_kittest_completed"; +const std::string EVENT_REQU_KITTEST = "requ_com_ohos_amsst_appkit_service_kittest"; +const std::string EVENT_RESP_SECOND_ABILITY_CONTEXT = + "resp_com_ohos_amsst_appkit_service_secondability_ability_context"; +const std::string EVENT_REQU_KITTEST_SECOND = "resp_com_ohos_amsst_appkit_service_secondability_kittest"; + +const std::string APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_life_cycle_call_backs"; +const std::string APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_life_cycle_call_backs"; + +const std::string APP_ABILITY_CONTEXT_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_context"; +const std::string APP_ABILITY_CONTEXT_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_context"; + +const std::string APP_ABILITY_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability"; +const std::string APP_ABILITY_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability"; + +const std::string APP_ABILITY_CONNECTION_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_connection"; +const std::string APP_ABILITY_CONNECTION_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_connection"; + +const std::string APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_life_cycle"; +const std::string APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_life_cycle"; + +const std::string APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_life_cycle_observer"; +const std::string APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_life_cycle_observer"; + +enum class CaseIndex { + ONE = 1, + TWO = 2, + THREE = 3, + FOUR = 4, + FIVE = 5, + SIX = 6, + SEVEN = 7, + EIGHT = 8, + NINE = 9, + TEN = 10, + ELEVEN = 11, + TWELVE = 12, + THIRTEEN = 13, + FOURTEEN = 14, + FIFTEEN = 15, + SIXTEEN = 16, + SEVENTEEN = 17, + EIGHTEEN = 18, + NINETEEN = 19, + TWENTY = 20, + HANDRED = 1024, +}; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3fbc8e2715d297c8a29b8ab8992627bac201cc35 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp @@ -0,0 +1,782 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int SLEEP_SECOND = 2; +constexpr int loopCnt = 3; +} + +AbilityAbility::~AbilityAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AbilityAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AbilityAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); +} + +void AbilityAbility::DoTestCase() +{ + if (!AbilityAbility::sequenceNumber_.empty()) { + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::TWELVE: + OHOS::AppExecFwk::PostTask(); + break; + case CaseIndex::THIRTEEN: + DoWhile(); + break; + default: + break; + } + } +} + +bool AbilityAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_ABILITY_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AbilityAbility::OnStart(const Want &want) +{ + APP_LOGI("AbilityAbility::OnStart"); + + sequenceNumber_ = GetNoFromWantInfo(want); + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s", sequenceNumber_.c_str()); + want_ = want; + APP_LOGI("AbilityAbility::OnStart"); + BaseAbility::OnStart(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + + DoTestCase(); +} + +void AbilityAbility::OnStop() +{ + APP_LOGI("AbilityAbility::OnStop"); + + BaseAbility::OnStop(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); + + DoTestCase(); +} + +void AbilityAbility::OnActive() +{ + APP_LOGI("AbilityAbility::OnActive"); + + BaseAbility::OnActive(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); + + DoTestCase(); +} + +void AbilityAbility::OnInactive() +{ + APP_LOGI("AbilityAbility::OnInactive"); + + BaseAbility::OnInactive(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); + + DoTestCase(); +} + +void AbilityAbility::OnBackground() +{ + APP_LOGI("AbilityAbility::OnBackground"); + + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); + + DoTestCase(); +} + +void AbilityAbility::OnForeground(const Want &want) +{ + APP_LOGI("AbilityAbility::OnForeground"); + + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnForeground"); + + DoTestCase(); +} + +void AbilityAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("AbilityAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); + + DoTestCase(); +} + +sptr AbilityAbility::OnConnect(const Want &want) +{ + APP_LOGI("AbilityAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + + DoTestCase(); + + return ret; +} + +void AbilityAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AbilityAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); + + DoTestCase(); +} + +void AbilityAbility::OnNewWant(const Want &want) +{ + APP_LOGI("AbilityAbility::OnNewWant"); + + BaseAbility::OnNewWant(want); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnNewWant"); + + DoTestCase(); +} + +void AbilityAbility::CaseIndexOne() +{ + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::CaseIndexTwo() +{ + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::TestConnectAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + CaseIndexOne(); + break; + } + case CaseIndex::TWO: { + CaseIndexTwo(); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback); + break; + } + default: + break; + } +} + +void AbilityAbility::TestStopAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < loopCnt; i++) { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::DisconnectCaseIndexOne() +{ + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::DisconnectCaseIndexTwo() +{ + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::TestDisconnectAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + DisconnectCaseIndexOne(); + break; + } + case CaseIndex::TWO: { + DisconnectCaseIndexTwo(); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < loopCnt; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityAbility::TestStartAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want, INT_MAX); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want, INT_MIN); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestTerminateAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + sleep(SLEEP_SECOND); + StopAbility(want); + TerminateAbility(); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + sleep(SLEEP_SECOND); + StopAbility(want); + TerminateAbility(); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want, 0); + sleep(SLEEP_SECOND); + TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityStartAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + StartAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + sleep(1); + StopAbility(want); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + StartAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityStartAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityConnectAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + break; + } + case CaseIndex::TWO: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityStopAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + StartAbility(want); + sleep(1); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + StartAbility(want); + sleep(1); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + StartAbility(want); + bool ret = StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityStopAbility"); + break; + } + default: + break; + } +} + +void AbilityAbility::TestAbilityGetLifecycle() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::TWO: { + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestAbilityGetLifecycle"); + break; + } + default: + break; + } +} + +void AbilityAbility::AbilityDisconnectCaseIndexOne() +{ + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::AbilityDisconnectCaseIndexTwo() +{ + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::TestAbilityDisconnectAbility() +{ + APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", + sequenceNumber_.c_str(), + std::stoi(AbilityAbility::sequenceNumber_)); + + switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + AbilityDisconnectCaseIndexOne(); + break; + } + case CaseIndex::TWO: { + AbilityDisconnectCaseIndexTwo(); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("AbilityAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("AbilityAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("AbilityAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_ABILITY_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI( + "AbilityAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} +REGISTER_AA(AbilityAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..896e0336114095dba415221abdac46bc99254663 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp @@ -0,0 +1,425 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_connection_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +AbilityConnectionAbility::~AbilityConnectionAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AbilityConnectionAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AbilityConnectionAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); +} + +bool AbilityConnectionAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AbilityConnectionAbility::OnStart(const Want &want) +{ + want_ = want; + sequenceNumber_ = GetNoFromWantInfo(want); + APP_LOGI("AbilityConnectionAbility::OnStart"); + + BaseAbility::OnStart(want); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); +} + +void AbilityConnectionAbility::OnStop() +{ + APP_LOGI("AbilityConnectionAbility::OnStop"); + BaseAbility::OnStop(); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} + +void AbilityConnectionAbility::OnActive() +{ + APP_LOGI("AbilityConnectionAbility::OnActive"); + BaseAbility::OnActive(); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} + +void AbilityConnectionAbility::OnInactive() +{ + APP_LOGI("AbilityConnectionAbility::OnInactive"); + BaseAbility::OnInactive(); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} + +void AbilityConnectionAbility::OnBackground() +{ + APP_LOGI("AbilityConnectionAbility::OnBackground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void AbilityConnectionAbility::OnForeground(const Want &want) +{ + APP_LOGI("AbilityConnectionAbility::OnForeground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnForeground"); +} + +void AbilityConnectionAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("AbilityConnectionAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} + +sptr AbilityConnectionAbility::OnConnect(const Want &want) +{ + APP_LOGI("AbilityConnectionAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return ret; +} + +void AbilityConnectionAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AbilityConnectionAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent( + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} + +void AbilityConnectionAbility::ConnectCaseIndexOne() +{ + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::ConnectCaseIndexTwo() +{ + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::TestConnectAbility() +{ + switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + ConnectCaseIndexOne(); + break; + } + case CaseIndex::TWO: { + ConnectCaseIndexTwo(); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityConnectionConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityConnectionAbility::TestStopAbility() +{ + switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + default: + break; + } +} + +void AbilityConnectionAbility::DisconnectCaseIndexOne() +{ + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::DisconnectCaseIndexTwo() +{ + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + DisconnectCaseIndexOne(); + break; + } + case CaseIndex::TWO: { + DisconnectCaseIndexTwo(); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityConnectionAbility::TestStartAbility() +{ + switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + default: + break; + } +} + +void AbilityConnectionAbility::TestTerminateAbility() +{ + switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + default: + break; + } +} + +void AbilityConnectionAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI( + "AbilityConnectionAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("AbilityConnectionAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("AbilityConnectionAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_ABILITY_CONNECTION_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("AbilityConnectionAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", + target.c_str()); + } + } +} +REGISTER_AA(AbilityConnectionAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..934641dfd2f000302f2f2c38f199abe455047bec --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp @@ -0,0 +1,434 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_context_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int SLEEP_SECOND = 2; +} + +AbilityContextAbility::~AbilityContextAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AbilityContextAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AbilityContextAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); +} + +bool AbilityContextAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AbilityContextAbility::OnStart(const Want &want) +{ + want_ = want; + sequenceNumber_ = std::stoi(GetNoFromWantInfo(want)); + APP_LOGI("AbilityContextAbility::OnStart"); + + BaseAbility::OnStart(want); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); +} + +void AbilityContextAbility::OnStop() +{ + APP_LOGI("AbilityContextAbility::OnStop"); + BaseAbility::OnStop(); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} + +void AbilityContextAbility::OnActive() +{ + APP_LOGI("AbilityContextAbility::OnActive"); + BaseAbility::OnActive(); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} + +void AbilityContextAbility::OnInactive() +{ + APP_LOGI("AbilityContextAbility::OnInactive"); + BaseAbility::OnInactive(); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} + +void AbilityContextAbility::OnBackground() +{ + APP_LOGI("AbilityContextAbility::OnBackground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void AbilityContextAbility::OnForeground(const Want &want) +{ + APP_LOGI("AbilityContextAbility::OnForeground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnForeground"); +} + +void AbilityContextAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("AbilityContextAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} + +sptr AbilityContextAbility::OnConnect(const Want &want) +{ + APP_LOGI("AbilityContextAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return ret; +} + +void AbilityContextAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AbilityContextAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent( + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} + +void AbilityContextAbility::ConnectCaseIndexOne() +{ + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::ConnectCaseIndexTwo() +{ + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::TestConnectAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + ConnectCaseIndexOne(); + break; + } + case CaseIndex::TWO: { + ConnectCaseIndexTwo(); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityContextConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityContextAbility::TestStopAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + default: + break; + } +} + +void AbilityContextAbility::DisconnectCaseIndexOne() +{ + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::DisconnectCaseIndexTwo() +{ + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + DisconnectCaseIndexOne(); + break; + } + case CaseIndex::TWO: { + DisconnectCaseIndexTwo(); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityContextAbility::TestStartAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->StopAbility(want); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->StopAbility(want); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + default: + break; + } +} + +void AbilityContextAbility::TestTerminateAbility() +{ + switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->StopAbility(want); + BaseAbility::GetContext()->TerminateAbility(); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->StopAbility(want); + BaseAbility::GetContext()->TerminateAbility(); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + default: + break; + } +} + +void AbilityContextAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI( + "AbilityContextAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("AbilityContextAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("AbilityContextAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_ABILITY_CONTEXT_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("AbilityContextAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", + target.c_str()); + } + } +} +REGISTER_AA(AbilityContextAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a25ab12d966902601d9023e2f6aaf47fc62cda4a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp @@ -0,0 +1,799 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_life_cycle_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int loopCnt = 3; +} +AbilityLifeCycleAbility::~AbilityLifeCycleAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AbilityLifeCycleAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AbilityLifeCycleAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + SubscribeEvent(); + + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifeCycleAbility::GetState(), "Init"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +bool AbilityLifeCycleAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AbilityLifeCycleAbility::OnStart(const Want &want) +{ + sequenceNumber_ = std::stoi(GetNoFromWantInfo(want)); + want_ = want; + APP_LOGI("AbilityLifeCycleAbility::OnStart"); + + BaseAbility::OnStart(want); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnStop() +{ + APP_LOGI("AbilityLifeCycleAbility::OnStop"); + BaseAbility::OnStop(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnActive() +{ + APP_LOGI("AbilityLifeCycleAbility::OnActive"); + BaseAbility::OnActive(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnInactive() +{ + APP_LOGI("AbilityLifeCycleAbility::OnInactive"); + BaseAbility::OnInactive(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnBackground() +{ + APP_LOGI("AbilityLifeCycleAbility::OnBackground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnForeground(const Want &want) +{ + APP_LOGI("AbilityLifeCycleAbility::OnForeground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnForeground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("AbilityLifeCycleAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +sptr AbilityLifeCycleAbility::OnConnect(const Want &want) +{ + APP_LOGI("AbilityLifeCycleAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); + return ret; +} + +void AbilityLifeCycleAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("AbilityLifeCycleAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::TestConnectAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::TWO: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::THREE: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } + break; + } + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) AbilityLifeCycleConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestConnectAbility"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestStopAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < loopCnt; i++) { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) AbilityLifeCycleConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestStartAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestStartAbility"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestTerminateAbility() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + break; + } + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleGetLifecycle() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + break; + } + case CaseIndex::TWO: { + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + break; + } + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + break; + } + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + break; + } + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + break; + } + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::GetLifecycleStateCaseOne() +{ + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); +} + +void AbilityLifeCycleAbility::TestLifeCycleGetLifecycleState() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + GetLifecycleStateCaseOne(); + break; + } + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + } + break; + } + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + break; + } + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + break; + } + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + break; + } + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + break; + } + case CaseIndex::SEVEN: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + break; + } + default: + break; + } +} + +void AbilityLifecycleLifecycleObserver::OnActive() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnActive"); +} + +void AbilityLifecycleLifecycleObserver::OnBackground() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnBackground"); +} + +void AbilityLifecycleLifecycleObserver::OnForeground(const Want &want) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnForeground"); +} + +void AbilityLifecycleLifecycleObserver::OnInactive() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnInactive"); +} + +void AbilityLifecycleLifecycleObserver::OnStart(const Want &want) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStart"); +} + +void AbilityLifecycleLifecycleObserver::OnStop() +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStop"); +} + +void AbilityLifecycleLifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void AbilityLifecycleLifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void AbilityLifeCycleAbility::TestLifeCycleAddObserver() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + break; + } + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::ONE; i++) { + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + break; + } + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::ONE; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + break; + } + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::ONE; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + break; + } + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->AddObserver(nullptr); + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleDispatchLifecycleOne() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleDispatchLifecycleTwo() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_START); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_STOP); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + case CaseIndex::SEVEN: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + case CaseIndex::EIGHT: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + case CaseIndex::NINE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbility::TestLifeCycleDispatchLifecycle() +{ + TestLifeCycleDispatchLifecycleOne(); + TestLifeCycleDispatchLifecycleTwo(); +} + +void AbilityLifeCycleAbility::TestLifeCycleRemoveObserver() +{ + switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + break; + } + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + break; + } + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + break; + } + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + break; + } + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + break; + } + default: + break; + } +} + +void AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI( + "AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("AbilityLifeCycleAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", + target.c_str()); + } + } +} +REGISTER_AA(AbilityLifeCycleAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/base_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/base_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89e59465ded5e4e0a7b1a166badc0ceaa81572cb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/base_ability.cpp @@ -0,0 +1,110 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "base_ability.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +void BaseAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("BaseAbility::Init called."); + + Ability::Init(abilityInfo, application, handler, token); +} + +void BaseAbility::OnStart(const Want &want) +{ + APP_LOGI("BaseAbility::OnStart"); + + Ability::OnStart(want); +} + +void BaseAbility::OnStop() +{ + APP_LOGI("BaseAbility::OnStop"); + + Ability::OnStop(); +} + +void BaseAbility::OnActive() +{ + APP_LOGI("BaseAbility::OnActive"); + + Ability::OnActive(); +} + +void BaseAbility::OnInactive() +{ + APP_LOGI("BaseAbility::OnInactive"); + + Ability::OnInactive(); +} + +void BaseAbility::OnBackground() +{ + APP_LOGI("BaseAbility::OnBackground"); + + Ability::OnBackground(); +} + +void BaseAbility::OnForeground(const Want &want) +{ + APP_LOGI("BaseAbility::OnForeground"); + + Ability::OnForeground(want); +} + +void BaseAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("BaseAbility::OnCommand"); + + Ability::OnCommand(want, restart, startId); +} + +sptr BaseAbility::OnConnect(const Want &want) +{ + APP_LOGI("BaseAbility::OnConnect"); + + sptr ret = Ability::OnConnect(want); + return ret; +} + +void BaseAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("BaseAbility::OnDisconnect"); + + Ability::OnDisconnect(want); +} + +void BaseAbility::OnNewWant(const Want &want) +{ + APP_LOGI("BaseAbility::OnNewWant"); + + Ability::OnNewWant(want); +} + +std::string BaseAbility::GetNoFromWantInfo(const Want &want) +{ + Want wantImpl(want); + return wantImpl.GetStringParam("No."); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_call_backs_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_call_backs_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ada1a15a3a814cdd138bcddfa543e30b852c522f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_call_backs_ability.cpp @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "life_cycle_call_backs_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +void ServiceLifecycleCallbacks::DoTask() +{ + if (!LifecycleCallbacksAbility::sequenceNumber_.empty()) { + switch ((CaseIndex)std::stoi(LifecycleCallbacksAbility::sequenceNumber_)) { + case CaseIndex::TWO: + PostTask(); + break; + case CaseIndex::THREE: + DoWhile(); + break; + case CaseIndex::SIX: + break; + default: + break; + } + } +} +void ServiceLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityStart"); +} + +void ServiceLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityInactive"); +} + +void ServiceLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityBackground"); +} + +void ServiceLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityForeground"); +} + +void ServiceLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityActive"); +} + +void ServiceLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + DoTask(); + TestUtils::PublishEvent(EVENT_RESP_LIFECYCLE_CALLBACK, 0, "OnAbilityStop"); +} + +void ServiceLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + DoTask(); +} + +LifecycleCallbacksAbility::~LifecycleCallbacksAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void LifecycleCallbacksAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("LifecycleCallbacksAbility::Init called."); + + Ability::Init(abilityInfo, application, handler, token); + + SubscribeEvent(); + lifecycleCallbacks_ = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(lifecycleCallbacks_); +} + +std::string LifecycleCallbacksAbility::GetNoFromWantInfo(const Want &want) +{ + Want wantImpl(want); + return wantImpl.GetStringParam("No."); +} + +void LifecycleCallbacksAbility::OnStart(const Want &want) +{ + APP_LOGI("LifecycleCallbacksAbility::OnStart"); + + sequenceNumber_ = GetNoFromWantInfo(want); + + Ability::OnStart(want); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); +} + +void LifecycleCallbacksAbility::StopSelfAbility() +{ + TerminateAbility(); +} + +void LifecycleCallbacksEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("LifecycleCallbacksEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("LifecycleCallbacksEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("LifecycleCallbacksEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI( + "LifecycleCallbacksEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +bool LifecycleCallbacksAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void LifecycleCallbacksAbility::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("LifecycleCallbacksAbility::OnCommand"); + + Ability::OnCommand(want, restart, startId); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void LifecycleCallbacksAbility::OnNewWant(const Want &want) +{ + APP_LOGI("LifecycleCallbacksAbility::OnNewWant"); + + Ability::OnNewWant(want); +} +void LifecycleCallbacksAbility::OnStop() +{ + APP_LOGI("LifecycleCallbacksAbility::OnStop"); + + Ability::OnStop(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void LifecycleCallbacksAbility::OnActive() +{ + APP_LOGI("LifecycleCallbacksAbility::OnActive"); + + Ability::OnActive(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void LifecycleCallbacksAbility::OnInactive() +{ + APP_LOGI("LifecycleCallbacksAbility::OnInactive"); + + Ability::OnInactive(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void LifecycleCallbacksAbility::OnBackground() +{ + APP_LOGI("LifecycleCallbacksAbility::OnBackground"); + + Ability::OnBackground(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, + AbilityLifecycleExecutor::LifecycleState::BACKGROUND, + "OnBackground"); +} + +REGISTER_AA(LifecycleCallbacksAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5559b0e1be5f0e2a32352b3690bb12496a31ea3 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp @@ -0,0 +1,777 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "life_cycle_observer_ability.h" +#include "app_log_wrapper.h" +#include "base_ability.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int loopCnt = 100; +} +void LifecycleObserverLifecycleObserver::DoTask() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::TWO: + PostTask(); + break; + case CaseIndex::THREE: + DoWhile(); + break; + case CaseIndex::SIX: + break; + default: + break; + } +} + +void LifecycleObserverLifecycleObserver::OnActive() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnActive"); +} + +void LifecycleObserverLifecycleObserver::OnBackground() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnBackground"); +} + +void LifecycleObserverLifecycleObserver::OnForeground(const Want &want) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnForeground"); +} + +void LifecycleObserverLifecycleObserver::OnInactive() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnInactive"); +} + +void LifecycleObserverLifecycleObserver::OnStart(const Want &want) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStart"); +} + +void LifecycleObserverLifecycleObserver::OnStop() +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStop"); +} + +void LifecycleObserverLifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void LifecycleObserverLifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + DoTask(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnStateChanged"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnAbilityStart"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnAbilityInactive"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnAbilityBackground"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnAbilityForeground"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnAbilityActive"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnAbilityStop"); +} + +void LifecycleObserverLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 0, "OnAbilitySaveState"); +} + +LifeCycleObserverAbility::~LifeCycleObserverAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void LifeCycleObserverAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("LifeCycleObserverAbility::Init called."); + BaseAbility::Init(abilityInfo, application, handler, token); + SubscribeEvent(); + lifecycleCallbacks_ = std::make_shared(); + GetApplication()->RegisterAbilityLifecycleCallbacks(lifecycleCallbacks_); + lifecycleObserver_ = std::make_shared(); + GetLifecycle()->AddObserver(lifecycleObserver_); + + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, + BaseAbility::GetLifecycle()->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); +} + +bool LifeCycleObserverAbility::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = *this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void LifeCycleObserverAbility::OnStart(const Want &want) +{ + sequenceNumber_ = std::stoi(GetNoFromWantInfo(want)); + want_ = want; + + BaseAbility::OnStart(want); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnStop() +{ + APP_LOGI("LifeCycleObserverAbility::OnStop"); + BaseAbility::OnStop(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnActive() +{ + APP_LOGI("LifeCycleObserverAbility::OnActive"); + BaseAbility::OnActive(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnInactive() +{ + APP_LOGI("LifeCycleObserverAbility::OnInactive"); + BaseAbility::OnInactive(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnBackground() +{ + APP_LOGI("LifeCycleObserverAbility::OnBackground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnForeground(const Want &want) +{ + APP_LOGI("LifeCycleObserverAbility::OnForeground"); + BaseAbility::OnBackground(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnForeground"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::OnCommand(const Want &want, bool restart, int startId) +{ + APP_LOGI("LifeCycleObserverAbility::OnCommand"); + + BaseAbility::OnCommand(want, restart, startId); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +sptr LifeCycleObserverAbility::OnConnect(const Want &want) +{ + APP_LOGI("LifeCycleObserverAbility::OnConnect"); + + sptr ret = BaseAbility::OnConnect(want); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); + return ret; +} + +void LifeCycleObserverAbility::OnDisconnect(const Want &want) +{ + APP_LOGI("LifeCycleObserverAbility::OnDisconnect"); + + BaseAbility::OnDisconnect(want); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); + + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycleState"); +} + +void LifeCycleObserverAbility::TestConnectAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::TWO: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::THREE: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } + } break; + case CaseIndex::FIVE: { + sptr stub(new (std::nothrow) LifeCycleObserverConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestConnectAbility"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestStopAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + bool ret = BaseAbility::GetContext()->StopAbility(want_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + bool ret = BaseAbility::GetContext()->StopAbility(want); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestStopAbility"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestDisconnectAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + stub_ = new (std::nothrow) LifeCycleObserverConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestStartAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->StartAbility(want_, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestStartAbility"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestTerminateAbility() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::TWO: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::THREE: { + MAP_STR_STR params; + Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + case CaseIndex::FOUR: { + for (int i = 0; i < (int)CaseIndex::THREE; i++) { + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } + } break; + case CaseIndex::FIVE: { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); + BaseAbility::GetContext()->StartAbility(want, 0); + BaseAbility::GetContext()->TerminateAbility(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestTerminateAbility"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleGetLifecycle() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::TWO: { + for (int i = 0; i < loopCnt; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent( + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, lifecycle->GetLifecycleState(), "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleGetLifecycleState() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::TWO: { + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + auto lifecycle = GetLifecycle(); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + lifecycle->AddObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + lifecycle->RemoveObserver(nullptr); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycleState"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleAddObserver() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->AddObserver(nullptr); + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleAddObserver"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleDispatchLifecycleOne() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleDispatchLifecycleTwo() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_START); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::SIX: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_STOP); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::SEVEN: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::EIGHT: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + case CaseIndex::NINE: { + auto lifecycle = GetLifecycle(); + lifecycle->DispatchLifecycle(LifeCycle::Event::UNDEFINED); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleDispatchLifecycle"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbility::TestLifeCycleDispatchLifecycle() +{ + TestLifeCycleDispatchLifecycleOne(); + TestLifeCycleDispatchLifecycleTwo(); +} + +void LifeCycleObserverAbility::TestLifeCycleRemoveObserver() +{ + switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { + case CaseIndex::ONE: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::TWO: { + auto lifecycle = GetLifecycle(); + std::shared_ptr lifecycleObserver = + std::make_shared(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::THREE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::FOUR: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + std::shared_ptr lifecycleObserver = + std::make_shared(); + lifecycle->AddObserver(lifecycleObserver); + lifecycle->RemoveObserver(lifecycleObserver); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + case CaseIndex::FIVE: { + auto lifecycle = GetLifecycle(); + for (int i = 0; i < (int)CaseIndex::HANDRED; i++) { + lifecycle->RemoveObserver(nullptr); + } + TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleRemoveObserver"); + } break; + default: + break; + } +} + +void LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI( + "LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME.c_str()) == 0) { + auto target = data.GetData(); + auto func = mapTestFunc_.find(target); + if (func != mapTestFunc_.end()) { + func->second(); + } else { + APP_LOGI("LifeCycleObserverAbilityEventSubscriber::OnReceiveEvent: CommonEventData error(%{public}s)", + target.c_str()); + } + } +} +REGISTER_AA(LifeCycleObserverAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6a74ab78d2ebe0a92e07d36ba8639bb0f2288da --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/test_utils.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f28083ee1cb8be55a264ce4dc9988ba125e37dd4 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsMissionStackTestConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsMissionStackTest\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsMissionStackTest") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + "${SUBDEMOSYSTEM_DIR}/src/third_ability.cpp", + ] + configs = [ ":amsMissionStackTestConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/config.json b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3967c8b6b8eba230f3586c5d35ca68f8459c69d9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/config.json @@ -0,0 +1,63 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.MissionStack", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.MissionStack.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Second Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ThirdAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Third Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..46403d06b73899a34093da2624180529467584b9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/main_ability.h @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + void MissionStackCase4(int code); + void MissionStackCase5(int code); + void MissionStackCase6(int code); + void MissionStackCase7(int code); + void MissionStackCase8(int code); + void MissionStackCase9(int code); + void MissionStackCase10(int code); + void MissionStackCase11(int code); + void MissionStackCase12(int code); + void MissionStackCase13(int code); + void MissionStackCase14(int code); + void MissionStackCase15(int code); + void MissionStackCase16(int code); + void MissionStackCase17(int code); + void MissionStackCase18(int code); + + void SaveAbilityStateCase1(int code); + void SaveAbilityStateCase2(int code); + void SaveAbilityStateCase3(int code); + + void RestoreAbilityStateCase1(int code); + void RestoreAbilityStateCase2(int code); + void RestoreAbilityStateCase3(int code); + + MainAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + [this](int code) { MissionStackCase4(code); }, + [this](int code) { MissionStackCase5(code); }, + [this](int code) { MissionStackCase6(code); }, + [this](int code) { MissionStackCase7(code); }, + [this](int code) { MissionStackCase8(code); }, + [this](int code) { MissionStackCase9(code); }, + [this](int code) { MissionStackCase10(code); }, + [this](int code) { MissionStackCase11(code); }, + [this](int code) { MissionStackCase12(code); }, + [this](int code) { MissionStackCase13(code); }, + [this](int code) { MissionStackCase14(code); }, + [this](int code) { MissionStackCase15(code); }, + [this](int code) { MissionStackCase16(code); }, + [this](int code) { MissionStackCase17(code); }, + [this](int code) { MissionStackCase18(code); }, + + }}, + {(int)TestAbilityState::OnSaveAbilityState, + { + [this](int code) { SaveAbilityStateCase1(code); }, + [this](int code) { SaveAbilityStateCase2(code); }, + [this](int code) { SaveAbilityStateCase3(code); }, + }}, + {(int)TestAbilityState::OnRestoreAbilityState, + { + [this](int code) { RestoreAbilityStateCase1(code); }, + [this](int code) { RestoreAbilityStateCase2(code); }, + [this](int code) { RestoreAbilityStateCase3(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + {"TestAbilityState", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..5c0477bfa3336a2c9b7650617b79a8d8fdc07b06 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/second_ability.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + void MissionStackCase4(int code); + void MissionStackCase5(int code); + void MissionStackCase6(int code); + void MissionStackCase7(int code); + void MissionStackCase8(int code); + void MissionStackCase9(int code); + void MissionStackCase10(int code); + void MissionStackCase11(int code); + void MissionStackCase12(int code); + void MissionStackCase13(int code); + void MissionStackCase14(int code); + void MissionStackCase15(int code); + void MissionStackCase16(int code); + void MissionStackCase17(int code); + void MissionStackCase18(int code); + + void SaveAbilityStateCase1(int code); + void SaveAbilityStateCase2(int code); + void SaveAbilityStateCase3(int code); + + void RestoreAbilityStateCase1(int code); + void RestoreAbilityStateCase2(int code); + void RestoreAbilityStateCase3(int code); + + SecondAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + [this](int code) { MissionStackCase4(code); }, + [this](int code) { MissionStackCase5(code); }, + [this](int code) { MissionStackCase6(code); }, + [this](int code) { MissionStackCase7(code); }, + [this](int code) { MissionStackCase8(code); }, + [this](int code) { MissionStackCase9(code); }, + [this](int code) { MissionStackCase10(code); }, + [this](int code) { MissionStackCase11(code); }, + [this](int code) { MissionStackCase12(code); }, + [this](int code) { MissionStackCase13(code); }, + [this](int code) { MissionStackCase14(code); }, + [this](int code) { MissionStackCase15(code); }, + [this](int code) { MissionStackCase16(code); }, + [this](int code) { MissionStackCase17(code); }, + [this](int code) { MissionStackCase18(code); }, + + }}, + {(int)TestAbilityState::OnSaveAbilityState, + { + [this](int code) { SaveAbilityStateCase1(code); }, + [this](int code) { SaveAbilityStateCase2(code); }, + [this](int code) { SaveAbilityStateCase3(code); }, + }}, + {(int)TestAbilityState::OnRestoreAbilityState, + { + [this](int code) { RestoreAbilityStateCase1(code); }, + [this](int code) { RestoreAbilityStateCase2(code); }, + [this](int code) { RestoreAbilityStateCase3(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + std::shared_ptr subscriber_; +}; +class SecondEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + {"TestAbilityState", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + secondAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + secondAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *secondAbility; + std::unordered_map> mapTestFunc_; + ~SecondEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/third_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..a91d270db86ddac23a41ea901f853f176308908c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/third_ability.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class ThirdEventSubscriber; +class ThirdAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + void MissionStackCase4(int code); + void MissionStackCase5(int code); + void MissionStackCase6(int code); + void MissionStackCase7(int code); + void MissionStackCase8(int code); + void MissionStackCase9(int code); + void MissionStackCase10(int code); + void MissionStackCase11(int code); + void MissionStackCase12(int code); + void MissionStackCase13(int code); + void MissionStackCase14(int code); + void MissionStackCase15(int code); + void MissionStackCase16(int code); + void MissionStackCase17(int code); + void MissionStackCase18(int code); + + ThirdAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + [this](int code) { MissionStackCase4(code); }, + [this](int code) { MissionStackCase5(code); }, + [this](int code) { MissionStackCase6(code); }, + [this](int code) { MissionStackCase7(code); }, + [this](int code) { MissionStackCase8(code); }, + [this](int code) { MissionStackCase9(code); }, + [this](int code) { MissionStackCase10(code); }, + [this](int code) { MissionStackCase11(code); }, + [this](int code) { MissionStackCase12(code); }, + [this](int code) { MissionStackCase13(code); }, + [this](int code) { MissionStackCase14(code); }, + [this](int code) { MissionStackCase15(code); }, + [this](int code) { MissionStackCase16(code); }, + [this](int code) { MissionStackCase17(code); }, + [this](int code) { MissionStackCase18(code); }, + + }}, + }; + } + + std::unordered_map>> mapCase_; + ~ThirdAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + std::shared_ptr subscriber_; +}; +class ThirdEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit ThirdEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + {"TestAbilityState", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + thirdAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + thirdAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + ThirdAbility *thirdAbility; + std::unordered_map> mapTestFunc_; + ~ThirdEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4084128d4e1da62e91814663c6cb68ddf9ba9415 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/main_ability.cpp @@ -0,0 +1,334 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnForeground"); +} + +void MainAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("MainAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnRestoreAbilityState"); +} +void MainAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("MainAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnSaveAbilityState"); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_MAIN, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_MAIN.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void MainAbility::MissionStackCase1(int code) +{ + APP_LOGI("MainAbility::MissionStackCase1"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase2(int code) +{ + APP_LOGI("MainAbility::MissionStackCase2"); + bool result = true; + LockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); + TerminateAbility(); +} +void MainAbility::MissionStackCase3(int code) +{ + APP_LOGI("MainAbility::MissionStackCase3"); + bool result = true; + LockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase5(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase6(int code) +{ + APP_LOGI("MainAbility::MissionStackCase6"); + bool result = true; + LockMission(); + std::map params; + Want want = TestUtils::MakeWant("", "ThirdAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase7(int code) +{ + APP_LOGI("MainAbility::MissionStackCase7"); + bool result = true; + LockMission(); + UnlockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase8(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase9(int code) +{ + APP_LOGI("MainAbility::MissionStackCase9"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase10(int code) +{ + APP_LOGI("MainAbility::MissionStackCase10"); + bool result = true; + int missionId = GetMissionId(); + result = missionId >= 0; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(missionId)); +} +void MainAbility::MissionStackCase11(int code) +{ + APP_LOGI("MainAbility::MissionStackCase11"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase12(int code) +{ + APP_LOGI("MainAbility::MissionStackCase12"); + bool result = true; + result = MoveMissionToEnd(true); + if (result) { + APP_LOGI("MainAbility::MissionStackCase12 MoveMissionToEnd(true)true ====> %{public}d", result); + } else { + APP_LOGI("MainAbility::MissionStackCase12 MoveMissionToEnd(true)false ====> %{public}d", result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase13(int code) +{ + APP_LOGI("MainAbility::MissionStackCase13"); + bool result = true; + result = MoveMissionToEnd(false); + if (result) { + APP_LOGI("MainAbility::MissionStackCase13 MoveMissionToEnd(false)true ====> %{public}d", result); + } else { + APP_LOGI("MainAbility::MissionStackCase13 MoveMissionToEnd(false)false ====> %{public}d", result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase14(int code) +{ + APP_LOGI("MainAbility::MissionStackCase14"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase15(int code) +{ + APP_LOGI("MainAbility::MissionStackCase15"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase16(int code) +{ + APP_LOGI("MainAbility::MissionStackCase16"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase17(int code) +{ + APP_LOGI("MainAbility::MissionStackCase17"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase18(int code) +{ + APP_LOGI("MainAbility::MissionStackCase18"); + bool result = true; + LockMission(); + result = MoveMissionToEnd(false); + if (result) { + APP_LOGI("MainAbility::MissionStackCase18 MoveMissionToEnd(false)true ====> %{public}d", result); + } else { + APP_LOGI("MainAbility::MissionStackCase18 MoveMissionToEnd(false)false ====> %{public}d", result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::SaveAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::SaveAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::SaveAbilityStateCase3(int code) +{ + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} + +void MainAbility::RestoreAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::RestoreAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::RestoreAbilityStateCase3(int code) +{ + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c56b71123e1fe14ba2002a5804f6eef2e3dd791 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/second_ability.cpp @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnStop"); +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnActive"); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnForeground"); +} + +void SecondAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("SecondAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnRestoreAbilityState"); +} +void SecondAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("SecondAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnSaveAbilityState"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->secondAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::MissionStackCase1(int code) +{ + bool result = true; + LockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); + TerminateAbility(); +} +void SecondAbility::MissionStackCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase5(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase6(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase7(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase8(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase9(int code) +{ + bool result = true; + LockMission(); + UnlockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); + TerminateAbility(); +} +void SecondAbility::MissionStackCase10(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase11(int code) +{ + bool result = true; + result = MoveMissionToEnd(false); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase12(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase13(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase14(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase14"); + bool result = true; + result = MoveMissionToEnd(true); + if (result) { + APP_LOGI("SecondAbility::MissionStackCase14 MoveMissionToEnd(true)true ====> %{public}d", result); + } else { + APP_LOGI("SecondAbility::MissionStackCase14 MoveMissionToEnd(true)false ====> %{public}d", result); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase15(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase15"); + bool result = true; + result = MoveMissionToEnd(false); + if (result) { + APP_LOGI("SecondAbility::MissionStackCase15 MoveMissionToEnd(false)true ====> %{public}d", result); + } else { + APP_LOGI("SecondAbility::MissionStackCase15 MoveMissionToEnd(false)false ====> %{public}d", result); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase16(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase16"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase17(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase17"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase18(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase18"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::SaveAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::SaveAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::SaveAbilityStateCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::RestoreAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::RestoreAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::RestoreAbilityStateCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); + TerminateAbility(); +} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/third_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/third_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59b7c1e79338b68ca791c1def3e16f89fc0b4b27 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/third_ability.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "third_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +void ThirdAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("ThirdAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +ThirdAbility::~ThirdAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ThirdAbility::OnStart(const Want &want) +{ + APP_LOGI("ThirdAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnStart"); +} + +void ThirdAbility::OnStop() +{ + APP_LOGI("ThirdAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnStop"); +} + +void ThirdAbility::OnActive() +{ + APP_LOGI("ThirdAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnActive"); +} + +void ThirdAbility::OnInactive() +{ + APP_LOGI("ThirdAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnInactive"); +} + +void ThirdAbility::OnBackground() +{ + APP_LOGI("ThirdAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnBackground"); +} + +void ThirdAbility::OnForeground(const Want &want) +{ + APP_LOGI("ThirdAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnForeground"); +} + +void ThirdAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("ThirdAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnRestoreAbilityState"); +} +void ThirdAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("ThirdAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnSaveAbilityState"); +} + +void ThirdAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_THIRD, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->thirdAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ThirdEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("ThirdEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("ThirdEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("ThirdEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_THIRD.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void ThirdAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("ThirdAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void ThirdAbility::MissionStackCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase5(int code) +{ + bool result = true; + LockMission(); + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase6(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase7(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase8(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase9(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase10(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase11(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase12(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase13(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase14(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase15(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase16(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase17(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase18(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +REGISTER_AA(ThirdAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..dbd22d08de76a1f60060a8a811ab94a029c4138a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsMissionStackTestSubsidiaryConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsMissionStackTestSubsidiary\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsMissionStackTestSubsidiary") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + "${SUBDEMOSYSTEM_DIR}/src/third_ability.cpp", + ] + configs = [ ":amsMissionStackTestSubsidiaryConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/config.json b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/config.json new file mode 100644 index 0000000000000000000000000000000000000000..727170594afef8424401f8b4c4cc6deb5ec521ae --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/config.json @@ -0,0 +1,63 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.MissionStackSubsidiary", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.MissionStackSubsidiary.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "MainAbility label", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "SecondAbility label", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ThirdAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "ThirdAbility label", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..789530e3d5b7b51c90f4fd1284804438973373ee --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/main_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_FWK_MISSIONSTACK_TEST_MAIN_ABILITY_H +#define AMS_FWK_MISSIONSTACK_TEST_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class MainAbilityEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + + MainAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + std::string callbackSeq; + std::string callbackUpdated; +}; +class MainAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit MainAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~MainAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_FWK_MISSIONSTACK_TEST_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..f425db4c8b65882acddf34e58b985ae0cde5aec8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/second_ability.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_FWK_MISSIONSTACK_TEST_SECOND_ABILITY_H +#define AMS_FWK_MISSIONSTACK_TEST_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondAbilityEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void MissionStackCase1(int code); + void MissionStackCase2(int code); + + SecondAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class SecondAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + secondAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + secondAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *secondAbility; + std::unordered_map> mapTestFunc_; + ~SecondAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_FWK_MISSIONSTACK_TEST_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/third_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..58342d5889c81e84c05af532282694b2f51c5254 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/third_ability.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_FWK_MISSIONSTACK_TEST_THIRD_ABILITY_H +#define AMS_FWK_MISSIONSTACK_TEST_THIRD_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class ThirdAbilityEventSubscriber; +class ThirdAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + ThirdAbility() + { + mapCase_ = {}; + } + + std::unordered_map>> mapCase_; + ~ThirdAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class ThirdAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit ThirdAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = {}; + thirdAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + thirdAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + ThirdAbility *thirdAbility; + std::unordered_map> mapTestFunc_; + ~ThirdAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_FWK_MISSIONSTACK_TEST_THIRD_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1494ddd3b7a09eeaa4194fd7968f4e7ec230b612 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/main_ability.cpp @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq = "OnStop"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq = "OnActive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("MainAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; // UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, callbackUpdated); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnForeground"); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_MAIN_SUBSIDIARY, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void MainAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_MAIN_SUBSIDIARY.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void MainAbility::MissionStackCase1(int code) +{ + APP_LOGI("MainAbility::MissionStackCase1"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStackSubsidiary", params); + AbilityContext::StartAbility(want, 1); + + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_SUBSIDIARY, code, std::to_string(result)); +} + +void MainAbility::MissionStackCase2(int code) +{ + APP_LOGI("MainAbility::MissionStackCase2"); + bool result = true; + result = MoveMissionToEnd(true); + if (result) { + APP_LOGI("MainAbility::MissionStackCase2 MoveMissionToEnd(true)true ====> %{public}d", result); + } else { + APP_LOGI("MainAbility::MissionStackCase2 MoveMissionToEnd(true)false ====> %{public}d", result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_SUBSIDIARY, code, std::to_string(result)); +} +void MainAbility::MissionStackCase3(int code) +{ + APP_LOGI("MainAbility::MissionStackCase3"); + bool result = true; + result = MoveMissionToEnd(false); + if (result) { + APP_LOGI("MainAbility::MissionStackCase3 MoveMissionToEnd(false)true ====> %{public}d", result); + } else { + APP_LOGI("MainAbility::MissionStackCase3 MoveMissionToEnd(false)false ====> %{public}d", result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_SUBSIDIARY, code, std::to_string(result)); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..913eedc54acf04cf9521dd87979d5fba5a070e8a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/second_ability.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq = "OnStop"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq = "OnActive"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("SecondAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; // UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, callbackUpdated); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnForeground"); +} + +void SecondAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("SecondAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent( + g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnRestoreAbilityState"); +} +void SecondAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("SecondAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent( + g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnSaveAbilityState"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND_SUBSIDIARY, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->secondAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::MissionStackCase1(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase1====<"); + bool result = true; + result = true; + + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::MissionStackCase2(int code) +{ + bool result = true; + result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/third_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/third_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b15f3e21b415e1e4ce0bc37358fc6153e595080e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/third_ability.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "third_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void ThirdAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("ThirdAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +ThirdAbility::~ThirdAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ThirdAbility::OnStart(const Want &want) +{ + APP_LOGI("ThirdAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnStart"); +} + +void ThirdAbility::OnStop() +{ + APP_LOGI("ThirdAbility::OnStop"); + Ability::OnStop(); + callbackSeq += "OnStop"; // OnInactiveOnBackgroundOnStop + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void ThirdAbility::OnActive() +{ + APP_LOGI("ThirdAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; // OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void ThirdAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("ThirdAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; // UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackUpdated); +} + +void ThirdAbility::OnInactive() +{ + APP_LOGI("ThirdAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnInactive"); +} + +void ThirdAbility::OnBackground() +{ + APP_LOGI("ThirdAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnBackground"); +} + +void ThirdAbility::OnForeground(const Want &want) +{ + APP_LOGI("ThirdAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnForeground"); +} + +void ThirdAbility::SubscribeEvent() +{ + std::vector eventList = { + // g_EVENT_REQU_THIRD, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->thirdAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ThirdAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); +} + +void ThirdAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("ThirdAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +REGISTER_AA(ThirdAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1e0fab8598d55dcc96693697267efddc809957e7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsStDataAbility" +EVENT_DIR = "//base/notification/ces_standard/cesfwk" + +config("verify_act_ability_config") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${EVENT_DIR}/kits/native/include", + ] + defines = [ + "APP_LOG_TAG = \"amsStDataAbility\"", + "LOG_DOMAIN = 0xD002200", + ] +} +config("verify_act_ability_public_config") { + visibility = [ ":*" ] + include_dirs = [] +} +ohos_shared_library("amsStDataAbility") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/verify_act_data_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_data_ability2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_page_ability.cpp", + ] + configs = [ ":verify_act_ability_config" ] + public_configs = [ ":verify_act_ability_public_config" ] + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", + "//base/notification/ces_standard/interfaces/kits/napi/common_event:commonevent", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + public_deps = [ "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + subsystem_name = "amssystemtestability" + + #part_name = "ability_runtime" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/config.json b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c725baad078df8b80f6bfc1776347951e16ebc3f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/config.json @@ -0,0 +1,63 @@ +{ + "app":{ + "bundleName": "com.ix.verify.act", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.VerifyActAbility.src", + "name":"VerifyActFirstAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "VerifyActPageAbility", + "icon": "$media:snowflakes", + "label": "VerifyActPageAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "srcLanguage": "c++", + "visible": true + }, + { + "name": "VerifyActDataAbility", + "icon": "$media:snowball", + "label": "Data Firs Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "uri": "dataability://com.ix.VerifyActDataAbility", + "srcLanguage": "c++", + "visible": true + }, + { + "name": "VerifyActDataAbility2", + "icon": "$media:snowball", + "label": "Data Firs Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "uri": "dataability://com.ix.VerifyActDataAbility2", + "srcLanguage": "c++", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability.h b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..b8967ce1f7bf707f6cd1a4b0b590a8807a824ad6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 VERIFY_ACT_DATA_ABILITY_H +#define VERIFY_ACT_DATA_ABILITY_H +#include "ability.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" + +namespace OHOS { +namespace NativeRdb { +class AbsSharedResultSet; +class DataAbilityPredicates; +class ValuesBucket; +} // namespace NativeRdb +namespace AppExecFwk { +class VerifyActDataAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual std::shared_ptr Query(const Uri &uri, + const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + + virtual std::string GetType(const Uri &uri) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + + virtual int BatchInsert(const Uri &uri, const std::vector &values) override; + + std::vector> sharedList_; +}; + +class InsertTestOpenCallback : public NativeRdb::RdbOpenCallback { +public: + int OnCreate(NativeRdb::RdbStore &rdbStore) override; + int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; + static const std::string CREATE_TABLE_TEST; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // VERIFY_ACT_DATA_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability2.h b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability2.h new file mode 100644 index 0000000000000000000000000000000000000000..eba0a04bdc8b458b9001a91df9099580e142faf6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability2.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 VERIFY_ACT_DATA_ABILITY2_H +#define VERIFY_ACT_DATA_ABILITY2_H +#include "ability.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" + +namespace OHOS { +namespace NativeRdb { +class AbsSharedResultSet; +class DataAbilityPredicates; +class ValuesBucket; +} // namespace NativeRdb +namespace AppExecFwk { +class VerifyActDataAbility2 : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual std::shared_ptr Query(const Uri &uri, + const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + + virtual std::string GetType(const Uri &uri) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + + virtual int BatchInsert(const Uri &uri, const std::vector &values) override; + + std::vector> sharedList_; +}; + +class InsertTestOpenCallback2 : public NativeRdb::RdbOpenCallback { +public: + int OnCreate(NativeRdb::RdbStore &rdbStore) override; + int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; + static const std::string CREATE_TABLE_TEST; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // VERIFY_ACT_DATA_ABILITY2_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_page_ability.h b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_page_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..3863c0dc4cca6c556ea0035e81b17391f91f87bb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_page_ability.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 VERIFY_ACT_PAGE_ABILITY_H +#define VERIFY_ACT_PAGE_ABILITY_H +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +namespace { +const int INSERT = 0; +const int DELETE = 1; +const int UPDATE = 2; +const int QUERY = 3; +const int GETFILETYPES = 4; +const int OPENFILE = 5; +} // namespace +class CommentDataAbilityTest : public EventFwk::CommonEventSubscriber { +public: + CommentDataAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + std::weak_ptr DataAbility_; +}; + +class VerifyActPageAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + std::shared_ptr subscriberDataAbility = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // VERIFY_ACT_PAGE_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_service_ability.h b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_service_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..dc740e43a58dee74cfe7d3a38fd503e4045ec222 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_service_ability.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 VERIFY_ACT_SERVICE_ABILITY_H +#define VERIFY_ACT_SERVICE_ABILITY_H +#include "ability.h" + +namespace OHOS { +namespace AppExecFwk { +class VerifyActServiceAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + + std::string Split(std::string &str, std::string delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // VERIFY_ACT_SERVICE_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5bcbb9676e7a1808257a100d3fb31d57175fd1e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +#include "app_log_wrapper.h" +#include "ability_loader.h" +#include "verify_act_data_ability.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static std::shared_ptr testStore; +static const std::string RDB_TEST_PATH = "/data/test/"; +static const std::string DATABASE_FILE_NAME = "insert_test.db"; +static const std::string DATABASE_NAME = RDB_TEST_PATH + "insert_test.db"; +static const int defaultReturn = 1; +} + +const std::string InsertTestOpenCallback::CREATE_TABLE_TEST = + std::string("CREATE TABLE IF NOT EXISTS test ") + std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, age INTEGER, salary " + "REAL, blobType BLOB)"); + +int InsertTestOpenCallback::OnCreate(NativeRdb::RdbStore &store) +{ + return store.ExecuteSql(CREATE_TABLE_TEST); +} + +int InsertTestOpenCallback::OnUpgrade(NativeRdb::RdbStore &store, int oldVersion, int newVersion) +{ + return 0; +} + +void VerifyActDataAbility::OnStart(const Want &want) +{ + APP_LOGI("VerifyActDataAbility OnStart"); + sharedList_.clear(); + Ability::OnStart(want); +} + +int VerifyActDataAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + return defaultReturn; +} + +std::shared_ptr VerifyActDataAbility::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + int errCode = 0; + std::string dbDir = GetDatabaseDir(); + NativeRdb::RdbStoreConfig config(dbDir + "/" + DATABASE_FILE_NAME); + InsertTestOpenCallback helper; + testStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); + APP_LOGI("VerifyActDataAbility <<<>>> Patch %{public}s", (dbDir + "/" + DATABASE_FILE_NAME).c_str()); + + int64_t id; + NativeRdb::ValuesBucket values; + int idValue = 1; + int age = 18; + double salary = 100.5; + + values.PutInt("id", idValue); + values.PutString("name", std::string("zhangsan")); + values.PutInt("age", age); + values.PutDouble("salary", salary); + values.PutBlob("blobType", std::vector {1, 2, 3}); + + if (testStore == nullptr) { + APP_LOGI("VerifyActDataAbility <<<>>> testStore is nullptr, data will be empty"); + return nullptr; + } + + if (testStore->Replace(id, "test", values) != 0) { + APP_LOGE("VerifyActDataAbility <<<>>> store->Replace Error"); + return nullptr; + } + + std::unique_ptr rresultSet = + testStore->QuerySql("SELECT * FROM test WHERE name = ?", std::vector {"zhangsan"}); + if (rresultSet == nullptr) { + APP_LOGE("VerifyActDataAbility <<<>>> rresultSet is nullptr"); + return nullptr; + } + + std::shared_ptr ret(rresultSet.release()); + sharedList_.push_back(ret); + return ret; +} + +int VerifyActDataAbility::Update( + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + return defaultReturn; +} +int VerifyActDataAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + return defaultReturn; +} +std::string VerifyActDataAbility::GetType(const Uri &uri) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + std::string retval(uri.ToString()); + return retval; +} +int VerifyActDataAbility::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + return 0; +} +int VerifyActDataAbility::BatchInsert(const Uri &uri, const std::vector &values) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + return Ability::BatchInsert(uri, values); +} + +REGISTER_AA(VerifyActDataAbility); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability2.cpp b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51606531b0c3184d3d03184fe7f6dab6e9b9395c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability2.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +#include "app_log_wrapper.h" +#include "ability_loader.h" +#include "verify_act_data_ability2.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +static std::shared_ptr testStore; +static const std::string RDB_TEST_PATH = "/data/test/"; +static const std::string DATABASE_FILE_NAME = "insert_test.db"; +static const std::string DATABASE_NAME = RDB_TEST_PATH + "insert_test.db"; +static const int defaultReturn = 1; +} + +const std::string InsertTestOpenCallback2::CREATE_TABLE_TEST = + std::string("CREATE TABLE IF NOT EXISTS test ") + std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, age INTEGER, salary " + "REAL, blobType BLOB)"); + +int InsertTestOpenCallback2::OnCreate(NativeRdb::RdbStore &store) +{ + return store.ExecuteSql(CREATE_TABLE_TEST); +} + +int InsertTestOpenCallback2::OnUpgrade(NativeRdb::RdbStore &store, int oldVersion, int newVersion) +{ + return 0; +} + +void VerifyActDataAbility2::OnStart(const Want &want) +{ + APP_LOGI("VerifyActDataAbility2 OnStart"); + sharedList_.clear(); + Ability::OnStart(want); +} + +int VerifyActDataAbility2::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("VerifyActDataAbility2 <<<>>>"); + return defaultReturn; +} + +std::shared_ptr VerifyActDataAbility2::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + int errCode = 0; + std::string dbDir = GetDatabaseDir(); + NativeRdb::RdbStoreConfig config(dbDir + "/" + DATABASE_FILE_NAME); + InsertTestOpenCallback2 helper; + testStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); + APP_LOGI("VerifyActDataAbility2 <<<>>> Patch %{public}s", (dbDir + "/" + DATABASE_FILE_NAME).c_str()); + + int64_t id; + NativeRdb::ValuesBucket values; + int idValue = 1; + int age = 18; + double salary = 100.5; + + values.PutInt("id", idValue); + values.PutString("name", std::string("zhangsan")); + values.PutInt("age", age); + values.PutDouble("salary", salary); + values.PutBlob("blobType", std::vector {1, 2, 3}); + + if (testStore == nullptr) { + APP_LOGI("VerifyActDataAbility2 <<<>>> testStore is nullptr, data will be empty"); + return nullptr; + } + + if (testStore->Replace(id, "test", values) != 0) { + APP_LOGE("VerifyActDataAbility2 <<<>>> store->Replace Error"); + return nullptr; + } + + std::unique_ptr rresultSet = + testStore->QuerySql("SELECT * FROM test WHERE name = ?", std::vector {"zhangsan"}); + if (rresultSet == nullptr) { + APP_LOGE("VerifyActDataAbility2 <<<>>> rresultSet is nullptr"); + return nullptr; + } + + APP_LOGI("VerifyActDataAbility2 <<<>>> Marshalling Object"); + std::shared_ptr ret(rresultSet.release()); + sharedList_.push_back(ret); + return ret; +} + +int VerifyActDataAbility2::Update( + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("VerifyActDataAbility2 <<<>>>"); + return defaultReturn; +} +int VerifyActDataAbility2::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("VerifyActDataAbility2 <<<>>>"); + return defaultReturn; +} +std::string VerifyActDataAbility2::GetType(const Uri &uri) +{ + APP_LOGI("VerifyActDataAbility2 <<<>>>"); + std::string retval(uri.ToString()); + return retval; +} +int VerifyActDataAbility2::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("VerifyActDataAbility2 <<<>>>"); + return 0; +} +int VerifyActDataAbility2::BatchInsert(const Uri &uri, const std::vector &values) +{ + APP_LOGI("VerifyActDataAbility2 <<<>>>"); + return Ability::BatchInsert(uri, values); +} + +REGISTER_AA(VerifyActDataAbility2); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_page_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_page_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c4790a5f54e952b2135ee279c8b1cffd1ce35ca --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_page_ability.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + +#include "app_log_wrapper.h" +#include "verify_act_page_ability.h" + +namespace OHOS { +namespace AppExecFwk { +void VerifyActPageAbility::OnStart(const Want &want) +{ + APP_LOGI("----------VerifyActPageAbility::onStart begin----------"); + // Test DataAbility + EventFwk::MatchingSkills MatchingSkillsDataAbility; + MatchingSkillsDataAbility.AddEvent("Test_DataAbility"); + EventFwk::CommonEventSubscribeInfo subscriberInfoDataAbility(MatchingSkillsDataAbility); + subscriberDataAbility = std::make_shared(subscriberInfoDataAbility); + EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberDataAbility); + subscriberDataAbility->DataAbility_ = Ability::GetContext(); + + APP_LOGI("----------VerifyActPageAbility::onStart end----------"); + Ability::OnStart(want); +} +void VerifyActPageAbility::OnStop() +{ + APP_LOGI("----------VerifyActPageAbility::onStop begin----------"); + if (subscriberDataAbility != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriberDataAbility); + } + APP_LOGI("----------VerifyActPageAbility::onStop end----------"); + APP_LOGI("----------VerifyActPageAbility::onStop TimerThreadDestoryBegin----------"); + APP_LOGI("----------VerifyActPageAbility::onStop TimerThreadDestoryEnd----------"); + Ability::OnStop(); +} +void VerifyActPageAbility::OnActive() +{ + APP_LOGI("----------VerifyActPageAbility::OnActive begin----------"); + APP_LOGI("----------VerifyActPageAbility::OnActive end----------"); + Ability::OnActive(); +} +void VerifyActPageAbility::OnInactive() +{ + APP_LOGI("----------VerifyActPageAbility::OnInactive begin----------"); + APP_LOGI("----------VerifyActPageAbility::OnInactive end----------"); + Ability::OnInactive(); +} +void VerifyActPageAbility::OnBackground() +{ + APP_LOGI("----------VerifyActPageAbility::OnBackground begin----------"); + APP_LOGI("----------VerifyActPageAbility::OnBackground end----------"); + Ability::OnBackground(); +} +void VerifyActPageAbility::OnForeground(const Want &want) +{ + APP_LOGI("----------VerifyActPageAbility::OnForeground begin----------"); + APP_LOGI("----------VerifyActPageAbility::OnForeground end----------"); + Ability::OnForeground(want); +} +void CommentDataAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + APP_LOGI("----------OnReceiveEvent---------DataAbility_%{public}ld", DataAbility_.use_count()); + auto dataAbility = DataAbility_.lock(); + if (dataAbility == nullptr) { + return; + } + APP_LOGI("----------OnReceiveEvent----------dataAbility%{public}ld", dataAbility.use_count()); + std::shared_ptr uri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + std::shared_ptr helper = DataAbilityHelper::Creator(dataAbility, uri, false); + if (helper != nullptr) { + APP_LOGI("-----------OnReceiveEvent helper isn't null-----------"); + Uri uri_DataAbility("dataability:///com.ix.VerifyActDataAbility"); + APP_LOGI("-----------OnReceiveEvent data.GetCode() ====%{public}d ---------", data.GetCode()); + switch (data.GetCode()) { + case INSERT: { + NativeRdb::ValuesBucket valueBucket; + int result = helper->Insert(uri_DataAbility, valueBucket); + APP_LOGI("-----------insertTest::OnReceiveEvent result = %{public}d", result); + break; + } + case DELETE: { + NativeRdb::DataAbilityPredicates dataAbilityPredicate("dumy Predicates"); + int result = helper->Delete(uri_DataAbility, dataAbilityPredicate); + APP_LOGI("-----------deleteTest::OnReceiveEvent result = %{public}d", result); + break; + } + default: + break; + } + } +} +REGISTER_AA(VerifyActPageAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..a276b31bf2863e24c3a2e9b5cf06e259a17af64e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestA" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestA\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsSystemTestA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilitya1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilitya2.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestAConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..98a5a7b945f85701a3f5089b47b7dd60c25b33fe --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/config.json @@ -0,0 +1,51 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appA", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestA.src", + "name":"AmsSystemTestA", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityA1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityA1 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityA2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityA2 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/include/amsstabilitya1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/include/amsstabilitya1.h new file mode 100644 index 0000000000000000000000000000000000000000..cd9c821e3d2e9f1860b28043f6410e7134faa9e7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/include/amsstabilitya1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_A1_ +#define _AMS_ST_ABILITY_A1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityA1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_A1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/include/amsstabilitya2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/include/amsstabilitya2.h new file mode 100644 index 0000000000000000000000000000000000000000..6ca95cad8abfda3c77a8343398aeaf62fcbc82ae --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/include/amsstabilitya2.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_A2_ +#define _AMS_ST_ABILITY_A2_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityA2 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_A2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c7a0d712da3745eb548ee092d0cefa755d3a876 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya1.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilitya1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityA1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityA1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityA1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityA1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityA1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityA1::OnStop() +{ + APP_LOGI("AmsStAbilityA1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityA1::OnActive() +{ + APP_LOGI("AmsStAbilityA1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityA1::OnInactive() +{ + APP_LOGI("AmsStAbilityA1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityA1::OnBackground() +{ + APP_LOGI("AmsStAbilityA1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityA1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityA1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92f5ee7d67a389e13bee447b9f695edfec3f12d5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya2.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilitya2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityA2::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityA2::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityA2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityA2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityA2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityA2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityA2::OnStop() +{ + APP_LOGI("AmsStAbilityA2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityA2::OnActive() +{ + APP_LOGI("AmsStAbilityA2::OnActive"); + Ability::OnActive(); + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityA2::OnInactive() +{ + APP_LOGI("AmsStAbilityA2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityA2::OnBackground() +{ + APP_LOGI("AmsStAbilityA2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityA2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityA2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityA2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..82e7de10039b9d20d55100100bfca4ccf28de164 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestB" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestB\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityb1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestBConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..55504bf89d47526229ad540b7ffb7f71f40e2ead --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appB", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestB.src", + "name":"AmsSystemTestB", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityB1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStAbilityB1 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/include/amsstabilityb1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/include/amsstabilityb1.h new file mode 100644 index 0000000000000000000000000000000000000000..001bd07cdc7cd43bdf115ab764aef0492f8c7b13 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/include/amsstabilityb1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_B1_ +#define _AMS_ST_ABILITY_B1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityB1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_B1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/src/amsstabilityb1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/src/amsstabilityb1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..772751a38ea2095b304a3ee6cf859422ff594ea8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/src/amsstabilityb1.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityb1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityB1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityB1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityB1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityB1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityB1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityB1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityB1::OnStop() +{ + APP_LOGI("AmsStAbilityB1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityB1::OnActive() +{ + APP_LOGI("AmsStAbilityB1::OnActive"); + Ability::OnActive(); + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityB1::OnInactive() +{ + APP_LOGI("AmsStAbilityB1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityB1::OnBackground() +{ + APP_LOGI("AmsStAbilityB1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityB1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityB1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityB1) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..40384743d72ce0cf66ff5437c91110cf81fcfe03 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestC" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestC\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestC") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityc1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityc2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityc3.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f41686d598debb9293a1e65d298d1177273fb2bb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/config.json @@ -0,0 +1,61 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appC", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestC.src", + "name":"AmsSystemTestC", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityC1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityC1 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityC2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityC2 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityC3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityC3 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc1.h new file mode 100644 index 0000000000000000000000000000000000000000..3ba74f6a487922e2620c5882609338b60a3055ae --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_C1_ +#define _AMS_ST_ABILITY_C1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityC1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_C1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc2.h new file mode 100644 index 0000000000000000000000000000000000000000..4b362668af54a33fd4f3880892a6dfc088886a66 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc2.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_C2_ +#define _AMS_ST_ABILITY_C2_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityC2 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_C2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc3.h new file mode 100644 index 0000000000000000000000000000000000000000..9dde40b58aaf413c76e19f15421b018de8202857 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/include/amsstabilityc3.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_C3_ +#define _AMS_ST_ABILITY_C3_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityC3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_C3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd43e18e9d43c87ca012893476c1a93cf2e6a8e5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc1.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityc1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityC1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityC1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityC1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityC1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityC1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityC1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityC1::OnStop() +{ + APP_LOGI("AmsStAbilityC1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityC1::OnActive() +{ + APP_LOGI("AmsStAbilityC1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityC1::OnInactive() +{ + APP_LOGI("AmsStAbilityC1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityC1::OnBackground() +{ + APP_LOGI("AmsStAbilityC1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityC1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityC1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityC1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71f932129b4291b0e4ae25fbe6e9b2b5291e4c1c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc2.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityc2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityC2::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityC2::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityC2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityC2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityC2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityC2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityC2::OnStop() +{ + APP_LOGI("AmsStAbilityC2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityC2::OnActive() +{ + APP_LOGI("AmsStAbilityC2::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityC2::OnInactive() +{ + APP_LOGI("AmsStAbilityC2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityC2::OnBackground() +{ + APP_LOGI("AmsStAbilityC2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityC2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityC2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityC2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fd4ca9f158feaf8966519b19eb48930ac63603b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc3.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityc3.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityC3::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityC3::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityC3::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityC3::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityC3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityC3::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityC3::OnStop() +{ + APP_LOGI("AmsStAbilityC3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityC3::OnActive() +{ + APP_LOGI("AmsStAbilityC3::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityC3::OnInactive() +{ + APP_LOGI("AmsStAbilityC3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityC3::OnBackground() +{ + APP_LOGI("AmsStAbilityC3::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityC3::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityC3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityC3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..94a36d50c8e5517ff715e4d3600f7f06831e5cf8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestD" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestDConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestD\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestD") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityd1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityd2.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestDConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d6779121b3edf61c83c1634265fe5ec5d32d8362 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/config.json @@ -0,0 +1,51 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appD", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestD.src", + "name":"AmsSystemTestD", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityD1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityD1 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityD2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityD2 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/include/amsstabilityd1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/include/amsstabilityd1.h new file mode 100644 index 0000000000000000000000000000000000000000..0224cc955c82bb4ee4da8667069fe30334dc4269 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/include/amsstabilityd1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_D1_ +#define _AMS_ST_ABILITY_D1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityD1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_D1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/include/amsstabilityd2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/include/amsstabilityd2.h new file mode 100644 index 0000000000000000000000000000000000000000..d861aefff8e873a799594b5e4a95bff60c267df0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/include/amsstabilityd2.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_D2_ +#define _AMS_ST_ABILITY_D2_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityD2 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_D2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eaf945217286deb1d812524c1f1955c5748e206d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd1.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityd1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityD1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityD1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityD1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityD1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityD1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityD1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityD1::OnStop() +{ + APP_LOGI("AmsStAbilityD1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityD1::OnActive() +{ + APP_LOGI("AmsStAbilityD1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityD1::OnInactive() +{ + APP_LOGI("AmsStAbilityD1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityD1::OnBackground() +{ + APP_LOGI("AmsStAbilityD1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityD1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityD1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityD1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e824e91a27b74409ee5fbd9953891efb88695d62 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd2.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityd2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityD2::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityD2::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityD2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityD2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityD2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityD2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityD2::OnStop() +{ + APP_LOGI("AmsStAbilityD2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityD2::OnActive() +{ + APP_LOGI("AmsStAbilityD2::OnActive"); + Ability::OnActive(); + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityD2::OnInactive() +{ + APP_LOGI("AmsStAbilityD2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityD2::OnBackground() +{ + APP_LOGI("AmsStAbilityD2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityD2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityD2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityD2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..1ec8d7cbe5a9d8a3458562a3c9ef1913e6ac964d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestDFX" +SUBST_TOOLS_DIR = "${system_test_app_path}/tools" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestDFX\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestDFX") { + sources = [ + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + "${subdemosystem_path}/src/ams_dfx_st_service_ability_a1.cpp", + "${subdemosystem_path}/src/ams_dfx_st_service_ability_a2.cpp", + ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/config.json new file mode 100644 index 0000000000000000000000000000000000000000..dfac5dc9cbc625c9b293538a58244c74e5c35ca5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/config.json @@ -0,0 +1,51 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appDFX", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsStAbilityDFX.src", + "name":"AmsStAbilityDFX", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsDfxStServiceAbilityA1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsDfxStServiceAbilityA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "AmsDfxStServiceAbilityA2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsDfxStServiceAbilityA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a1.h new file mode 100644 index 0000000000000000000000000000000000000000..e8f39300abd178fccd0c26f9df7d7d6680e79cf1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a1.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_DFX_ST_SERVICE_ABILITY_A1_ +#define AMS_DFX_ST_SERVICE_ABILITY_A1_ +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsDfxStServiceAbilityA1 : public Ability { +public: + ~AmsDfxStServiceAbilityA1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_DFX_ST_SERVICE_ABILITY_A1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a2.h new file mode 100644 index 0000000000000000000000000000000000000000..127bc2c473f20d3b0090e072d20527c809d790cf --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a2.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_DFX_ST_SERVICE_ABILITY_A2_ +#define AMS_DFX_ST_SERVICE_ABILITY_A2_ +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsDfxStServiceAbilityA2 : public Ability { +public: + ~AmsDfxStServiceAbilityA2(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_DFX_ST_SERVICE_ABILITY_A2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97c7e6002d7764711ac9e1f3079886e3091ed0f7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a1.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_dfx_st_service_ability_a1.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +AmsDfxStServiceAbilityA1::~AmsDfxStServiceAbilityA1() +{} + +void AmsDfxStServiceAbilityA1::OnStart(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsDfxStServiceAbilityA1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnCommand"); + + Ability::OnCommand(want, restart, startId); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); +} + +void AmsDfxStServiceAbilityA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnNewWant"); + + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsDfxStServiceAbilityA1::OnStop() +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnStop"); + + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsDfxStServiceAbilityA1::OnActive() +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnActive"); + + Ability::OnActive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsDfxStServiceAbilityA1::OnInactive() +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnInactive"); + + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsDfxStServiceAbilityA1::OnBackground() +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnBackground"); + + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +sptr AmsDfxStServiceAbilityA1::OnConnect(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnConnect"); + + sptr ret = Ability::OnConnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnConnectCount(), eventData); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::CONNECT_TIMEOUT)); + return ret; +} + +void AmsDfxStServiceAbilityA1::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA1::OnDisconnect"); + + Ability::OnDisconnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnDisconnectCount(), eventData); +} + +REGISTER_AA(AmsDfxStServiceAbilityA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f2358f9f256ce1289c399423c443e67e54fea8e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a2.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_dfx_st_service_ability_a2.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +AmsDfxStServiceAbilityA2::~AmsDfxStServiceAbilityA2() +{} + +void AmsDfxStServiceAbilityA2::OnStart(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsDfxStServiceAbilityA2::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnCommand"); + + Ability::OnCommand(want, restart, startId); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); +} + +void AmsDfxStServiceAbilityA2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnNewWant"); + + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsDfxStServiceAbilityA2::OnStop() +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnStop"); + + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsDfxStServiceAbilityA2::OnActive() +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnActive"); + + Ability::OnActive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsDfxStServiceAbilityA2::OnInactive() +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnInactive"); + + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsDfxStServiceAbilityA2::OnBackground() +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnBackground"); + + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +sptr AmsDfxStServiceAbilityA2::OnConnect(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnConnect"); + + sptr ret = Ability::OnConnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnConnectCount(), eventData); + return ret; +} + +void AmsDfxStServiceAbilityA2::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsDfxStServiceAbilityA2::OnDisconnect"); + + Ability::OnDisconnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnDisconnectCount(), eventData); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::DISCONNECT_TIMEOUT)); +} + +REGISTER_AA(AmsDfxStServiceAbilityA2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..42796c02853998195320c45a4cff530b0b0b298a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestE" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestEConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestE\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestE") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilitye1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestEConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/config.json new file mode 100644 index 0000000000000000000000000000000000000000..fecdbea7e8a9ce77f4c905858fa589212b68d930 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appE", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestE.src", + "name":"AmsSystemTestE", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityE1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityE1 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/include/amsstabilitye1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/include/amsstabilitye1.h new file mode 100644 index 0000000000000000000000000000000000000000..c9c783574820ec18fe72f91f6e5ef0609fa03d85 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/include/amsstabilitye1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_E1_ +#define _AMS_ST_ABILITY_E1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityE1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_E1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/src/amsstabilitye1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/src/amsstabilitye1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..777bfcd11070b0cfdbe7c98d6695233a8faaeb43 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/src/amsstabilitye1.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilitye1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityE1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityE1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityE1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityE1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityE1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityE1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityE1::OnStop() +{ + APP_LOGI("AmsStAbilityE1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityE1::OnActive() +{ + APP_LOGI("AmsStAbilityE1::OnActive"); + Ability::OnActive(); + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityE1::OnInactive() +{ + APP_LOGI("AmsStAbilityE1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityE1::OnBackground() +{ + APP_LOGI("AmsStAbilityE1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityE1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityE1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityE1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..d6eb31cf88db4d3f74a3522c954c6cc99dbf3299 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK" +config("amsSystemTestErrorKConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestErrorK\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestErrorK") { + sources = [ "${SUBDEMOSYSTEM_DIR}/src/amsstabilityerrork1.cpp" ] + configs = [ ":amsSystemTestErrorKConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5d02da55adbf9ec53ef89af31af71bd0f8319b85 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/config.json @@ -0,0 +1,42 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appK", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsStAbilityErrorK.src", + "name":"AmsStAbilityErrorK", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityErrorK1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStAbilityErrorK1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + } + ] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/include/amsstabilityerrork1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/include/amsstabilityerrork1.h new file mode 100644 index 0000000000000000000000000000000000000000..47a5a9dc99f0b379552f56321fe0cd20af0e3b1b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/include/amsstabilityerrork1.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_ERROR_K1_ +#define _AMS_ST_ABILITY_ERROR_K1_ +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityErrorK1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_ERROR_K1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/src/amsstabilityerrork1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/src/amsstabilityerrork1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22fdc5c7bf94c8836ad8b1307fad6e0482b1acc8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/src/amsstabilityerrork1.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityerrork1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityErrorK1::OnStart(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); + int errorCode1 = 0; + int errorCode2 = 0; + int errorCode3 = 0; + errorCode1 = errorCode2 / errorCode3; + + APP_LOGI("AmsStAbilityErrorK1::onStart"); + Ability::OnStart(want); +} + +void AmsStAbilityErrorK1::OnStop() +{ + APP_LOGI("AmsStAbilityErrorK1::onStop"); + Ability::OnStop(); +} + +void AmsStAbilityErrorK1::OnActive() +{ + APP_LOGI("AmsStAbilityErrorK1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } +} + +void AmsStAbilityErrorK1::OnInactive() +{ + APP_LOGI("AmsStAbilityErrorK1::OnInactive"); + Ability::OnInactive(); +} + +void AmsStAbilityErrorK1::OnBackground() +{ + APP_LOGI("AmsStAbilityErrorK1::OnBackground"); + Ability::OnBackground(); +} + +REGISTER_AA(AmsStAbilityErrorK1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..618cc54897d3d06602b99a7e0541e5c598fa4abb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL" +config("amsSystemTestErrorLConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestErrorL\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestErrorL") { + sources = [ "${SUBDEMOSYSTEM_DIR}/src/amsstabilityerrorl1.cpp" ] + configs = [ ":amsSystemTestErrorLConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8e89699581ee146deec891ab932b554e9c8d94c3 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appL", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsStAbilityErrorL.src", + "name":"AmsStAbilityErrorL", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityL1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStAbilityL1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/include/amsstabilityerrorl1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/include/amsstabilityerrorl1.h new file mode 100644 index 0000000000000000000000000000000000000000..03e442243fb8a1e0b86d6bf62d4d4722399185c0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/include/amsstabilityerrorl1.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_ERROR_L1_ +#define _AMS_ST_ABILITY_ERROR_L1_ +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityErrorL1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_G2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/src/amsstabilityerrorl1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/src/amsstabilityerrorl1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b62ab38f5be6659663eb4392f9e5cb94300510b8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/src/amsstabilityerrorl1.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityerrorl1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityErrorL1::OnStart(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); + + APP_LOGI("AmsStAbilityErrorL1::onStart"); + Ability::OnStart(want); +} + +void AmsStAbilityErrorL1::OnStop() +{ + APP_LOGI("AmsStAbilityErrorL1::onStop"); + Ability::OnStop(); +} + +void AmsStAbilityErrorL1::OnActive() +{ + APP_LOGI("AmsStAbilityErrorL1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } +} + +void AmsStAbilityErrorL1::OnInactive() +{ + APP_LOGI("AmsStAbilityErrorL1::OnInactive"); + Ability::OnInactive(); +} + +void AmsStAbilityErrorL1::OnBackground() +{ + APP_LOGI("AmsStAbilityErrorL1::OnBackground"); + Ability::OnBackground(); +} + +REGISTER_AA(AmsStAbilityErrorL1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..f77bf0eb7fa6dc147cae9272fe8a985966c67406 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestF" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestFConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestF\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestF") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityf1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityf2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityf3.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestFConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d54b30c7dd804634206401f0a3bd97f268ab053d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/config.json @@ -0,0 +1,61 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appF", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestF.src", + "name":"AmsSystemTestF", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityF1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityF1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityF2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityF2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityF3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityF3 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf1.h new file mode 100644 index 0000000000000000000000000000000000000000..0cd56124ac390f9622fec0117f8074ec2daa8069 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_F1_ +#define _AMS_ST_ABILITY_F1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityF1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_F1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf2.h new file mode 100644 index 0000000000000000000000000000000000000000..09628fc83bb2e78ed4603098f2a8c2aa0ba40dcb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf2.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_F2_ +#define _AMS_ST_ABILITY_F2_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityF2 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_F2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf3.h new file mode 100644 index 0000000000000000000000000000000000000000..21ec74798eba5397fa3bb30380cf71701d125171 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/include/amsstabilityf3.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_F3_ +#define _AMS_ST_ABILITY_F3_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityF3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_F3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c3122a77089837e9fa192ae1870d21aa3cb1b91 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf1.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityf1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityF1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityF1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityF1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityF1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityF1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityF1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityF1::OnStop() +{ + APP_LOGI("AmsStAbilityF1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityF1::OnActive() +{ + APP_LOGI("AmsStAbilityF1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityF1::OnInactive() +{ + APP_LOGI("AmsStAbilityF1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityF1::OnBackground() +{ + APP_LOGI("AmsStAbilityF1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityF1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityF1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityF1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9e448a0bea91f41dede80cb8fa5fe057e2524ad --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf2.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityf2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityF2::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityF2::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityF2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityF2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityF2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityF2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityF2::OnStop() +{ + APP_LOGI("AmsStAbilityF2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityF2::OnActive() +{ + APP_LOGI("AmsStAbilityF2::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityF2::OnInactive() +{ + APP_LOGI("AmsStAbilityF2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityF2::OnBackground() +{ + APP_LOGI("AmsStAbilityF2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityF2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityF2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityF2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..710c33c97b079c2f5fa4ab62a4e32e771a24ee56 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf3.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityf3.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityF3::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityF3::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityF3::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityF3::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityF3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityF2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityF3::OnStop() +{ + APP_LOGI("AmsStAbilityF3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityF3::OnActive() +{ + APP_LOGI("AmsStAbilityF3::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityF3::OnInactive() +{ + APP_LOGI("AmsStAbilityF3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityF3::OnBackground() +{ + APP_LOGI("AmsStAbilityF3::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityF3::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityF3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityF3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..adb36e8fd58882a7cdffb0e5b64ee7ca0e8daf1c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestG" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestGConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestG\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestG") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityg1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityg2.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestGConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7a69271b4e0157e86e773cd0404dc736d0ff8f4b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/config.json @@ -0,0 +1,51 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appG", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestG.src", + "name":"AmsSystemTestG", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityG1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityG1 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityG2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityG2 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/include/amsstabilityg1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/include/amsstabilityg1.h new file mode 100644 index 0000000000000000000000000000000000000000..8ee8564a1cd4f120c2e78152a2b47e74062e749f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/include/amsstabilityg1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_G1_ +#define _AMS_ST_ABILITY_G1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityG1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnForeground(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_G1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/include/amsstabilityg2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/include/amsstabilityg2.h new file mode 100644 index 0000000000000000000000000000000000000000..134ad4524dddb85e328207c04ca1b12a58eea869 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/include/amsstabilityg2.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_G2_ +#define _AMS_ST_ABILITY_G2_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityG2 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnForeground(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_G2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..acc830c02fa98ae82f4c0fbdfc028affc0a5d219 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg1.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityg1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityG1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityG1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityG1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityG1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityG1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityG1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityG1::OnStop() +{ + APP_LOGI("AmsStAbilityG1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityG1::OnActive() +{ + APP_LOGI("AmsStAbilityG1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityG1::OnInactive() +{ + APP_LOGI("AmsStAbilityG1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityG1::OnBackground() +{ + APP_LOGI("AmsStAbilityG1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityG1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityG1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityG1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a857a1fe771c20afb6382d70e28c1f184a90a544 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg2.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityg2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityG2::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityG2::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityG2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityG2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityG2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityG2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityG2::OnStop() +{ + APP_LOGI("AmsStAbilityG2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityG2::OnActive() +{ + APP_LOGI("AmsStAbilityG2::OnActive"); + Ability::OnActive(); + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityG2::OnInactive() +{ + APP_LOGI("AmsStAbilityG2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityG2::OnBackground() +{ + APP_LOGI("AmsStAbilityG2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityG2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityG2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityG2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..4c1b279053e65d9c512ddf21f389f31bc3e8b989 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestH" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestHConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestH\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestH") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityh1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestHConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0d13d9898c6ff0b8bab49b4ad5186f915225946c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appH", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestH.src", + "name":"AmsSystemTestH", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityH1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityH1 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/include/amsstabilityh1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/include/amsstabilityh1.h new file mode 100644 index 0000000000000000000000000000000000000000..7cc9c2bc611b63f55c720deaa797e7ac10521945 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/include/amsstabilityh1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_H1_ +#define _AMS_ST_ABILITY_H1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityH1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnForeground(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_H1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/src/amsstabilityh1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/src/amsstabilityh1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46c9a8c21b3fc9bab67e1409324c87cc3eb088ec --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/src/amsstabilityh1.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityh1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityH1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityH1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityH1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityH1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityH1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityH1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityH1::OnStop() +{ + APP_LOGI("AmsStAbilityH1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityH1::OnActive() +{ + APP_LOGI("AmsStAbilityH1::OnActive"); + Ability::OnActive(); + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityH1::OnInactive() +{ + APP_LOGI("AmsStAbilityH1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityH1::OnBackground() +{ + APP_LOGI("AmsStAbilityH1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityH1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityH1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityH1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..732a9acd10ba56b13db39f7db5bc40a98084ee92 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestI" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestIConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestI\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestI") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityi1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityi2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityi3.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityi4.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestIConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a3795b631618e24bf30da12546f115d80cdd5399 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/config.json @@ -0,0 +1,71 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appI", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestI.src", + "name":"AmsSystemTestI", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityI1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityI1 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityI2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityI2 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityI3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityC3 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityI4", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityC3 Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi1.h new file mode 100644 index 0000000000000000000000000000000000000000..93502a8587db675075931b5e1409507c76661f8e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi1.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_I1_ +#define _AMS_ST_ABILITY_I1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityI1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_I1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi2.h new file mode 100644 index 0000000000000000000000000000000000000000..1c976ccb076ab88bb13418927878c3cd17a4eaaf --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi2.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_I2_ +#define _AMS_ST_ABILITY_I2_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityI2 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_I2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi3.h new file mode 100644 index 0000000000000000000000000000000000000000..8bfd96ed2eb94241616893c91a7d9db358b3afb9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi3.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_I3_ +#define _AMS_ST_ABILITY_I3_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityI3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_I3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi4.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi4.h new file mode 100644 index 0000000000000000000000000000000000000000..ae6cfafc53b385149c8400062664288ababf667a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/include/amsstabilityi4.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_I4_ +#define _AMS_ST_ABILITY_I4_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityI4 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_I4_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..796dee708c6e12e3547f2554a450dcc08cffb0f5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi1.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityi1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityI1::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityI1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityI1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityI1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityI1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityI1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityI1::OnStop() +{ + APP_LOGI("AmsStAbilityI1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityI1::OnActive() +{ + APP_LOGI("AmsStAbilityI1::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityI1::OnInactive() +{ + APP_LOGI("AmsStAbilityI1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityI1::OnBackground() +{ + APP_LOGI("AmsStAbilityI1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityI1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityI1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityI1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f2c8bc934a6e3c41f58ea1541f68e7fd9ce1ae6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi2.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityi2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityI2::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityI2::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityI2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityI2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityI2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityI1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityI2::OnStop() +{ + APP_LOGI("AmsStAbilityI2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityI2::OnActive() +{ + APP_LOGI("AmsStAbilityI2::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityI2::OnInactive() +{ + APP_LOGI("AmsStAbilityI2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityI2::OnBackground() +{ + APP_LOGI("AmsStAbilityI2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityI2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityI2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityI2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0758a5caedcd95c3158998eb4b04e27e68fcc7b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi3.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityi3.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityI3::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityI::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityI3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityI3::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityI3::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityI1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityI3::OnStop() +{ + APP_LOGI("AmsStAbilityI3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityI3::OnActive() +{ + APP_LOGI("AmsStAbilityI3::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityI3::OnInactive() +{ + APP_LOGI("AmsStAbilityI3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityI3::OnBackground() +{ + APP_LOGI("AmsStAbilityI3::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityI3::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityI3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityI3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..566f97e306ea8c07b3f085c7fee8ac4f3d578e56 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi4.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityi4.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityI4::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityI::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityI4::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityI4::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityI4::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityI1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityI4::OnStop() +{ + APP_LOGI("AmsStAbilityI4::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityI4::OnActive() +{ + APP_LOGI("AmsStAbilityI4::OnActive"); + Ability::OnActive(); + if (!targetBundle.empty() && !targetAbility.empty()) { + Want want; + want.SetElementName(targetBundle, targetAbility); + want.SetParam("shouldReturn", shouldReturn); + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityI4::OnInactive() +{ + APP_LOGI("AmsStAbilityI4::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityI4::OnBackground() +{ + APP_LOGI("AmsStAbilityI4::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityI4::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityI4::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +REGISTER_AA(AmsStAbilityI4); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..92d6670e864163a775b56d3ad4af2059691aab5c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestM" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestMConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestM\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestM") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilitym1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestMConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bc0e4efb166bfc1621be7af32d1a3e9e125e38ec --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appM", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestM.src", + "name":"AmsSystemTestM", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityM1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityM1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/include/amsstabilitym1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/include/amsstabilitym1.h new file mode 100644 index 0000000000000000000000000000000000000000..a3c27f3db913b6e59d03dc5aea3ce5dc167dd295 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/include/amsstabilitym1.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_M1_ +#define _AMS_ST_ABILITY_M1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityM1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void SendPath(const std::string &callBackPath); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_M1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/src/amsstabilitym1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/src/amsstabilitym1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55728cd7ef14052c051c5f93aa90b742c33ceadb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/src/amsstabilitym1.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilitym1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityM1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStAbilityM1::Init"); + Ability::Init(abilityInfo, application, handler, token); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + SendPath("Init"); +} + +void AmsStAbilityM1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityM1::OnStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); + SendPath("OnStart"); +} + +void AmsStAbilityM1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityM1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); + SendPath("OnNewWant"); +} + +void AmsStAbilityM1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityM1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); + SendPath("OnForeground"); +} + +void AmsStAbilityM1::OnStop() +{ + APP_LOGI("AmsStAbilityM1::OnStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); + SendPath("OnStop"); +} + +void AmsStAbilityM1::OnActive() +{ + APP_LOGI("AmsStAbilityM1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); + SendPath("OnActive"); +} + +void AmsStAbilityM1::OnInactive() +{ + APP_LOGI("AmsStAbilityM1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); + SendPath("OnInactive"); +} + +void AmsStAbilityM1::OnBackground() +{ + APP_LOGI("AmsStAbilityM1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); + SendPath("OnBackground"); +} + +void AmsStAbilityM1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityM1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityM1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void AmsStAbilityM1::SendPath(const std::string &callBackPath) +{ + std::string callBack = pageAbilityEvent.GetCallBackPath(callBackPath); + std::string abilityStatus = pageAbilityEvent.GetAbilityStatus(std::to_string(Ability::GetState())); + std::string callBackPathEventData = Ability::GetAbilityName() + callBack; + std::string abilityStatusEventData = Ability::GetAbilityName() + abilityStatus; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, callBackPathEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, abilityStatusEventData); +} + +REGISTER_AA(AmsStAbilityM1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..643484b9bcdddce0e2434499b2233d6add83596d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestN" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestNConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestN\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestN") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityn1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityn2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityn3.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityn4.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestNConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/config.json new file mode 100644 index 0000000000000000000000000000000000000000..15e9c3f6009881a8704c8cecec361f8e53c0fb1d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/config.json @@ -0,0 +1,71 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appN", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestN.src", + "name":"AmsSystemTestN", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityN1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityI1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityN2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityI2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityN3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityC3 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityN4", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityC3 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn1.h new file mode 100644 index 0000000000000000000000000000000000000000..f8b3001de833ecd766c7b92a96c1a7ddb3f8056c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn1.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_N1_ +#define _AMS_ST_ABILITY_N1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityN1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void SendPath(const std::string &callBackPath); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_N1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn2.h new file mode 100644 index 0000000000000000000000000000000000000000..bc368217833ebfe4c566514b8d5d7f9de27b4e67 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn2.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_N2_ +#define _AMS_ST_ABILITY_N2_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityN2 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void SendPath(const std::string &callBackPath); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_N2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn3.h new file mode 100644 index 0000000000000000000000000000000000000000..d0f01e229d59b1cc6393b79b65b6cadc01c064bb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn3.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_N3_ +#define _AMS_ST_ABILITY_N3_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityN3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_N3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn4.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn4.h new file mode 100644 index 0000000000000000000000000000000000000000..f65693eedcac4f601acc50fcc4e97061855f8266 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/include/amsstabilityn4.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_N4_ +#define _AMS_ST_ABILITY_N4_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityN4 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_N4_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..862b20cc0b8f0dea0c48b5ba42fc0dc1f5819bca --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn1.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityn1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityN1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStAbilityN1::Init"); + Ability::Init(abilityInfo, application, handler, token); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + SendPath("Init"); +} + +void AmsStAbilityN1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityN1::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); + SendPath("OnStart"); +} + +void AmsStAbilityN1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityN1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); + SendPath("OnNewWant"); +} + +void AmsStAbilityN1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityN1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); + SendPath("OnForeground"); +} + +void AmsStAbilityN1::OnStop() +{ + APP_LOGI("AmsStAbilityN1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); + SendPath("OnStop"); +} + +void AmsStAbilityN1::OnActive() +{ + APP_LOGI("AmsStAbilityN1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); + SendPath("OnActive"); +} + +void AmsStAbilityN1::OnInactive() +{ + APP_LOGI("AmsStAbilityN1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); + SendPath("OnInactive"); +} + +void AmsStAbilityN1::OnBackground() +{ + APP_LOGI("AmsStAbilityN1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); + SendPath("OnBackground"); +} + +void AmsStAbilityN1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityN1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityN1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void AmsStAbilityN1::SendPath(const std::string &callBackPath) +{ + std::string callBack = pageAbilityEvent.GetCallBackPath(callBackPath); + std::string abilityStatus = pageAbilityEvent.GetAbilityStatus(std::to_string(Ability::GetState())); + std::string callBackPathEventData = Ability::GetAbilityName() + callBack; + std::string abilityStatusEventData = Ability::GetAbilityName() + abilityStatus; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, callBackPathEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, abilityStatusEventData); +} + +REGISTER_AA(AmsStAbilityN1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..374c494894e1caabeddbc328bdd6d279127b2838 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn2.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityn2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityN2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStAbilityN2::Init"); + Ability::Init(abilityInfo, application, handler, token); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + SendPath("Init"); +} + +void AmsStAbilityN2::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityN2::onStart"); + Ability::OnStart(want); + SendPath("OnStart"); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityN2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityN2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); + SendPath("OnNewWant"); +} + +void AmsStAbilityN2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityN2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); + SendPath("OnForeground"); +} + +void AmsStAbilityN2::OnStop() +{ + APP_LOGI("AmsStAbilityN2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); + SendPath("OnStop"); +} + +void AmsStAbilityN2::OnActive() +{ + APP_LOGI("AmsStAbilityN2::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); + SendPath("OnActive"); +} + +void AmsStAbilityN2::OnInactive() +{ + APP_LOGI("AmsStAbilityN2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); + SendPath("OnInactive"); +} + +void AmsStAbilityN2::OnBackground() +{ + APP_LOGI("AmsStAbilityN2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); + SendPath("OnBackground"); +} + +void AmsStAbilityN2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityN2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityN2::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void AmsStAbilityN2::SendPath(const std::string &callBackPath) +{ + std::string callBack = pageAbilityEvent.GetCallBackPath(callBackPath); + std::string abilityStatus = pageAbilityEvent.GetAbilityStatus(std::to_string(Ability::GetState())); + std::string callBackPathEventData = Ability::GetAbilityName() + callBack; + std::string abilityStatusEventData = Ability::GetAbilityName() + abilityStatus; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, callBackPathEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, abilityStatusEventData); +} + +REGISTER_AA(AmsStAbilityN2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87aadf2b27926049b8a24944834417af1d2989eb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn3.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityn3.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityN3::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityN3::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityN3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityN3::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityN3::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityN3::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityN3::OnStop() +{ + APP_LOGI("AmsStAbilityN3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityN3::OnActive() +{ + APP_LOGI("AmsStAbilityN3::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityN3::OnInactive() +{ + APP_LOGI("AmsStAbilityN3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityN3::OnBackground() +{ + APP_LOGI("AmsStAbilityN3::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityN3::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityN3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityN3::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityN3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9618f49ed4cc192205af1c0a120fce3967a4245 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn4.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityn4.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityN4::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityN4::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityN4::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityN4::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityN4::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityN4::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityN4::OnStop() +{ + APP_LOGI("AmsStAbilityN4::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityN4::OnActive() +{ + APP_LOGI("AmsStAbilityN4::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityN4::OnInactive() +{ + APP_LOGI("AmsStAbilityN4::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityN4::OnBackground() +{ + APP_LOGI("AmsStAbilityN4::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityN4::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityN4::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityN4::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityN4); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..d7d3a4841230aa8cfe1e36b0e547c2f37f740bb7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestO" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestOConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestO\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestO") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityo1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestOConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b5b29cb8287097102d3008882a8c0f4f5593646d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appO", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestO.src", + "name":"AmsSystemTestO", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityO1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityO1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/include/amsstabilityo1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/include/amsstabilityo1.h new file mode 100644 index 0000000000000000000000000000000000000000..af719d3f860c37d440cff99e44e8c62f4c85e9b5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/include/amsstabilityo1.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_O1_ +#define _AMS_ST_ABILITY_O1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "process_info.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityO1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_O1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/src/amsstabilityo1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/src/amsstabilityo1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aabf5e500380d6b459acdc03e52ec032f11ea944 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/src/amsstabilityo1.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityo1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityO1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityO1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + if (processInfo != nullptr) { + int amsStAbilityO1Code = 10; + std::string pidInfo = std::to_string(processInfo->GetPid()); + pageAbilityEvent.PublishEvent(STEventName::g_pidEventName, amsStAbilityO1Code, pidInfo); + } + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityO1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityO1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityO1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityO1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityO1::OnStop() +{ + APP_LOGI("AmsStAbilityO1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityO1::OnActive() +{ + APP_LOGI("AmsStAbilityO1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityO1::OnInactive() +{ + APP_LOGI("AmsStAbilityO1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityO1::OnBackground() +{ + APP_LOGI("AmsStAbilityO1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityO1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityO1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityO1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityO1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..fc80971bd6236da418519357d5be2db6d2823be3 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestP" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestPConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestP\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestP") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityp1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestPConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/config.json new file mode 100644 index 0000000000000000000000000000000000000000..efa5e5cb1d74951ba6a1cb8483a140e6673b1c6c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appO", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestP.src", + "name":"AmsSystemTestP", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "feature" + }, + "abilities": [{ + "name": "AmsStAbilityP1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityP1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/include/amsstabilityp1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/include/amsstabilityp1.h new file mode 100644 index 0000000000000000000000000000000000000000..28c566882ce4fe267965125d5d6247ecfe6723eb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/include/amsstabilityp1.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_P1_ +#define _AMS_ST_ABILITY_P1_ +#include "stpageabilityevent.h" +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "process_info.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityP1 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_P1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/src/amsstabilityp1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/src/amsstabilityp1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afe9cc7c5245584cfd1c45aa6fbdfcc05574a06c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/src/amsstabilityp1.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityp1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityP1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityP1::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + if (processInfo != nullptr) { + int amsStAbilityP1Code = 11; + std::string pidInfo = std::to_string(processInfo->GetPid()); + pageAbilityEvent.PublishEvent(STEventName::g_pidEventName, amsStAbilityP1Code, pidInfo); + } + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityP1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityP1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityP1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityP1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityP1::OnStop() +{ + APP_LOGI("AmsStAbilityP1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityP1::OnActive() +{ + APP_LOGI("AmsStAbilityP1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityP1::OnInactive() +{ + APP_LOGI("AmsStAbilityP1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityP1::OnBackground() +{ + APP_LOGI("AmsStAbilityP1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityP1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityP1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityP1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityP1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..1bcababb3f480f355d152dd07d29b0cdefc13594 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestQConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestQ\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestQ") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityq1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityq2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityq3.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityq4.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestQConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5e93dd7d86c8d1a6b08d6a971f3b6b0f56c6ec9d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/config.json @@ -0,0 +1,71 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appQ", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestQ.src", + "name":"AmsSystemTestQ", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityQ1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityQ1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityQ2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityQ2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityQ3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityQ3 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityQ4", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityQ4 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq1.h new file mode 100644 index 0000000000000000000000000000000000000000..bbed9633d9a983e760187bc1f3dcc9b3fbd62b00 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq1.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_Q1_ +#define _AMS_ST_ABILITY_Q1_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityQ1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_Q1_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq2.h new file mode 100644 index 0000000000000000000000000000000000000000..50537923cd75bc340fae6355b723fa2db7e94d71 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq2.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_Q2_ +#define _AMS_ST_ABILITY_Q2_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityQ2 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void SendPath(const std::string &callBackPath); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_Q2_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq3.h new file mode 100644 index 0000000000000000000000000000000000000000..e23c12cbe47ce134a8d7dbbfcd17939e180dc9c9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq3.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_Q3_ +#define _AMS_ST_ABILITY_Q3_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityQ3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_Q3_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq4.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq4.h new file mode 100644 index 0000000000000000000000000000000000000000..442542f7361a07d516e55f17f7fe7c7353f8a152 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/include/amsstabilityq4.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_Q4_ +#define _AMS_ST_ABILITY_Q4_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityQ4 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_Q4_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..703b7316351b10bd85249cee0ccd07211e6c7ec4 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq1.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityq1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityQ1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStAbilityQ1::Init"); + Ability::Init(abilityInfo, application, handler, token); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); +} + +void AmsStAbilityQ1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityQ1::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityQ1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityQ1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityQ1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityQ1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityQ1::OnStop() +{ + APP_LOGI("AmsStAbilityQ1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityQ1::OnActive() +{ + APP_LOGI("AmsStAbilityQ1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityQ1::OnInactive() +{ + APP_LOGI("AmsStAbilityQ1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityQ1::OnBackground() +{ + APP_LOGI("AmsStAbilityQ1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityQ1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityQ1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityQ1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityQ1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c82d68334185b54b0993a42fe5bd46ceba66d655 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq2.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityq2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityQ2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStAbilityQ2::Init"); + Ability::Init(abilityInfo, application, handler, token); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::LOAD_TIMEOUT)); +} + +void AmsStAbilityQ2::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityQ2::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityQ2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityQ2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityQ2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityQ2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityQ2::OnStop() +{ + APP_LOGI("AmsStAbilityQ2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityQ2::OnActive() +{ + APP_LOGI("AmsStAbilityQ2::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityQ2::OnInactive() +{ + APP_LOGI("AmsStAbilityQ2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityQ2::OnBackground() +{ + APP_LOGI("AmsStAbilityQ2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityQ2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityQ2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityQ2::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityQ2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fdf423c03db54e34bdd02b6429e22bafdc9552e0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq3.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityq3.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityQ3::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityQ3::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityQ3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityQ3::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityQ3::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityQ3::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityQ3::OnStop() +{ + APP_LOGI("AmsStAbilityQ3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityQ3::OnActive() +{ + APP_LOGI("AmsStAbilityQ3::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityQ3::OnInactive() +{ + APP_LOGI("AmsStAbilityQ3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityQ3::OnBackground() +{ + APP_LOGI("AmsStAbilityQ3::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityQ3::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityQ3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityQ3::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityQ3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae8b01fe01685ab8423d45cfb7c347d15928d789 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq4.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityq4.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityQ4::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityQ4::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityQ4::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityQ4::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityQ4::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityQ4::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityQ4::OnStop() +{ + APP_LOGI("AmsStAbilityQ4::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityQ4::OnActive() +{ + APP_LOGI("AmsStAbilityQ4::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityQ4::OnInactive() +{ + APP_LOGI("AmsStAbilityQ4::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityQ4::OnBackground() +{ + APP_LOGI("AmsStAbilityQ4::OnBackground"); + Ability::OnBackground(); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::TERMINATE_TIMEOUT)); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityQ4::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityQ4::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityQ4::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityQ4); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..e8233dd104dfad39128d5789610dce423d18c1e6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsSystemTestR" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestRConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestR\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestR") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityr1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityr2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityr3.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsstabilityr4.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestRConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/config.json new file mode 100644 index 0000000000000000000000000000000000000000..1edef7bee175177a592ceb009b532899a62de746 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/config.json @@ -0,0 +1,71 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appR", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestR.src", + "name":"AmsSystemTestR", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStAbilityR1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityR1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityR2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityR2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityR3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityR3 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStAbilityR4", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AbilityR4 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr1.h new file mode 100644 index 0000000000000000000000000000000000000000..73e67b0d73c46b2abd841df793f74fed2660e20e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr1.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_R1_ +#define _AMS_ST_ABILITY_R1_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityR1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_R1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr2.h new file mode 100644 index 0000000000000000000000000000000000000000..4d91d70134d5c1d565e6111c92c995d7079ff64b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr2.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_R2_ +#define _AMS_ST_ABILITY_R2_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityR2 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void SendPath(const std::string &callBackPath); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_R2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr3.h new file mode 100644 index 0000000000000000000000000000000000000000..9fd9bbda02c7fc88826d49947356913f2dfe0f32 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr3.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_R3_ +#define _AMS_ST_ABILITY_R3_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityR3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_R3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr4.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr4.h new file mode 100644 index 0000000000000000000000000000000000000000..4f0742445c7d46e44c47398506078190fb6f76d5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/include/amsstabilityr4.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_ABILITY_R4_ +#define _AMS_ST_ABILITY_R4_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStAbilityR4 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string shouldReturn; + std::string targetBundle; + std::string targetAbility; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_ABILITY_R4_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..42b3d2879fc911b90edf820a3faba361e10289b0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr1.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityr1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityR1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStAbilityR1::Init"); + Ability::Init(abilityInfo, application, handler, token); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::LOAD_TIMEOUT)); +} + +void AmsStAbilityR1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityR1::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityR1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityR1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityR1::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityR1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityR1::OnStop() +{ + APP_LOGI("AmsStAbilityR1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityR1::OnActive() +{ + APP_LOGI("AmsStAbilityR1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityR1::OnInactive() +{ + APP_LOGI("AmsStAbilityR1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityR1::OnBackground() +{ + APP_LOGI("AmsStAbilityR1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityR1::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityR1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityR1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityR1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..75ee4caf3814631de34dbb08c63dbaf3f6fd4de0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityr2.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +constexpr uint32_t multiple = 100; +} +void AmsStAbilityR2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsStAbilityR2::Init"); + Ability::Init(abilityInfo, application, handler, token); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); +} + +void AmsStAbilityR2::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityR2::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityR2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityR2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityR2::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityR2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityR2::OnStop() +{ + APP_LOGI("AmsStAbilityR2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityR2::OnActive() +{ + APP_LOGI("AmsStAbilityR2::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityR2::OnInactive() +{ + APP_LOGI("AmsStAbilityR2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityR2::OnBackground() +{ + APP_LOGI("AmsStAbilityR2::OnBackground"); + Ability::OnBackground(); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::BACKGROUND_TIMEOUT * multiple)); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityR2::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityR2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityR2::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityR2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8c1476c1f0dde14e73b3e2965135e2c0cd9992f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityr3.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +constexpr uint32_t timeoutAdd = 5000; +} +void AmsStAbilityR3::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsStAbilityR3::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityR3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityR3::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityR3::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityR3::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityR3::OnStop() +{ + APP_LOGI("AmsStAbilityR3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityR3::OnActive() +{ + APP_LOGI("AmsStAbilityR3::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityR3::OnInactive() +{ + APP_LOGI("AmsStAbilityR3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityR3::OnBackground() +{ + APP_LOGI("AmsStAbilityR3::OnBackground"); + Ability::OnBackground(); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::TERMINATE_TIMEOUT + timeoutAdd)); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityR3::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityR3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityR3::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityR3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67730c5649c84b0365fb0a4dd85115442c52583c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr4.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "amsstabilityr4.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsStAbilityR4::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsStAbilityR4::onStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsStAbilityR4::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStAbilityR4::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsStAbilityR4::OnForeground(const Want &want) +{ + APP_LOGI("AmsStAbilityR4::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsStAbilityR4::OnStop() +{ + APP_LOGI("AmsStAbilityR4::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsStAbilityR4::OnActive() +{ + APP_LOGI("AmsStAbilityR4::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle, ","); + std::string startAbilityName = this->Split(targetAbility, ","); + if (!startBundleName.empty() && !startAbilityName.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + want.SetParam("shouldReturn", shouldReturn); + if (!targetBundle.empty() && !targetAbility.empty()) { + want.SetParam("targetBundle", targetBundle); + want.SetParam("targetAbility", targetAbility); + } + StartAbility(want); + } + if (std::string::npos != shouldReturn.find(GetAbilityName())) { + TerminateAbility(); + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsStAbilityR4::OnInactive() +{ + APP_LOGI("AmsStAbilityR4::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsStAbilityR4::OnBackground() +{ + APP_LOGI("AmsStAbilityR4::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsStAbilityR4::Clear() +{ + shouldReturn = ""; + targetBundle = ""; + targetAbility = ""; +} + +void AmsStAbilityR4::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn = mWant.GetStringParam("shouldReturn"); + targetBundle = mWant.GetStringParam("targetBundle"); + targetAbility = mWant.GetStringParam("targetAbility"); +} + +std::string AmsStAbilityR4::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsStAbilityR4); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..a87b636e91b5276b96107ebba21e384d79d8e100 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceA" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceA") { + sources = [ "${subdemosystem_path}/src/ams_st_service_ability_a1.cpp" ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..572a4759a3355c9a8b8e919f48bef810f5602297 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appA", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestServiceA.src", + "name":"AmsSystemTestServiceA", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStServiceAbilityA1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/include/ams_st_service_ability_a1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/include/ams_st_service_ability_a1.h new file mode 100644 index 0000000000000000000000000000000000000000..b7496c350f0719f67d8ee866e1896ef78305a114 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/include/ams_st_service_ability_a1.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_A1_ +#define AMS_ST_SERVICE_ABILITY_A1_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A1_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_a1"; +const std::string APP_A1_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_a1"; + +class AmsStServiceAbilityA1 : public Ability { +public: + ~AmsStServiceAbilityA1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (AmsStServiceAbilityA1::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityA1 *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_A1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/src/ams_st_service_ability_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/src/ams_st_service_ability_a1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e09ade6303f9d01df3378ab0e7eb2a953961f754 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/src/ams_st_service_ability_a1.cpp @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_a1.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int AmsStServiceAbilityA1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map AmsStServiceAbilityA1::funcMap_ = { + {"StartOtherAbility", &AmsStServiceAbilityA1::StartOtherAbility}, + {"ConnectOtherAbility", &AmsStServiceAbilityA1::ConnectOtherAbility}, + {"DisConnectOtherAbility", &AmsStServiceAbilityA1::DisConnectOtherAbility}, + {"StopSelfAbility", &AmsStServiceAbilityA1::StopSelfAbility}, +}; + +AmsStServiceAbilityA1::~AmsStServiceAbilityA1() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector AmsStServiceAbilityA1::Split(std::string str, const std::string &token) +{ + APP_LOGI("AmsStServiceAbilityA1::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void AmsStServiceAbilityA1::StartOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityA1::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("AmsStServiceAbilityA1::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void AmsStServiceAbilityA1::ConnectOtherAbility() +{ + APP_LOGI( + "AmsStServiceAbilityA1::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("AmsStServiceAbilityA1::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("AmsStServiceAbilityA1::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("AmsStServiceAbilityA1::ConnectAbility failed!"); + } + } + } +} +void AmsStServiceAbilityA1::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityA1::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("AmsStServiceAbilityA1::DisConnectOtherAbility end"); +} + +void AmsStServiceAbilityA1::StopSelfAbility() +{ + APP_LOGI("AmsStServiceAbilityA1::StopSelfAbility"); + + TerminateAbility(); +} + +void AmsStServiceAbilityA1::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void AmsStServiceAbilityA1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityA1::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityA1::OnStop() +{ + APP_LOGI("AmsStServiceAbilityA1::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityA1::OnActive() +{ + APP_LOGI("AmsStServiceAbilityA1::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityA1::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityA1::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityA1::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityA1::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void AmsStServiceAbilityA1::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void AmsStServiceAbilityA1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + AmsStServiceAbilityA1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool AmsStServiceAbilityA1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityA1::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr AmsStServiceAbilityA1::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnConnect"); + + sptr ret = Ability::OnConnect(want); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return ret; +} +void AmsStServiceAbilityA1::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityA1::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool AmsStServiceAbilityA1::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A1_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void AmsStServiceAbilityA1::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("AmsStServiceAbilityA1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A1_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "AmsStServiceAbilityA1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..6e34f41528a678785203eb4ebe831320d2953b7a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceB" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceB\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceB") { + sources = [ + "${subdemosystem_path}/src/ams_st_service_ability_b2.cpp", + "${subdemosystem_path}/src/ams_st_service_ability_b3.cpp", + ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9d48184059748bd6ed204d6756cd9c2d976212ef --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/config.json @@ -0,0 +1,52 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appB", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestServiceB.src", + "name":"AmsSystemTestServiceB", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "AmsStServiceAbilityB2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityB2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsStServiceAbilityB3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityB3 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/include/ams_st_service_ability_b2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/include/ams_st_service_ability_b2.h new file mode 100644 index 0000000000000000000000000000000000000000..898660ad3ba81a6d8d8cb92ee03f9d398b5f2ae7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/include/ams_st_service_ability_b2.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_B2_ +#define AMS_ST_SERVICE_ABILITY_B2_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_B2_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_b2"; +const std::string APP_B1_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_b2"; +class AmsStServiceAbilityB2 : public Ability { +public: + ~AmsStServiceAbilityB2(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void StopSelfAbility(); + void DisConnectOtherAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + + typedef void (AmsStServiceAbilityB2::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + std::vector> connCallback_ = {}; + std::vector> stub_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_B2_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_B2_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityB2 *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_B2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/include/ams_st_service_ability_b3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/include/ams_st_service_ability_b3.h new file mode 100644 index 0000000000000000000000000000000000000000..c4447a4c675268b6ab0f34a860c02812ef43f37a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/include/ams_st_service_ability_b3.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_B3_ +#define AMS_ST_SERVICE_ABILITY_B3_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +const std::string APP_B3_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_b3"; +const std::string APP_B3_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_b3"; +class AmsStServiceAbilityB3 : public Ability { +public: + ~AmsStServiceAbilityB3(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + + typedef void (AmsStServiceAbilityB3::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + std::vector> connCallback_ = {}; + std::vector> stub_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_B3_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_B3_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityB3 *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_B3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/src/ams_st_service_ability_b2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/src/ams_st_service_ability_b2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ddaabfcbbe51ec867f16913343c9391bb01fa05 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/src/ams_st_service_ability_b2.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_b2.h" +#include "app_log_wrapper.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +int AmsStServiceAbilityB2::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map AmsStServiceAbilityB2::funcMap_ = { + {"StartOtherAbility", &AmsStServiceAbilityB2::StartOtherAbility}, + {"ConnectOtherAbility", &AmsStServiceAbilityB2::ConnectOtherAbility}, + {"StopSelfAbility", &AmsStServiceAbilityB2::StopSelfAbility}, + {"DisConnectOtherAbility", &AmsStServiceAbilityB2::DisConnectOtherAbility}, +}; + +AmsStServiceAbilityB2::~AmsStServiceAbilityB2() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector AmsStServiceAbilityB2::Split(std::string str, const std::string &token) +{ + APP_LOGI("AmsStServiceAbilityB2::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void AmsStServiceAbilityB2::StartOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityB2::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("AmsStServiceAbilityB2::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void AmsStServiceAbilityB2::ConnectOtherAbility() +{ + APP_LOGI( + "AmsStServiceAbilityB2::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("AmsStServiceAbilityB2::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + stub_.push_back(new (std::nothrow) AbilityConnectCallback()); + connCallback_.push_back(new (std::nothrow) AbilityConnectionProxy(stub_[i])); + APP_LOGI("AmsStAbilitySvcD1::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_[i]); + sleep(1); + if (!ret) { + APP_LOGE("AmsStServiceAbilityB2::ConnectAbility failed!"); + } + } + } + APP_LOGI("AmsStServiceAbilityB2::ConnectOtherAbility end"); +} +void AmsStServiceAbilityB2::StopSelfAbility() +{ + APP_LOGI("AmsStServiceAbilityB2::StopSelfAbility"); + + TerminateAbility(); +} + +void AmsStServiceAbilityB2::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityB2::DisConnectOtherAbility begin"); + for (auto callBack : connCallback_) { + DisconnectAbility(callBack); + sleep(1); + } + APP_LOGI("AmsStServiceAbilityB2::DisConnectOtherAbility end"); +} + +void AmsStServiceAbilityB2::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB2::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); +} +void AmsStServiceAbilityB2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB2::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityB2::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityB2::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityB2::OnStop() +{ + APP_LOGI("AmsStServiceAbilityB2::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); + Clear(); +} +void AmsStServiceAbilityB2::OnActive() +{ + APP_LOGI("AmsStServiceAbilityB2::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityB2::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityB2::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityB2::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityB2::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +sptr AmsStServiceAbilityB2::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB2::OnConnect"); + + sptr remote = Ability::OnConnect(want); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return remote; +} +void AmsStServiceAbilityB2::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB2::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_B2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} + +void AmsStServiceAbilityB2::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; + AmsStServiceAbilityB2::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +void AmsStServiceAbilityB2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + AmsStServiceAbilityB2::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool AmsStServiceAbilityB2::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityB2::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +bool AmsStServiceAbilityB2::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_B1_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + subscriber->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber); +} +void AmsStServiceAbilityB2::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI( + "AmsStServiceAbilityB2::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s is exist", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_B1_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI("AmsStServiceAbilityB2::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = " + "%{public}s not find", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityB2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/src/ams_st_service_ability_b3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/src/ams_st_service_ability_b3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc11dea473439075168c419a54ed8c4bb68811e0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/src/ams_st_service_ability_b3.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_b3.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +int AmsStServiceAbilityB3::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map AmsStServiceAbilityB3::funcMap_ = { + {"StartOtherAbility", &AmsStServiceAbilityB3::StartOtherAbility}, + {"ConnectOtherAbility", &AmsStServiceAbilityB3::ConnectOtherAbility}, + {"DisConnectOtherAbility", &AmsStServiceAbilityB3::DisConnectOtherAbility}, + {"StopSelfAbility", &AmsStServiceAbilityB3::StopSelfAbility}, +}; + +AmsStServiceAbilityB3::~AmsStServiceAbilityB3() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector AmsStServiceAbilityB3::Split(std::string str, const std::string &token) +{ + APP_LOGI("AmsStServiceAbilityB3::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void AmsStServiceAbilityB3::StartOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityB3::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("AmsStServiceAbilityB3::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void AmsStServiceAbilityB3::ConnectOtherAbility() +{ + APP_LOGI( + "AmsStServiceAbilityB3::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("AmsStServiceAbilityB3::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_.push_back(new (std::nothrow) AbilityConnectCallback()); + connCallback_.push_back(new (std::nothrow) AbilityConnectionProxy(stub_[i])); + APP_LOGI("AmsStAbilitySvcD1::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_[i]); + sleep(1); + if (!ret) { + APP_LOGE("AmsStServiceAbilityB3::ConnectAbility failed!"); + } + } + } +} + +void AmsStServiceAbilityB3::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityB3::DisConnectOtherAbility begin"); + for (auto callBack : connCallback_) { + DisconnectAbility(callBack); + sleep(1); + } + APP_LOGI("AmsStServiceAbilityB3::DisConnectOtherAbility end"); +} + +void AmsStServiceAbilityB3::StopSelfAbility() +{ + APP_LOGI("AmsStServiceAbilityB3::StopSelfAbility"); + + TerminateAbility(); +} + +void AmsStServiceAbilityB3::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB3::onStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); +} +void AmsStServiceAbilityB3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB3::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityB3::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityB3::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityB3::OnStop() +{ + APP_LOGI("AmsStServiceAbilityB3::onStop"); + + Ability::OnStop(); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityB3::OnActive() +{ + APP_LOGI("AmsStServiceAbilityB3::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityB3::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityB3::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityB3::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityB3::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} +sptr AmsStServiceAbilityB3::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB3::OnConnect"); + + sptr remote = Ability::OnConnect(want); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return remote; +} +void AmsStServiceAbilityB3::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityB3::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_B3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +void AmsStServiceAbilityB3::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; + AmsStServiceAbilityB3::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +void AmsStServiceAbilityB3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + AmsStServiceAbilityB3::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool AmsStServiceAbilityB3::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityB3::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +bool AmsStServiceAbilityB3::SubscribeEvent() +{ + APP_LOGI("AmsStServiceAbilityB3::SubscribeEvent"); + + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_B3_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void AmsStServiceAbilityB3::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("AmsStServiceAbilityB3::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_B3_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "AmsStServiceAbilityB3::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityB3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..8c5ad15e84ee9bed97a43eccf2416aa440a1269e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceC" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceC\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceC") { + sources = [ "${subdemosystem_path}/src/ams_st_service_ability_c4.cpp" ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/config.json new file mode 100644 index 0000000000000000000000000000000000000000..eca73dca071d806e2d5356316c929ff6663e556b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/config.json @@ -0,0 +1,42 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appC", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestServiceC.src", + "name":"AmsSystemTestServiceC", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "AmsStServiceAbilityC4", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityC4 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/include/ams_st_service_ability_c4.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/include/ams_st_service_ability_c4.h new file mode 100644 index 0000000000000000000000000000000000000000..8d27630fb6573fb5e2a11235348cca36f8e68a34 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/include/ams_st_service_ability_c4.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_C4_ +#define AMS_ST_SERVICE_ABILITY_C4_ +#include +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStServiceAbilityC4 : public Ability { +public: + ~AmsStServiceAbilityC4(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + bool SubscribeEvent(); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + + typedef void (AmsStServiceAbilityC4::*func)(); + static std::map funcMap_; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityC4 *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_C4_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/src/ams_st_service_ability_c4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/src/ams_st_service_ability_c4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01c32d69cf67101311a7489f75f9d271cfc24d80 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/src/ams_st_service_ability_c4.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_c4.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +const std::string APP_C4_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_c4"; +const std::string APP_C4_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_c4"; + +std::map AmsStServiceAbilityC4::funcMap_ = { + {"DisConnectOtherAbility", &AmsStServiceAbilityC4::DisConnectOtherAbility}, + {"StopSelfAbility", &AmsStServiceAbilityC4::StopSelfAbility}, +}; + +AmsStServiceAbilityC4::~AmsStServiceAbilityC4() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsStServiceAbilityC4::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityC4::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); +} +void AmsStServiceAbilityC4::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityC4::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityC4::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityC4::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityC4::OnStop() +{ + APP_LOGI("AmsStServiceAbilityC4::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityC4::OnActive() +{ + APP_LOGI("AmsStServiceAbilityC4::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityC4::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityC4::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityC4::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityC4::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} +sptr AmsStServiceAbilityC4::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityC4::OnConnect"); + + sptr ret = Ability::OnConnect(want); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return ret; +} +void AmsStServiceAbilityC4::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityC4::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_C4_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +void AmsStServiceAbilityC4::StopSelfAbility() +{ + APP_LOGI("AmsStServiceAbilityC4::StopSelfAbility"); + + TerminateAbility(); +} +void AmsStServiceAbilityC4::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityC4::DisConnectOtherAbility begin"); + + APP_LOGI("AmsStServiceAbilityB3::DisConnectOtherAbility end"); +} +void AmsStServiceAbilityC4::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} +void AmsStServiceAbilityC4::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} +bool AmsStServiceAbilityC4::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityC4::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +bool AmsStServiceAbilityC4::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_C4_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsStServiceAbilityC4::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("AmsStServiceAbilityC4::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_C4_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "AmsStServiceAbilityC4::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityC4); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..6d4d6d96efee7be7b68d42b3ffd409a45017dfe7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceD" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceD\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceD") { + sources = [ "${subdemosystem_path}/src/ams_st_service_ability_d1.cpp" ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0c213146a5f3a5fa624062cdc8c962707e018e4c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/config.json @@ -0,0 +1,41 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appD", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestServiceD.src", + "name":"AmsSystemTestServiceD", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsStServiceAbilityD1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityD1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/include/ams_st_service_ability_d1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/include/ams_st_service_ability_d1.h new file mode 100644 index 0000000000000000000000000000000000000000..39881f3381a4ec61e0a011006a3f80231293366b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/include/ams_st_service_ability_d1.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_D1_ +#define AMS_ST_SERVICE_ABILITY_D1_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +class AmsStServiceAbilityD1 : public Ability { +public: + ~AmsStServiceAbilityD1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + void GetDataByDataAbility(); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void StopSelfAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + + typedef void (AmsStServiceAbilityD1::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + std::vector> connCallback_ = {}; + std::vector> stub_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityD1 *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_D1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/src/ams_st_service_ability_d1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/src/ams_st_service_ability_d1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2a7c0f243f86681e545b2c625c65d4ba5a13f1f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/src/ams_st_service_ability_d1.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_d1.h" +#include "app_log_wrapper.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +const std::string APP_D1_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_d1"; +const std::string APP_D1_REQ_EVENTNAME = "req_com_ohos_amsst_service_app_d1"; +int AmsStServiceAbilityD1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map AmsStServiceAbilityD1::funcMap_ = { + {"StartOtherAbility", &AmsStServiceAbilityD1::StartOtherAbility}, + {"ConnectOtherAbility", &AmsStServiceAbilityD1::ConnectOtherAbility}, + {"DisConnectOtherAbility", &AmsStServiceAbilityD1::DisConnectOtherAbility}, + {"StopSelfAbility", &AmsStServiceAbilityD1::StopSelfAbility}, + {"GetDataByDataAbility", &AmsStServiceAbilityD1::GetDataByDataAbility}, +}; + +AmsStServiceAbilityD1::~AmsStServiceAbilityD1() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector AmsStServiceAbilityD1::Split(std::string str, const std::string &token) +{ + APP_LOGI("AmsStServiceAbilityD1::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void AmsStServiceAbilityD1::StartOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityD1::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("AmsStServiceAbilityD1::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void AmsStServiceAbilityD1::ConnectOtherAbility() +{ + APP_LOGI( + "AmsStServiceAbilityD1::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("AmsStServiceAbilityD1::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + stub_.push_back(new (std::nothrow) AbilityConnectCallback()); + connCallback_.push_back(new (std::nothrow) AbilityConnectionProxy(stub_[i])); + APP_LOGI("AmsStServiceAbilityD1::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_[i]); + sleep(1); + if (!ret) { + APP_LOGE("AmsStServiceAbilityD1::ConnectAbility failed!"); + } + } + } + APP_LOGI("AmsStServiceAbilityD1::ConnectOtherAbility end"); +} + +void AmsStServiceAbilityD1::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityD1::DisConnectOtherAbility begin"); + for (auto callBack : connCallback_) { + DisconnectAbility(callBack); + sleep(1); + } + APP_LOGI("AmsStServiceAbilityD1::DisConnectOtherAbility end"); +} + +void AmsStServiceAbilityD1::StopSelfAbility() +{ + APP_LOGI("AmsStServiceAbilityD1::StopSelfAbility"); + + TerminateAbility(); +} + +void AmsStServiceAbilityD1::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityD1::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_D1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); +} +void AmsStServiceAbilityD1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityD1::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityD1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityD1::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_D1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityD1::OnStop() +{ + APP_LOGI("AmsStServiceAbilityD1::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_D1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityD1::GetDataByDataAbility() +{ + APP_LOGI("AmsStServiceAbilityD1::GetDataByDataAbility"); + + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + if (helper == nullptr) { + APP_LOGE("AmsStServiceAbilityD1::GetDataByDataAbility:helper == nullptr"); + return; + } + + Uri uri2("dataability:///com.ohos.amsst.service.appF.dataability"); + std::string mimeTypeFilter("mimeTypeFiltertest"); + std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); + + int count = result.size(); + if (count > 0) { + APP_LOGI("AmsStServiceAbilityD1::GetDataByDataAbility get data ability data info result > 0!"); + PublishEvent(APP_D1_RESP_EVENT_NAME, 1, "GetDataByDataAbility"); + } else { + APP_LOGI("AmsStServiceAbilityD1::GetDataByDataAbility get data ability data info result = 0!"); + PublishEvent(APP_D1_RESP_EVENT_NAME, 0, "GetDataByDataAbility"); + } +} +void AmsStServiceAbilityD1::OnActive() +{ + APP_LOGI("AmsStServiceAbilityD1::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_D1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityD1::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityD1::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_D1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityD1::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityD1::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_D1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void AmsStServiceAbilityD1::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; + AmsStServiceAbilityD1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +void AmsStServiceAbilityD1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + AmsStServiceAbilityD1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool AmsStServiceAbilityD1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityD1::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +bool AmsStServiceAbilityD1::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_D1_REQ_EVENTNAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void AmsStServiceAbilityD1::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("AmsStServiceAbilityD1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_D1_REQ_EVENTNAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "AmsStServiceAbilityD1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityD1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..7b159c901110b13059699ff1754003c17032e680 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceE" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceE\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceE") { + sources = [ "${subdemosystem_path}/src/ams_st_service_ability_e2.cpp" ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/config.json new file mode 100644 index 0000000000000000000000000000000000000000..2ca72585de733ab009b2dd323d89ad227dbd7a20 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/config.json @@ -0,0 +1,42 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appE", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestServiceE.src", + "name":"AmsSystemTestServiceE", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "AmsStServiceAbilityE2", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityE2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/include/ams_st_service_ability_e2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/include/ams_st_service_ability_e2.h new file mode 100644 index 0000000000000000000000000000000000000000..598b994882b55751f70d16194f16991704fcc4ec --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/include/ams_st_service_ability_e2.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_E2_ +#define AMS_ST_SERVICE_ABILITY_E2_ + +#include +#include + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +const std::string APP_E2_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_e2"; +const std::string APP_E2_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_e2"; +class AmsStServiceAbilityE2 : public Ability { +public: + ~AmsStServiceAbilityE2(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + void GetDataByDataAbility(); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + + typedef void (AmsStServiceAbilityE2::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + std::vector> connCallback_ = {}; + std::vector> stub_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_E2_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_E2_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityE2 *mainAbility_ = nullptr; + }; + class MyRemoteObject : public IRemoteObject { + public: + void GetDataByDataAbility(); + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_E2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/src/ams_st_service_ability_e2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/src/ams_st_service_ability_e2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72f58c88123d7c10dd2227ada0102894c220a3d8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/src/ams_st_service_ability_e2.cpp @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_e2.h" +#include "app_log_wrapper.h" +#include "ability_context.h" +#include "ability.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +int AmsStServiceAbilityE2::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map AmsStServiceAbilityE2::funcMap_ = { + {"StartOtherAbility", &AmsStServiceAbilityE2::StartOtherAbility}, + {"ConnectOtherAbility", &AmsStServiceAbilityE2::ConnectOtherAbility}, + {"DisConnectOtherAbility", &AmsStServiceAbilityE2::DisConnectOtherAbility}, +}; + +AmsStServiceAbilityE2::~AmsStServiceAbilityE2() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector AmsStServiceAbilityE2::Split(std::string str, const std::string &token) +{ + APP_LOGI("AmsStServiceAbilityE2::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void AmsStServiceAbilityE2::StartOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityE2::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("AmsStServiceAbilityE2::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void AmsStServiceAbilityE2::ConnectOtherAbility() +{ + APP_LOGI( + "AmsStServiceAbilityE2::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("AmsStServiceAbilityE2::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + stub_.push_back(new (std::nothrow) AbilityConnectCallback()); + connCallback_.push_back(new (std::nothrow) AbilityConnectionProxy(stub_[i])); + APP_LOGI("AmsStServiceAbilityE2::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_[i]); + sleep(1); + if (!ret) { + APP_LOGE("AmsStServiceAbilityE2::ConnectAbility failed!"); + } + } + } + APP_LOGI("AmsStServiceAbilityE2::ConnectOtherAbility end"); +} +void AmsStServiceAbilityE2::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityE2::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); +} +void AmsStServiceAbilityE2::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityE2::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityE2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityE2::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityE2::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityE2::DisConnectOtherAbility begin"); + if (connCallback_.size() > 0) { + DisconnectAbility(connCallback_[0]); + sleep(1); + } + APP_LOGI("AmsStServiceAbilityE2::DisConnectOtherAbility end"); +} + +void AmsStServiceAbilityE2::OnStop() +{ + APP_LOGI("AmsStServiceAbilityE2::onStop"); + + Ability::OnStop(); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityE2::GetDataByDataAbility() +{ + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + if (helper == nullptr) { + APP_LOGE("AmsStServiceAbilityE2::GetDataByDataAbility:helper == nullptr"); + return; + } + + Uri uri2("dataability:///com.ohos.amsst.service.appF.dataability"); + std::string mimeTypeFilter("mimeTypeFiltertest"); + std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); + + int count = result.size(); + if (count > 0) { + APP_LOGI("AmsStServiceAbilityE2::OnBackground get data ability data info result > 0!"); + PublishEvent(APP_E2_RESP_EVENT_NAME, 1, "GetDataByDataAbility"); + } else { + APP_LOGI("AmsStServiceAbilityE2::OnBackground get data ability data info result = 0!"); + PublishEvent(APP_E2_RESP_EVENT_NAME, 0, "GetDataByDataAbility"); + } +} +void AmsStServiceAbilityE2::OnActive() +{ + APP_LOGI("AmsStServiceAbilityE2::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityE2::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityE2::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityE2::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityE2::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} +sptr AmsStServiceAbilityE2::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityE2::OnConnect"); + + Ability::OnConnect(want); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return nullptr; +} +void AmsStServiceAbilityE2::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityE2::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_E2_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +void AmsStServiceAbilityE2::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; + AmsStServiceAbilityE2::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +void AmsStServiceAbilityE2::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + AmsStServiceAbilityE2::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool AmsStServiceAbilityE2::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityE2::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +bool AmsStServiceAbilityE2::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_E2_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void AmsStServiceAbilityE2::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("AmsStServiceAbilityE2::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_E2_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "AmsStServiceAbilityE2::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityE2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..90995f967d68c797e449eee31b7e964ad53f3d60 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceF" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceF\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceF") { + sources = [ "${subdemosystem_path}/src/ams_st_service_ability_f3.cpp" ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/config.json new file mode 100644 index 0000000000000000000000000000000000000000..875cb47e0bd478f49afbcec1458d7ae45d0de9e2 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/config.json @@ -0,0 +1,43 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appF", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestServiceF.src", + "name":"AmsSystemTestServiceF", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "AmsStServiceAbilityF3", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityF3 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "uri": "dataability://com.ohos.amsst.service.appF.dataability", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/include/ams_st_service_ability_f3.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/include/ams_st_service_ability_f3.h new file mode 100644 index 0000000000000000000000000000000000000000..945eea21b741af48c5823aa9419233aa6f49a33e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/include/ams_st_service_ability_f3.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_F3_ +#define AMS_ST_SERVICE_ABILITY_F3_ +#include +#include "ability_loader.h" + +namespace OHOS { +namespace AppExecFwk { +class AmsStServiceAbilityF3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_F3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/src/ams_st_service_ability_f3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/src/ams_st_service_ability_f3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d420fe0e44e0679e011d010ebfd43baed68b055 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/src/ams_st_service_ability_f3.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "app_log_wrapper.h" +#include "ams_st_service_ability_f3.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +const std::string APP_F3_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_f3"; + +std::vector AmsStServiceAbilityF3::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsStServiceAbilityF3 <<<>>>"); + PublishEvent(APP_F3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "GetFileTypes"); + std::vector fileType = {"filetypes"}; + return fileType; +} + +void AmsStServiceAbilityF3::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityF3::onStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_F3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); +} +void AmsStServiceAbilityF3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityF3::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityF3::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityF3::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_F3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityF3::OnStop() +{ + APP_LOGI("AmsStServiceAbilityF3::onStop"); + + Ability::OnStop(); + PublishEvent(APP_F3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityF3::OnActive() +{ + APP_LOGI("AmsStServiceAbilityF3::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_F3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityF3::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityF3::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_F3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityF3::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityF3::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_F3_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void AmsStServiceAbilityF3::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} +void AmsStServiceAbilityF3::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} +bool AmsStServiceAbilityF3::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityF3::PublishEvent eventName = %s, code = %d, data = %s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +REGISTER_AA(AmsStServiceAbilityF3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..243c4009eedd38d27280a9817c6e734e6c6bd6fd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceG" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceG\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceG") { + sources = [ "${subdemosystem_path}/src/ams_st_service_ability_g1.cpp" ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/config.json new file mode 100644 index 0000000000000000000000000000000000000000..20cdf19ff1d3237b567191068815f684f68f7dba --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/config.json @@ -0,0 +1,42 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appG", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.amsSystemTestServiceG.src", + "name":"amsSystemTestServiceG", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "AmsStServiceAbilityG1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityG1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/include/ams_st_service_ability_g1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/include/ams_st_service_ability_g1.h new file mode 100644 index 0000000000000000000000000000000000000000..af1b5d86e9847678aefd8fc8a8f9e3a383204b8f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/include/ams_st_service_ability_g1.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_G1_ +#define AMS_ST_SERVICE_ABILITY_G1_ + +#include +#include + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +const std::string APP_G1_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_g1"; +const std::string APP_G1_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_g1"; +class AmsStServiceAbilityG1 : public Ability { +public: + ~AmsStServiceAbilityG1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + void GetDataByDataAbility(); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + + typedef void (AmsStServiceAbilityG1::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + std::vector> connCallback_ = {}; + std::vector> stub_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_G1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_G1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityG1 *mainAbility_ = nullptr; + }; + class MyRemoteObject : public IRemoteObject { + public: + void GetDataByDataAbility(); + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_G1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/src/ams_st_service_ability_g1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/src/ams_st_service_ability_g1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..398c08ea02db732b8213364aba42d1e155c43b44 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/src/ams_st_service_ability_g1.cpp @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_g1.h" +#include "app_log_wrapper.h" +#include "ability_context.h" +#include "ability.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +int AmsStServiceAbilityG1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map AmsStServiceAbilityG1::funcMap_ = { + {"StartOtherAbility", &AmsStServiceAbilityG1::StartOtherAbility}, + {"ConnectOtherAbility", &AmsStServiceAbilityG1::ConnectOtherAbility}, + {"DisConnectOtherAbility", &AmsStServiceAbilityG1::DisConnectOtherAbility}, +}; + +AmsStServiceAbilityG1::~AmsStServiceAbilityG1() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector AmsStServiceAbilityG1::Split(std::string str, const std::string &token) +{ + APP_LOGI("AmsStServiceAbilityG1::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void AmsStServiceAbilityG1::StartOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityG1::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("AmsStServiceAbilityG1::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void AmsStServiceAbilityG1::ConnectOtherAbility() +{ + APP_LOGI( + "AmsStServiceAbilityG1::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("AmsStServiceAbilityG1::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + stub_.push_back(new (std::nothrow) AbilityConnectCallback()); + connCallback_.push_back(new (std::nothrow) AbilityConnectionProxy(stub_[i])); + APP_LOGI("AmsStServiceAbilityG1::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_[i]); + sleep(1); + if (!ret) { + APP_LOGE("AmsStServiceAbilityG1::ConnectAbility failed!"); + } + } + } + APP_LOGI("AmsStServiceAbilityG1::ConnectOtherAbility end"); +} +void AmsStServiceAbilityG1::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityG1::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); +} +void AmsStServiceAbilityG1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityG1::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityG1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityG1::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityG1::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityG1::DisConnectOtherAbility begin"); + for (auto &callback : connCallback_) { + DisconnectAbility(callback); + sleep(1); + } + APP_LOGI("AmsStServiceAbilityG1::DisConnectOtherAbility end"); +} + +void AmsStServiceAbilityG1::OnStop() +{ + APP_LOGI("AmsStServiceAbilityG1::onStop"); + + Ability::OnStop(); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityG1::GetDataByDataAbility() +{ + std::shared_ptr helper = DataAbilityHelper::Creator(std::shared_ptr(this)); + if (helper == nullptr) { + APP_LOGE("AmsStServiceAbilityG1::GetDataByDataAbility:helper == nullptr"); + return; + } + + Uri uri2("dataability:///com.ohos.amsst.service.appF.dataability"); + std::string mimeTypeFilter("mimeTypeFiltertest"); + std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); + + int count = result.size(); + if (count > 0) { + APP_LOGI("AmsStServiceAbilityG1::OnBackground get data ability data info result > 0!"); + PublishEvent(APP_G1_RESP_EVENT_NAME, 1, "GetDataByDataAbility"); + } else { + APP_LOGI("AmsStServiceAbilityG1::OnBackground get data ability data info result = 0!"); + PublishEvent(APP_G1_RESP_EVENT_NAME, 0, "GetDataByDataAbility"); + } +} +void AmsStServiceAbilityG1::OnActive() +{ + APP_LOGI("AmsStServiceAbilityG1::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityG1::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityG1::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityG1::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityG1::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} +sptr AmsStServiceAbilityG1::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityG1::OnConnect"); + + Ability::OnConnect(want); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return nullptr; +} +void AmsStServiceAbilityG1::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityG1::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_G1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +void AmsStServiceAbilityG1::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; + AmsStServiceAbilityG1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +void AmsStServiceAbilityG1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + AmsStServiceAbilityG1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool AmsStServiceAbilityG1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityG1::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +bool AmsStServiceAbilityG1::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_G1_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void AmsStServiceAbilityG1::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("AmsStServiceAbilityG1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_G1_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "AmsStServiceAbilityG1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityG1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..07e7175138ba9057ead7653a2c9c6ab8dc4cd0f0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") +subdemosystem_path = "${system_test_app_path}/amsSystemTestServiceH" +config("amsSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"amsSystemTestServiceH\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsSystemTestServiceH") { + sources = [ "${subdemosystem_path}/src/ams_st_service_ability_h1.cpp" ] + configs = [ ":amsSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/config.json new file mode 100644 index 0000000000000000000000000000000000000000..2f6929ab73cb084e8885cd5694e616ebb7f8e4e6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/config.json @@ -0,0 +1,42 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.service.appG", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestServiceH.src", + "name":"AmsSystemTestServiceH", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "feature" + }, + "abilities": [ + { + "name": "AmsStServiceAbilityH1", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "AmsStServiceAbilityH1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/include/ams_st_service_ability_h1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/include/ams_st_service_ability_h1.h new file mode 100644 index 0000000000000000000000000000000000000000..484daa68b6986d29fc8643fce7619ec7643f9d81 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/include/ams_st_service_ability_h1.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_ST_SERVICE_ABILITY_H1_ +#define AMS_ST_SERVICE_ABILITY_H1_ + +#include +#include + +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +const std::string APP_H1_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_h1"; +const std::string APP_H1_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_h1"; +class AmsStServiceAbilityH1 : public Ability { +public: + ~AmsStServiceAbilityH1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + void GetDataByDataAbility(); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + + typedef void (AmsStServiceAbilityH1::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + std::vector> connCallback_ = {}; + std::vector> stub_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_H1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_H1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + AmsStServiceAbilityH1 *mainAbility_ = nullptr; + }; + class MyRemoteObject : public IRemoteObject { + public: + void GetDataByDataAbility(); + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ST_SERVICE_ABILITY_H1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/src/ams_st_service_ability_h1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/src/ams_st_service_ability_h1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85e4e90e415e194b2654e625b5129a8714c1f90c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/src/ams_st_service_ability_h1.cpp @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ams_st_service_ability_h1.h" +#include "app_log_wrapper.h" +#include "ability_context.h" +#include "ability.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +int AmsStServiceAbilityH1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map AmsStServiceAbilityH1::funcMap_ = { + {"StartOtherAbility", &AmsStServiceAbilityH1::StartOtherAbility}, + {"ConnectOtherAbility", &AmsStServiceAbilityH1::ConnectOtherAbility}, + {"DisConnectOtherAbility", &AmsStServiceAbilityH1::DisConnectOtherAbility}, +}; + +AmsStServiceAbilityH1::~AmsStServiceAbilityH1() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector AmsStServiceAbilityH1::Split(std::string str, const std::string &token) +{ + APP_LOGI("AmsStServiceAbilityH1::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void AmsStServiceAbilityH1::StartOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityH1::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("AmsStServiceAbilityH1::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void AmsStServiceAbilityH1::ConnectOtherAbility() +{ + APP_LOGI( + "AmsStServiceAbilityH1::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("AmsStServiceAbilityH1::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("nextTargetBundleConn", nextTargetBundleConn_); + want.SetParam("nextTargetAbilityConn", nextTargetAbilityConn_); + stub_.push_back(new (std::nothrow) AbilityConnectCallback()); + connCallback_.push_back(new (std::nothrow) AbilityConnectionProxy(stub_[i])); + APP_LOGI("AmsStServiceAbilityH1::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_[i]); + sleep(1); + if (!ret) { + APP_LOGE("AmsStServiceAbilityH1::ConnectAbility failed!"); + } + } + } + APP_LOGI("AmsStServiceAbilityH1::ConnectOtherAbility end"); +} +void AmsStServiceAbilityH1::OnStart(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityH1::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); +} +void AmsStServiceAbilityH1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsStServiceAbilityH1::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void AmsStServiceAbilityH1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityH1::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void AmsStServiceAbilityH1::DisConnectOtherAbility() +{ + APP_LOGI("AmsStServiceAbilityH1::DisConnectOtherAbility begin"); + for (auto &callback : connCallback_) { + DisconnectAbility(callback); + sleep(1); + } + APP_LOGI("AmsStServiceAbilityH1::DisConnectOtherAbility end"); +} + +void AmsStServiceAbilityH1::OnStop() +{ + APP_LOGI("AmsStServiceAbilityH1::onStop"); + + Ability::OnStop(); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void AmsStServiceAbilityH1::GetDataByDataAbility() +{ + std::shared_ptr helper = DataAbilityHelper::Creator(std::shared_ptr(this)); + if (helper == nullptr) { + APP_LOGE("AmsStServiceAbilityH1::GetDataByDataAbility:helper == nullptr"); + return; + } + + Uri uri2("dataability:///com.ohos.amsst.service.appF.dataability"); + std::string mimeTypeFilter("mimeTypeFiltertest"); + std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); + + int count = result.size(); + if (count > 0) { + APP_LOGI("AmsStServiceAbilityH1::OnBackground get data ability data info result > 0!"); + PublishEvent(APP_H1_RESP_EVENT_NAME, 1, "GetDataByDataAbility"); + } else { + APP_LOGI("AmsStServiceAbilityH1::OnBackground get data ability data info result = 0!"); + PublishEvent(APP_H1_RESP_EVENT_NAME, 0, "GetDataByDataAbility"); + } +} +void AmsStServiceAbilityH1::OnActive() +{ + APP_LOGI("AmsStServiceAbilityH1::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void AmsStServiceAbilityH1::OnInactive() +{ + APP_LOGI("AmsStServiceAbilityH1::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void AmsStServiceAbilityH1::OnBackground() +{ + APP_LOGI("AmsStServiceAbilityH1::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} +sptr AmsStServiceAbilityH1::OnConnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityH1::OnConnect"); + + Ability::OnConnect(want); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnConnect"); + return nullptr; +} +void AmsStServiceAbilityH1::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsStServiceAbilityH1::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_H1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +void AmsStServiceAbilityH1::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; + AmsStServiceAbilityH1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +void AmsStServiceAbilityH1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + AmsStServiceAbilityH1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool AmsStServiceAbilityH1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("AmsStServiceAbilityH1::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +bool AmsStServiceAbilityH1::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_H1_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void AmsStServiceAbilityH1::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("AmsStServiceAbilityH1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_H1_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "AmsStServiceAbilityH1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} +REGISTER_AA(AmsStServiceAbilityH1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h b/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h new file mode 100644 index 0000000000000000000000000000000000000000..939b33dde92eb9900f3276b75ce9245fcfa44d9e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 ABILITY_APPEND_TEST_INFO_H +#define ABILITY_APPEND_TEST_INFO_H + +namespace OHOS { +namespace AppExecFwk { +const std::string g_EVENT_REQU_FIRST = "requ_com_ohos_amsst_appkit_first"; +const std::string g_EVENT_RESP_FIRST = "resp_com_ohos_amsst_appkit_first"; +const std::string g_EVENT_RESP_FIRST_LIFECYCLE = "resp_com_ohos_amsst_appkit_first_lifecycle"; + +const std::string g_EVENT_REQU_FIRSTB = "requ_com_ohos_amsst_appkit_firstb"; +const std::string g_EVENT_RESP_FIRSTB = "resp_com_ohos_amsst_appkit_firstb"; +const std::string g_EVENT_RESP_FIRSTB_LIFECYCLE = "resp_com_ohos_amsst_appkit_firstb_lifecycle"; + +const std::string g_EVENT_REQU_SECOND = "requ_com_ohos_amsst_appkit_second"; +const std::string g_EVENT_RESP_SECOND = "resp_com_ohos_amsst_appkit_second"; +const std::string g_EVENT_RESP_SECOND_LIFECYCLE = "resp_com_ohos_amsst_appkit_second_lifecycle"; + +const std::string g_EVENT_REQU_THIRD = "requ_com_ohos_amsst_appkit_third"; +const std::string g_EVENT_RESP_THIRD = "resp_com_ohos_amsst_appkit_third"; +const std::string g_EVENT_RESP_THIRD_LIFECYCLE = "resp_com_ohos_amsst_appkit_third_lifecycle"; + +const std::string g_EVENT_REQU_FOURTH = "requ_com_ohos_amsst_appkit_fourth"; +const std::string g_EVENT_RESP_FOURTH = "resp_com_ohos_amsst_appkit_fourth"; +const std::string g_EVENT_RESP_FOURTH_LIFECYCLE = "resp_com_ohos_amsst_appkit_fourth_lifecycle"; + +const std::string g_EVENT_REQU_FIFTH = "requ_com_ohos_amsst_appkit_fifth"; +const std::string g_EVENT_RESP_FIFTH = "resp_com_ohos_amsst_appkit_fifth"; +const std::string g_EVENT_RESP_FIFTH_LIFECYCLE = "resp_com_ohos_amsst_appkit_fifth_lifecycle"; + +const std::string g_EVENT_REQU_SIXTH = "requ_com_ohos_amsst_appkit_sixth"; +const std::string g_EVENT_RESP_SIXTH = "resp_com_ohos_amsst_appkit_sixth"; +const std::string g_EVENT_RESP_SIXTH_LIFECYCLE = "resp_com_ohos_amsst_appkit_sixth_lifecycle"; + +const std::string g_EVENT_REQU_MAIN = "requ_com_ohos_amsst_appkit_main"; +const std::string g_EVENT_RESP_MAIN = "resp_com_ohos_amsst_appkit_main"; +const std::string g_EVENT_RESP_MAIN_LIFECYCLE = "resp_com_ohos_amsst_appkit_main_lifecycle"; + +const std::string g_EVENT_REQU_MAIN_SUBSIDIARY = "requ_com_ohos_amsst_appkit_main_subsidiary"; +const std::string g_EVENT_RESP_MAIN_SUBSIDIARY = "resp_com_ohos_amsst_appkit_main_subsidiary"; +const std::string g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY = "resp_com_ohos_amsst_appkit_main_lifecycle_subsidiary"; + +const std::string g_EVENT_REQU_SECOND_SUBSIDIARY = "requ_com_ohos_amsst_appkit_second_subsidiary"; +const std::string g_EVENT_RESP_SECOND_SUBSIDIARY = "resp_com_ohos_amsst_appkit_second_subsidiary"; +const std::string g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY = "resp_com_ohos_amsst_appkit_second_lifecycle_subsidiary"; + +const int MAIN_ABILITY_A_CODE = 100; +const int SECOND_ABILITY_A_CODE = 200; +const int MAIN_ABILITY_B_CODE = 300; + +const int EXPECT_ST_ZERO = 0; + +const int MAIN_ABILITY_CODE = 100; +const int SECOND_ABILITY_CODE = 200; +const int THIRD_ABILITY_CODE = 300; +const int FOURTH_ABILITY_CODE = 400; +const int FIFTH_ABILITY_CODE = 500; +const int SIXTH_ABILITY_CODE = 600; + +const int MAIN_ABILITY_CODE_SUBSIDIARY = 10100; +const int SECOND_ABILITY_CODE_SUBSIDIARY = 10200; + +enum class AppendApi { + OnSetCaller, + TerminateAndRemoveMisson, + GetString, + GetStringArray, + GetIntArray, + GetPattern, + GetColor, + TerminateAbilityResult, + GetDispalyOrientation, + GetPreferencesDir, + StartAbilities, + GetColorMode, + SetColorMode, + IsFirstInMission, + End +}; + +enum class MissionStackApi { + LockMission = (int)AppendApi::End, + End +}; + +enum class TestAbilityState { + OnSaveAbilityState = (int)MissionStackApi::End, + OnRestoreAbilityState, + End +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // ABILITY_APPEND_TEST_INFO_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h b/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h new file mode 100644 index 0000000000000000000000000000000000000000..c6c6a41b6da9ff4523451eb9f2c11ce93e5583ef --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h @@ -0,0 +1,428 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 KIT_TEST_COMMON_INFO_H +#define KIT_TEST_COMMON_INFO_H + +namespace OHOS { +namespace AppExecFwk { +constexpr int pressureTimes = 3; +const std::string g_EVENT_REQU_FIRST = "requ_com_ohos_amsst_appkit_first"; +const std::string g_EVENT_RESP_FIRST = "resp_com_ohos_amsst_appkit_first"; +const std::string g_EVENT_RESP_FIRST_LIFECYCLE = "resp_com_ohos_amsst_appkit_first_lifecycle"; +const std::string g_EVENT_RESP_FIRST_LIFECYCLE_CALLBACK = "resp_com_ohos_amsst_appkit_first_lifecycle_callbacks"; +const std::string g_EVENT_RESP_FIRST_LIFECYCLE_OBSERVER = "resp_com_ohos_amsst_appkit_first_lifecycle_observer"; +const std::string g_EVENT_RESP_FIRST_LIFECYCLE_OBSERVER2 = "resp_com_ohos_amsst_appkit_first_lifecycle_observer2"; +const std::string g_EVENT_RESP_FIRST_ON_ABILITY_RESULT = "resp_com_ohos_amsst_appkit_first_onabilityresult"; +const std::string g_EVENT_RESP_FIRST_ON_BACK_PRESSED = "resp_com_ohos_amsst_appkit_first_onbackpressed"; +const std::string g_EVENT_RESP_FIRST_ON_NEW_WANT = "resp_com_ohos_amsst_appkit_first_onnewwant"; +const std::string g_EVENT_REQU_FIRSTB = "requ_com_ohos_amsst_appkit_firstb"; +const std::string g_EVENT_RESP_FIRSTB = "resp_com_ohos_amsst_appkit_firstb"; +const std::string g_EVENT_RESP_FIRSTB_LIFECYCLE = "resp_com_ohos_amsst_appkit_firstb_lifecycle"; +const std::string g_EVENT_REQU_SECOND = "requ_com_ohos_amsst_appkit_second"; +const std::string g_EVENT_RESP_SECOND = "resp_com_ohos_amsst_appkit_second"; +const std::string g_EVENT_RESP_SECOND_LIFECYCLE = "resp_com_ohos_amsst_appkit_second_lifecycle"; +const std::string g_EVENT_RESP_SECOND_ABILITY_CONTEXT = "resp_com_ohos_amsst_appkit_secondability_ability_context"; +const std::string g_EVENT_RESP_SECOND_ABILITY_API = "resp_com_ohos_amsst_appkit_secondability_ability_api"; +// PageAbility: ThirdAbility Constants to use +const std::string g_respPageThirdAbilityST = "resp_com_ohos_amsst_appkit_third_ability"; +const std::string g_requPageThirdAbilityST = "requ_com_ohos_amsst_appkit_third_ability"; +const std::vector g_requPageThirdAbilitySTVector = {g_requPageThirdAbilityST}; +// PageAbility: FourthAbility Constants to use +const std::string g_respPageFourthAbilityST = "resp_com_ohos_amsst_appkit_fourth_ability"; +const std::string g_requPageFourthAbilityST = "requ_com_ohos_amsst_appkit_fourth_ability"; +const std::vector g_requPageFourthAbilitySTVector = {g_requPageFourthAbilityST}; +// PageAbility: SixthAbility Constants to use +const std::string g_respPageSixthAbilityST = "resp_com_ohos_amsst_appkit_sixth_ability"; +const std::string g_respPageSixthAbilityLifecycleCallbacks = "resp_sixth_ability_lifecycle_callback"; +const std::string g_requPageSixthAbilityST = "requ_com_ohos_amsst_appkit_sixth_ability"; +const std::vector g_requPageSixthAbilitySTVector = {g_requPageSixthAbilityST}; +// PageAbility: KitTestAbilityManager Constants to use +const std::string g_respPageManagerAbilityST = "resp_com_ohos_amsst_appkit_manager_ability"; +const std::string g_requPageManagerAbilityST = "requ_com_ohos_amsst_appkit_manager_ability"; +const std::vector g_requPageManagerAbilitySTVector = {g_requPageManagerAbilityST}; +// PageAbility: KitTestAbilityManagerSecond Constants to use +const std::string g_respPageManagerSecondAbilityST = "resp_com_ohos_amsst_appkit_manager_second_ability"; +const std::string g_requPageManagerSecondAbilityST = "requ_com_ohos_amsst_appkit_manager_second_ability"; +const std::vector g_requPageManagerSecondAbilitySTVector = {g_requPageManagerSecondAbilityST}; +const std::string g_onAbilityStart = ":OnAbilityStart"; +const std::string g_onAbilityInactive = ":OnAbilityInactive"; +const std::string g_onAbilityBackground = ":OnAbilityBackground"; +const std::string g_onAbilityForeground = ":OnAbilityForeground"; +const std::string g_onAbilityActive = ":OnAbilityActive"; +const std::string g_onAbilityStop = ":OnAbilityStop"; +const std::string g_onAbilitySaveState = ":OnAbilitySaveState"; +const std::string g_memoryLevel = ":OnMemoryLevel"; +const std::string g_configuration = ":OnConfigurationUpdated"; +const std::string g_abilityStateOnStart = ":OnStart"; +const std::string g_abilityStateOnStop = ":OnStop"; +const std::string g_abilityStateOnActive = ":OnActive"; +const std::string g_abilityStateOnInactive = ":OnInactive"; +const std::string g_abilityStateOnBackground = ":OnBackground"; +const std::string g_abilityStateOnForeground = ":OnForeground"; +const std::string g_abilityStateOnNewWant = ":OnNewWant"; +const std::string g_EVENT_REQU_FIFTH = "requ_com_ohos_amsst_appkit_fifth"; +const std::string g_EVENT_RESP_FIFTH = "resp_com_ohos_amsst_appkit_fifth"; + +enum class WantApi { + WantCopy, + WantAssign, + AddEntity, + AddFlags, + ClearWant, + CountEntities, + FormatMimeType, + FormatType, + FormatUri, + FormatUriAndType, + GetAction, + GetBundle, + GetEntities, + GetElement, + GetUri, + GetUriString, + GetFlags, + GetScheme, + GetType, + HasEntity, + MakeMainAbility, + Marshalling, + ParseUri, + RemoveEntity, + RemoveFlags, + SetAction, + SetBundle, + SetElement, + SetElementName_String_String, + SetElementName_String_String_String, + SetFlags, + SetType, + SetUri, + SetUriAndType, + ToUri, + Unmarshalling, + WantParseUri, + WantToUri, + GetParams, + GetByteParam, + GetByteArrayParam, + GetBoolParam, + GetBoolArrayParam, + GetCharParam, + GetCharArrayParam, + GetIntParam, + GetIntArrayParam, + GetDoubleParam, + GetDoubleArrayParam, + GetFloatParam, + GetFloatArrayParam, + GetLongParam, + GetLongArrayParam, + GetShortParam, + GetShortArrayParam, + GetStringParam, + GetStringArrayParam, + SetParam_WantParams, + SetParam_byte, + SetParam_byte_array, + SetParam_bool, + SetParam_bool_array, + SetParam_char, + SetParam_char_array, + SetParam_int, + SetParam_int_array, + SetParam_double, + SetParam_double_array, + SetParam_float, + SetParam_float_array, + SetParam_long, + SetParam_long_array, + SetParam_short, + SetParam_short_array, + SetParam_string, + SetParam_string_array, + HasParameter, + ReplaceParams_WantParams, + ReplaceParams_Want, + RemoveParam, + GetOperation, + SetOperation, + OperationEquals, + CloneOperation, + End +}; + +enum class SkillsApi { + AddAction = (int)WantApi::End, + CountActions, + GetAction, + HasAction, + RemoveAction, + AddEntity, + CountEntities, + GetEntity, + HasEntity, + RemoveEntity, + AddAuthority, + CountAuthorities, + GetAuthority, + HasAuthority, + RemoveAuthority, + AddScheme, + CountSchemes, + GetScheme, + HasScheme, + RemoveScheme, + AddSchemeSpecificPart, + CountSchemeSpecificParts, + GetSchemeSpecificPart, + HasSchemeSpecificPart, + RemoveSchemeSpecificPart, + AddPath_String, + AddPath_String_MatchType, + AddPath_PatternMatcher, + AddPath_String_CountPaths, + AddPath_String_MatchType_CountPaths, + AddPath_PatternMatcher_CountPaths, + CountPaths, + AddPath_String_GetPath, + AddPath_String_MatchType_GetPath, + AddPath_PatternMatcher_GetPath, + GetPath, + AddPath_String_HasPath, + AddPath_String_MatchType_HasPath, + AddPath_PatternMatcher_HasPath, + HasPath, + RemovePath_String, + RemovePath_String_MatchType, + RemovePath_PatternMatcher, + RemovePath_Other, + AddType_String, + AddType_String_MatchType, + AddType_PatternMatcher, + AddType_String_CountTypes, + AddType_String_MatchType_CountTypes, + AddType_PatternMatcher_CountTypes, + CountTypes, + AddType_String_GetType, + AddType_String_MatchType_GetType, + AddType_PatternMatcher_GetType, + GetType, + AddType_String_HasType, + AddType_String_MatchType_HasType, + AddType_PatternMatcher_HasType, + HasType, + RemoveType_String, + RemoveType_String_MatchType, + RemoveType_PatternMatcher, + RemoveType_Other, + GetEntities, + GetWantParams, + Match, + Unmarshalling, + Marshalling, + Skills, + Skills_Skills, + End +}; + +enum class AbilityApi { + GetAbilityName = (int)SkillsApi::End, + GetAbilityPackage, + GetLifecycle, + GetWant, + GetWindow, + Dump, + OnStart, + OnActive, + OnBackground, + OnInactive, + OnStop, + OnForeground, + OnAbilityResult, + OnBackPressed, + OnNewWant, + Reload, + SetResult, + SetWant, + StartAbilityForResult_Want_int, + StartAbility_Want, + StartAbility_Want_AbilityStartSetting, + TerminateAbility, + BatchInsert, + GetType, + OnKeyDown, + OnKeyUp, + OnTouchEvent, + End +}; + +enum class AbilityContextApi { + GetApplicationInfo = (int)AbilityApi::End, + GetCacheDir, + GetCodeCacheDir, + GetDatabaseDir, + GetDataDir, + GetDir, + GetNoBackupFilesDir, + GetBundleManager, + VerifyCallingPermission, + VerifyPermission, + VerifySelfPermission, + GetBundleCodePath, + GetBundleName, + GetBundleResourcePath, + CanRequestPermission, + GetApplicationContext, + GetCallingAbility, + GetContext, + GetAbilityManager, + GetProcessInfo, + GetAppType, + GetCallingBundle, + StartAbility_Want_int, + TerminateAbility, + GetElementName, + GetHapModuleInfo, + End +}; + +enum class LifeCycleApi { + GetLifecycleState = (int)AbilityContextApi::End, + AddObserver, + DispatchLifecycle_Event_Want, + DispatchLifecycle_Event, + RemoveObserver, + End +}; + +enum class AbilityLifecycleCallbacksApi { + OnAbilityStart = (int)LifeCycleApi::End, + OnAbilityInactive, + OnAbilityBackground, + OnAbilityForeground, + OnAbilityActive, + OnAbilityStop, + OnAbilitySaveState, + End +}; + +enum class AbilityManagerApi { + ClearUpApplicationData = (int)AbilityLifecycleCallbacksApi::End, + GetAllRunningProcesses, + GetAllStackInfo, + QueryRecentAbilityMissionInfo, + QueryRunningAbilityMissionInfo, + MoveMissionToTop, + End +}; + +enum class ContextApi { + CanRequestPermission = (int)AbilityManagerApi::End, + DeleteFile, + GetAbilityInfo, + GetApplicationInfo, + GetApplicationContext, + GetBundleCodePath, + GetBundleManager, + GetBundleName, + GetBundleResourcePath, + GetCallingBundle, + GetCacheDir, + GetCodeCacheDir, + GetDatabaseDir, + GetDataDir, + GetDir, + GetFilesDir, + GetHapModuleInfo, + GetNoBackupFilesDir, + GetProcessName, + GetResourceManager, + VerifyCallingPermission, + VerifySelfPermission, + StartAbility_Want_int, + TerminateAbility_int, + CreateBundleContext, + VerifyCallingOrSelfPermission, + VerifyPermission, + End +}; + +enum class ElementNameApi { + SetElementDeviceID = (int)ContextApi::End, + SetElementBundleName, + SetElementAbilityName, + ClearElement, + End +}; + +enum class OHOSApplicationApi { + RegisterAbilityLifecycleCallbacks = (int)ElementNameApi::End, + UnregisterAbilityLifecycleCallbacks, + DispatchAbilitySavedState, + OnConfigurationUpdated, + OnMemoryLevel, + OnStart, + OnTerminate, + RegisterElementsCallbacks, + UnregisterElementsCallbacks, + End +}; + +enum class LifecycleObserverApi { + OnActive = (int)OHOSApplicationApi::End, + OnBackground, + OnForeground, + OnInactive, + OnStart, + OnStop, + OnStateChanged_Event_Want, + OnStateChanged_Event, + End +}; + +enum class ProcessInfoApi { + GetPid = (int)LifecycleObserverApi::End, + GetProcessName, + Marshalling, + Unmarshalling, + ProcessInfo, + ProcessInfo_String_int, + End +}; + +enum class RunningProcessInfoApi { + GetProcessName = (int)ProcessInfoApi::End, + GetPid, + GetUid, + End, +}; + +enum class WantParamsApi { + HasParam = (int)RunningProcessInfoApi::End, + IsEmpty, + Marshalling, + Unmarshalling, + Size, + WantParamsCopy, + GetParam, + KeySet, + Remove, + SetParam, + End, +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // KIT_TEST_COMMON_INFO_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..054b450a757624122324459880e38de1f0c7ec4e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +APP_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/fwkAbilityState" +TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsSystemTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${APP_DIR}/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"fwkAbilityState\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("fwkAbilityState") { + sources = [ + "${APP_DIR}/src/ability_state_main.cpp", + "${APP_DIR}/src/ability_state_second.cpp", + "${APP_DIR}/src/test_utils.cpp", + "${TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsSystemTestAConfig" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/config.json b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b0ac4ebdc6290970792a209e3a32eb0a9b17dbfa --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/config.json @@ -0,0 +1,51 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.fwkAbilityState", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.fwkAbilityState.src", + "name":"fwkAbilityState", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FwkAbilityStateMain", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "FwkAbilityStateMain", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "FwkAbilityStateSecond", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "FwkAbilityStateSecond", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/ability_state_main.h b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/ability_state_main.h new file mode 100755 index 0000000000000000000000000000000000000000..c354eda18ef97ef67f6cf8529b514329fa562516 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/ability_state_main.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FWK_ABILITY_STATE_ABILITY_A_H +#define FWK_ABILITY_STATE_ABILITY_A_H +#include +#include "ability.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "pac_map.h" +#include "stpageabilityevent.h" + +namespace OHOS { +namespace AppExecFwk { +class FwkAbilityStateMainSubscriber; +class FwkAbilityStateMain : public Ability { +public: + FwkAbilityStateMain() + { + mapAction_["StartNextAbility"] = [this](int code) { StartNextAbility(code); }; + } + ~FwkAbilityStateMain(); + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + + void Action(std::string action, int code); + void StartNextAbility(int code); + void DoCrash(std::string action, int code); + void BlockAndStart(std::string action, int code); + void OnBlockProcess(bool &bIsBlockFlag); + +private: + std::shared_ptr subscriber_; + std::string callback_seq; + std::string action; + std::unordered_map> mapAction_; + bool bIsBlockSave; + bool bIsBlockRestore; + void SubscribeEvent(); +}; + +class FwkAbilityStateMainSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FwkAbilityStateMainSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapAction_ = { + {"StartNextAbility", [this](std::string action, int code) { Action(action, code); }}, + {"DoCrash", [this](std::string action, int code) { DoCrash(action, code); }}, + {"BlockAndStart", [this](std::string action, int code) { BlockAndStart(action, code); }}, + }; + mainAbility = nullptr; + } + + void Action(std::string action, int code) + { + mainAbility->Action(action, code); + } + + void DoCrash(std::string action, int code) + { + mainAbility->DoCrash(action, code); + } + + void BlockAndStart(std::string action, int code) + { + mainAbility->BlockAndStart(action, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FwkAbilityStateMain *mainAbility; + std::unordered_map> mapAction_; + ~FwkAbilityStateMainSubscriber() = default; +}; +class CrashMaker { +public: + int CrashTry() + { + return this->crashData; + }; + +private: + int crashData = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FWK_ABILITY_STATE_ABILITY_A_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/ability_state_second.h b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/ability_state_second.h new file mode 100755 index 0000000000000000000000000000000000000000..015757e668c3a276039dff735f47f7b6a2a00c03 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/ability_state_second.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FWK_ABILITY_STATE_ABILITY_B_H +#define FWK_ABILITY_STATE_ABILITY_B_H +#include +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "pac_map.h" +#include "stpageabilityevent.h" + +namespace OHOS { +namespace AppExecFwk { +class FwkAbilityStateSecondSubscriber; +class FwkAbilityStateSecond : public Ability { +public: + FwkAbilityStateSecond() + { + mapAction_["Terminate"] = [this](int code) { TerminateThis(code); }; + } + ~FwkAbilityStateSecond(); + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + + void Action(std::string action, int code); + void TerminateThis(int code); + +private: + std::shared_ptr subscriber_; + std::unordered_map> mapAction_; + void SubscribeEvent(); + std::string callback_seq; +}; + +class FwkAbilityStateSecondSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FwkAbilityStateSecondSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) + : CommonEventSubscriber(sp) + { + mapAction_ = { + {"Terminate", [this](std::string action, int code) { Action(action, code); }}, + }; + mainAbility = nullptr; + } + + void Action(std::string action, int code) + { + mainAbility->Action(action, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + FwkAbilityStateSecond *mainAbility; + std::unordered_map> mapAction_; + ~FwkAbilityStateSecondSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FWK_ABILITY_STATE_ABILITY_B_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..8969a915e65912a2c9fb54f8bad24d013b8a92f1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/include/test_utils.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _TEST_UTILS_H_ +#define _TEST_UTILS_H_ +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _TEST_UTILS_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/ability_state_main.cpp b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/ability_state_main.cpp new file mode 100755 index 0000000000000000000000000000000000000000..85831e3eec88657229e5bcb9f6a71ca550991892 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/ability_state_main.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_state_main.h" +#include +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +std::string FwkAbilityState_Event_Resp_A = "resp_com_ohos_amsst_FwkAbilityStateA"; +std::string FwkAbilityState_Event_Requ_A = "requ_com_ohos_amsst_FwkAbilityStateA"; +const std::string FwkAbilityState_SaveData_Int = "int_data_1"; +int OnStopCode = 3; +int OnActiveCode = 1; +int OnBackgroundCode = 2; +int OnRestoreCheckCode = 4; +constexpr int iBlockTime = 12; +const int iSaveData = 12345; +} // namespace + +FwkAbilityStateMain::~FwkAbilityStateMain() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void FwkAbilityStateMain::OnStart(const Want &want) +{ + APP_LOGI("FwkAbilityStateMain::onStart"); + SubscribeEvent(); + bIsBlockRestore = want.HasParameter("StartType1"); + bIsBlockSave = false; + Ability::OnStart(want); + callback_seq += "OnStart"; +} + +void FwkAbilityStateMain::OnNewWant(const Want &want) +{ + APP_LOGI("FwkAbilityStateMain::OnNewWant"); + Ability::OnNewWant(want); + callback_seq += "OnNewWant"; +} + +void FwkAbilityStateMain::OnForeground(const Want &want) +{ + APP_LOGI("FwkAbilityStateMain::OnForeground"); + Ability::OnForeground(want); + callback_seq += "OnForeground"; +} + +void FwkAbilityStateMain::OnStop() +{ + APP_LOGI("FwkAbilityStateMain::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callback_seq += "OnStop"; + TestUtils::PublishEvent(FwkAbilityState_Event_Resp_A, OnStopCode, callback_seq); + callback_seq = ""; +} + +void FwkAbilityStateMain::OnActive() +{ + APP_LOGI("FwkAbilityStateMain::OnActive"); + Ability::OnActive(); + callback_seq += "OnActive"; + TestUtils::PublishEvent(FwkAbilityState_Event_Resp_A, OnActiveCode, callback_seq); + callback_seq = ""; +} + +void FwkAbilityStateMain::OnInactive() +{ + APP_LOGI("FwkAbilityStateMain::OnInactive"); + Ability::OnInactive(); + callback_seq += "OnInactive"; +} + +void FwkAbilityStateMain::OnBackground() +{ + APP_LOGI("FwkAbilityStateMain::OnBackground"); + Ability::OnBackground(); + callback_seq += "OnBackground"; + TestUtils::PublishEvent(FwkAbilityState_Event_Resp_A, OnBackgroundCode, callback_seq); + callback_seq = ""; +} + +void FwkAbilityStateMain::OnBlockProcess(bool &bIsBlockFlag) +{ + int i = iBlockTime; + + if (bIsBlockFlag) { + while (i-- > 0) { + APP_LOGI("FwkAbilityStateMain::OnBlockProcess time left %{public}d", i); + sleep(1); + } + bIsBlockFlag = false; + } +} + +void FwkAbilityStateMain::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("FwkAbilityStateMain::OnSaveAbilityState"); + OnBlockProcess(bIsBlockSave); + outState.PutIntValue(FwkAbilityState_SaveData_Int, iSaveData); + Ability::OnSaveAbilityState(outState); + callback_seq += "OnSaveAbilityState"; +} + +void FwkAbilityStateMain::OnRestoreAbilityState(const PacMap &inState) +{ + int iGetSaveData; + PacMap tmpPacMap; + + APP_LOGI("FwkAbilityStateMain::OnRestoreAbilityState"); + OnBlockProcess(bIsBlockRestore); + Ability::OnRestoreAbilityState(inState); + tmpPacMap = (PacMap)inState; + iGetSaveData = tmpPacMap.GetIntValue(FwkAbilityState_SaveData_Int); + if (iSaveData != iGetSaveData) { + TestUtils::PublishEvent(FwkAbilityState_Event_Resp_A, OnRestoreCheckCode, "NotEqual"); + APP_LOGI("FwkAbilityStateMain::restore not equal %{public}d", iGetSaveData); + } else { + APP_LOGI("FwkAbilityStateMain::restore equal %{public}d", iGetSaveData); + } + callback_seq += "OnRestoreAbilityState"; +} + +void FwkAbilityStateMain::SubscribeEvent() +{ + std::vector eventList = { + FwkAbilityState_Event_Requ_A, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FwkAbilityStateMainSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + if (strcmp(eventName.c_str(), FwkAbilityState_Event_Requ_A.c_str()) == 0) { + auto target = data.GetData(); + if (mapAction_.find(target) != mapAction_.end()) { + mapAction_[target](target, data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void FwkAbilityStateMain::Action(std::string action, int code) +{ + APP_LOGI("FwkAbilityStateMain::Action Called"); + if (mapAction_.find(action) != mapAction_.end()) { + mapAction_[action](code); + } +} + +void FwkAbilityStateMain::DoCrash(std::string action, int code) +{ + APP_LOGI("FwkAbilityStateMain::DoCrash Called"); + CrashMaker *pcCrashMaker = nullptr; + int a = pcCrashMaker->CrashTry(); + APP_LOGI("FwkAbilityStateMain::DoCrash Process %{public}d", a); +} + +void FwkAbilityStateMain::StartNextAbility(int code) +{ + std::string targetBundle = "com.ohos.amsst.fwkAbilityState"; + std::string targetAbility = "FwkAbilityStateSecond"; + Want want; + want.SetElementName(targetBundle, targetAbility); + StartAbility(want); +} + +void FwkAbilityStateMain::BlockAndStart(std::string action, int code) +{ + bIsBlockSave = true; + StartNextAbility(code); +} + +REGISTER_AA(FwkAbilityStateMain); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/ability_state_second.cpp b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/ability_state_second.cpp new file mode 100755 index 0000000000000000000000000000000000000000..67d56766fb555bf13171b75269f94a7dcf45e52e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/ability_state_second.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_state_second.h" +#include +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +std::string FwkAbilityState_Event_Requ_B = "requ_com_ohos_amsst_FwkAbilityStateB"; +std::string FwkAbilityState_Event_Resp_B = "resp_com_ohos_amsst_FwkAbilityStateB"; +int OnActiveCode = 1; + +FwkAbilityStateSecond::~FwkAbilityStateSecond() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void FwkAbilityStateSecond::OnStart(const Want &want) +{ + SubscribeEvent(); + APP_LOGI("FwkAbilityStateSecond::onStart"); + Ability::OnStart(want); + callback_seq += "OnStart"; +} + +void FwkAbilityStateSecond::OnForeground(const Want &want) +{ + APP_LOGI("FwkAbilityStateSecond::OnForeground"); + Ability::OnForeground(want); +} + +void FwkAbilityStateSecond::OnNewWant(const Want &want) +{ + APP_LOGI("FwkAbilityStateSecond::OnNewWant"); + Ability::OnNewWant(want); +} + +void FwkAbilityStateSecond::OnStop() +{ + APP_LOGI("FwkAbilityStateSecond::onStop"); + Ability::OnStop(); +} + +void FwkAbilityStateSecond::OnActive() +{ + APP_LOGI("FwkAbilityStateSecond::OnActive"); + Ability::OnActive(); + callback_seq += "OnActive"; + TestUtils::PublishEvent(FwkAbilityState_Event_Resp_B, OnActiveCode, callback_seq); + callback_seq = ""; +} + +void FwkAbilityStateSecond::OnInactive() +{ + APP_LOGI("FwkAbilityStateSecond::OnInactive"); + Ability::OnInactive(); +} + +void FwkAbilityStateSecond::OnBackground() +{ + APP_LOGI("FwkAbilityStateSecond::OnBackground"); + Ability::OnBackground(); +} + +void FwkAbilityStateSecond::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("FwkAbilityStateSecond::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); +} + +void FwkAbilityStateSecond::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("FwkAbilityStateSecond::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); +} + + +void FwkAbilityStateSecond::SubscribeEvent() +{ + std::vector eventList = { + FwkAbilityState_Event_Requ_B, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FwkAbilityStateSecondSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + if (strcmp(eventName.c_str(), FwkAbilityState_Event_Requ_B.c_str()) == 0) { + auto target = data.GetData(); + if (mapAction_.find(target) != mapAction_.end()) { + mapAction_[target](target, data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void FwkAbilityStateSecond::Action(std::string action, int code) +{ + if (mapAction_.find(action) != mapAction_.end()) { + mapAction_[action](code); + } +} + +void FwkAbilityStateSecond::TerminateThis(int code) +{ + std::string targetBundle = "com.ohos.amsst.fwkAbilityState"; + std::string targetAbility = "FwkAbilityStateSecond"; + Want want; + want.SetElementName(targetBundle, targetAbility); + StartAbility(want); +} + +REGISTER_AA(FwkAbilityStateSecond); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/test_utils.cpp new file mode 100755 index 0000000000000000000000000000000000000000..7b565fcd78fa2005b1600f94bda7519089720dd2 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/fwkAbilityState/src/test_utils.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "common_event_data.h" +#include "common_event_manager.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg(delim); + std::vector res = { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + return res; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8cb0e5d88070dd4885a92e039c4ad352751d4ac9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/serviceAbilityA" + +config("service_ability_a_config") { + visibility = [ ":*" ] + include_dirs = [ "${SUBDEMOSYSTEM_DIR}/include" ] + defines = [ + "APP_LOG_TAG = \"serviceAbilityA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("serviceAbilityA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/service_ability_a.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_ability_connect_callback_stub.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_ability_connection.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_first_ability.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":service_ability_a_config" ] + deps = [ + "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + ] + external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/config.json b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..2883bdda56b9dd9c7ec562f7969ba55319e5f03b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/config.json @@ -0,0 +1,51 @@ +{ + "app":{ + "bundleName": "com.ix.ServiceAbility", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ix.ServiceAbility.src", + "name":"VerifyActFirstAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "ServiceAbilityA", + "moduleType": "entry" + }, + "abilities": [{ + "name": "VerifyActFirstAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "VerifyActFirstAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ServiceAbilityA", + "icon": "$media:snowball", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + } + ] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/service_ability_a.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/service_ability_a.h new file mode 100644 index 0000000000000000000000000000000000000000..bc495fab410415fc503b6215d1d22753bd014c73 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/service_ability_a.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 MAIN_SERVICE_ABILITY_H +#define MAIN_SERVICE_ABILITY_H +#include "app_log_wrapper.h" +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "want.h" +#include "ability.h" +#include "ability_loader.h" + +using Want = OHOS::AAFwk::Want; +namespace OHOS { +namespace AppExecFwk { +class ServiceAbilityA : public Ability { +protected: + virtual void OnStart(const Want &want); + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId); + virtual sptr OnConnect(const Want &want); + virtual void OnDisconnect(const Want &want); + virtual void OnStop(); +}; + +class IServiceRemoteTest : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.ServiceRemoteTest"); + virtual int32_t ScheduleAdd(int32_t a, int32_t b) = 0; + virtual int32_t ScheduleSub(int32_t a, int32_t b) = 0; + enum { + // ipc id for OnAbilityConnectDone + ON_ABILITY_ADD = 0, + + // ipc id for OnAbilityDisConnectDone + ON_ABILITY_SUB + }; +}; + +class MockServiceRemoteTest : public IRemoteStub { +public: + MockServiceRemoteTest() = default; + virtual ~MockServiceRemoteTest() = default; + + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + return 0; + } + +private: + DISALLOW_COPY_AND_MOVE(MockServiceRemoteTest); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // MAIN_SERVICE_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_proxy.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..381cee206c5e52a5ecfb9e62d8e939e6506c6741 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_proxy.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_PROXY_H +#define OHOS_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_PROXY_H + +// #include "test_ability_connect_callback_interface.h" +#include "iremote_proxy.h" +#include "service_ability_a.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class AbilityConnectProxy + * AbilityConnect proxy. + */ +class TestAbilityConnectionProxy : public IRemoteProxy { +public: + explicit TestAbilityConnectionProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~TestAbilityConnectionProxy() + {} + + virtual int32_t ScheduleAdd(int32_t a, int32_t b) override; + virtual int32_t ScheduleSub(int32_t a, int32_t b) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_AAFWK_ABILITY_CONNECT_CALLBACK_PROXY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_stub.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..b7612fb37ad518432832ff1795ab91defa4abb6f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_stub.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_STUB_H +#define OHOS_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_STUB_H + +#include +#include +#include "service_ability_a.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class TestAbilityConnectionStub + * AbilityConnect Stub. + */ +class TestAbilityConnectionStub : public IRemoteStub { +public: + TestAbilityConnectionStub(); + virtual ~TestAbilityConnectionStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + DISALLOW_COPY_AND_MOVE(TestAbilityConnectionStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_AAFWK_ABILITY_CONNECT_CALLBACK_STUB_H diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connection.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..817131bc2d247f23dde0688ff154a06de215de86 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connection.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_TEST_ABILITY_THREAD_H +#define FOUNDATION_APPEXECFWK_TEST_ABILITY_THREAD_H + +#include "test_ability_connect_callback_stub.h" + +namespace OHOS { +namespace AppExecFwk { +class TestAbilityConnection : public TestAbilityConnectionStub { +public: + /** + * @brief Default constructor used to create a AbilityThread instance. + */ + TestAbilityConnection(); + ~TestAbilityConnection(); + + /** + * @description: Provide operating system ConnectAbility information to the observer + * @param want Indicates the structure containing connect information about the ability. + */ + virtual int32_t ScheduleAdd(int32_t a, int32_t b) override; + virtual int32_t ScheduleSub(int32_t a, int32_t b) override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_ABILITY_THREAD_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..4f4926ec6edd4af63bb20633492e08f47b994fee --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 VERIFY_ACT_FIRST_ABILITY +#define VERIFY_ACT_FIRST_ABILITY +#include "ability_loader.h" +#include "common_event.h" +#include "app_log_wrapper.h" +#include "common_event_manager.h" +#include "ability_connect_callback_stub.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int CONNECT_SERVICE_ABILITY = 0; +const int DISCONNECT_SERVICE_ABILITY = 1; +const int START_SERVICE_ABILITY = 2; +const int STOP_SERVICE_ABILITY = 3; +} // namespace +class VerifyActFirstAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class VerifyIOAbilityLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + VerifyIOAbilityLifecycleCallbacks() = default; + virtual ~VerifyIOAbilityLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability); + virtual void OnAbilityInactive(const std::shared_ptr &ability); + virtual void OnAbilityBackground(const std::shared_ptr &ability); + virtual void OnAbilityForeground(const std::shared_ptr &ability); + virtual void OnAbilityActive(const std::shared_ptr &ability); + virtual void OnAbilityStop(const std::shared_ptr &ability); + virtual void OnAbilitySaveState(const PacMap &outState); +}; + +class AbilityContextStartAbilityTest : public EventFwk::CommonEventSubscriber { +public: + AbilityContextStartAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) + : EventFwk::CommonEventSubscriber(sp){}; + virtual ~AbilityContextStartAbilityTest() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +}; +class ConnectServiceAbilityTest : public EventFwk::CommonEventSubscriber { +public: + ConnectServiceAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp, std::shared_ptr abilityContext, + sptr conne) + : EventFwk::CommonEventSubscriber(sp) + { + abilityContext_ = abilityContext; + conne_ = conne; + }; + virtual ~ConnectServiceAbilityTest() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + std::shared_ptr abilityContext_ = nullptr; + sptr conne_ = nullptr; +}; +class AbilityConnectionActFirst : public AAFwk::AbilityConnectionStub { +public: + AbilityConnectionActFirst(){}; + virtual ~AbilityConnectionActFirst(){}; + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + static int onAbilityConnectDoneCount; + static int onAbilityDisconnectDoneCount; + static int test; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // VERIFY_ACT_FIRST_ABILITY \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/service_ability_a.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/service_ability_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e03b4a9416985635805a4b6e7e55d1d1421bffdf --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/service_ability_a.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "service_ability_a.h" +// #include "app_log_wrapper.h" +// #include "iremote_broker.h" +// #include "iremote_object.h" +// #include "iremote_proxy.h" +// #include "iremote_stub.h" +// #include "main_service_ability.h" +#include "test_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +void ServiceAbilityA::OnStart(const Want &want) +{ + APP_LOGI("ServiceAbilityA OnStart"); + Ability::OnStart(want); +} +void ServiceAbilityA::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("ServiceAbilityA::OnCommand"); + Ability::OnCommand(want, restart, startId); +} +sptr ServiceAbilityA::OnConnect(const Want &want) +{ + APP_LOGI("ServiceAbilityA::OnConnect"); + sptr remoteObject = sptr(new (std::nothrow) TestAbilityConnection()); + + Ability::OnConnect(want); + return remoteObject->AsObject(); +} +void ServiceAbilityA::OnDisconnect(const Want &want) +{ + APP_LOGI("ServiceAbilityA::OnDisconnect"); + Ability::OnDisconnect(want); +} +void ServiceAbilityA::OnStop() +{ + APP_LOGI("ServiceAbilityA::OnStop"); + Ability::OnStop(); +} +REGISTER_AA(ServiceAbilityA); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connect_callback_stub.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connect_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3325b8b88bd1cd47ff3e29487f9d3fbf5321d65 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connect_callback_stub.cpp @@ -0,0 +1,145 @@ + +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_ability_connect_callback_stub.h" + +#include "test_ability_connect_callback_proxy.h" +#include "hilog_wrapper.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +bool TestAbilityConnectionProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(TestAbilityConnectionProxy::GetDescriptor())) { + HILOG_ERROR("write interface token failed"); + return false; + } + return true; +} + +int32_t TestAbilityConnectionProxy::ScheduleAdd(int32_t a, int32_t b) +{ + HILOG_DEBUG("%s, a:%d,b:%d", __func__, a, b); + + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return -1; + } + + if (!data.WriteInt32(a)) { + HILOG_ERROR("connect done element error"); + return -1; + } + + if (!data.WriteInt32(b)) { + HILOG_ERROR("connect done element error"); + return -1; + } + + error = Remote()->SendRequest(IServiceRemoteTest::ON_ABILITY_ADD, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("connect done fail, error: %d", error); + + int32_t result = 0; + if (!reply.ReadInt32(result)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + return result; + } + return -1; +} + +int32_t TestAbilityConnectionProxy::ScheduleSub(int32_t a, int32_t b) +{ + HILOG_DEBUG("%s, a:%d, b:%d", __func__, a, b); + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return -1; + } + + if (!data.WriteInt32(a)) { + HILOG_ERROR("connect done element error"); + return -1; + } + + if (!data.WriteInt32(b)) { + HILOG_ERROR("connect done element error"); + return -1; + } + error = Remote()->SendRequest(IServiceRemoteTest::ON_ABILITY_SUB, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("disconnect done fail, error: %d", error); + + int32_t result = 0; + if (!reply.ReadInt32(result)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + return result; + } + return -1; +} + +TestAbilityConnectionStub::TestAbilityConnectionStub() +{} + +TestAbilityConnectionStub::~TestAbilityConnectionStub() +{} + +int TestAbilityConnectionStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::u16string descriptor = TestAbilityConnectionStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + HILOG_INFO("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + switch (code) { + case IServiceRemoteTest::ON_ABILITY_ADD: { + int a = 0; + if (!data.ReadInt32(a)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + + int b = 0; + if (!data.ReadInt32(b)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + + uint32_t res = ScheduleAdd(a, b); + reply.WriteInt32(res); + + return NO_ERROR; + } + default: { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connection.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f2d3688caa660a7961a3ed6d30842fe74802bfd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connection.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +TestAbilityConnection::TestAbilityConnection() +{} +TestAbilityConnection::~TestAbilityConnection() +{} + +int32_t TestAbilityConnection::ScheduleAdd(int32_t a, int32_t b) +{ + return a + b; +} + +int32_t TestAbilityConnection::ScheduleSub(int32_t a, int32_t b) +{ + return a - b; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/verify_act_first_ability.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/verify_act_first_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..555ad8d1121a10c4ffaad3e38578427591b6f7c7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/verify_act_first_ability.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "verify_act_first_ability.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +void AbilityConnectionActFirst::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("AbilityConnectionActFirst OnAbilityConnectDone resultCode: %{public}d", resultCode); + APP_LOGI("AbilityConnectionActFirst OnAbilityConnectDone %{public}s", element.GetAbilityName().c_str()); + APP_LOGI("AbilityConnectionActFirst OnAbilityConnectDone %{public}p", remoteObject.GetRefPtr()); +} + +void AbilityConnectionActFirst::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + APP_LOGI("AbilityConnectionActFirst OnAbilityDisconnectDone resultCode: %{public}d", resultCode); + APP_LOGI("AbilityConnectionActFirst OnAbilityDisconnectDone : %{public}s", element.GetAbilityName().c_str()); +} +void VerifyIOAbilityLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilityStart called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI( + "----------VerifyIOAbilityLifecycleCallbacks::OnAbilityInactive called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI( + "----------VerifyIOAbilityLifecycleCallbacks::OnAbilityBackground called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI( + "----------VerifyIOAbilityLifecycleCallbacks::OnAbilityForeground called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilityActive called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilityStop called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} +void VerifyIOAbilityLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilitySaveState called.----------"); +} + +void VerifyActFirstAbility::OnStart(const Want &want) +{ + APP_LOGI("----------VerifyActFirstAbility::onStart begin----------"); + std::shared_ptr callback = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + + EventFwk::MatchingSkills MatchingSkillsFirst; + MatchingSkillsFirst.AddEvent("Test_AbilityContextStartAbility"); + EventFwk::CommonEventSubscribeInfo subscriberInfoFirst(MatchingSkillsFirst); + std::shared_ptr subscriberFirst = + std::make_shared(subscriberInfoFirst); + EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberFirst); + + EventFwk::MatchingSkills MatchingSkillsService; + MatchingSkillsService.AddEvent("Test_ServiceAbility"); + EventFwk::CommonEventSubscribeInfo subscriberInfoService(MatchingSkillsService); + sptr conne = new AbilityConnectionActFirst(); + std::shared_ptr serviceSubscriber = + std::make_shared(subscriberInfoService, Ability::GetContext(), conne); + EventFwk::CommonEventManager::SubscribeCommonEvent(serviceSubscriber); + APP_LOGI("----------VerifyActFirstAbility::onStart end----------"); + + Ability::OnStart(want); +} +void VerifyActFirstAbility::OnStop() +{ + APP_LOGI("----------VerifyActFirstAbility::onStop begin----------"); + APP_LOGI("----------VerifyActFirstAbility::onStop end----------"); + Ability::OnStop(); +} +void VerifyActFirstAbility::OnActive() +{ + APP_LOGI("----------VerifyActFirstAbility::OnActive begin----------"); + APP_LOGI("----------VerifyActFirstAbility::OnActive end----------"); + Ability::OnActive(); +} +void VerifyActFirstAbility::OnInactive() +{ + APP_LOGI("----------VerifyActFirstAbility::OnInactive begin----------"); + APP_LOGI("----------VerifyActFirstAbility::OnInactive end----------"); + Ability::OnInactive(); +} +void VerifyActFirstAbility::OnBackground() +{ + APP_LOGI("----------VerifyActFirstAbility::OnBackground begin----------"); + APP_LOGI("----------VerifyActFirstAbility::OnBackground end----------"); + Ability::OnBackground(); +} + +void AbilityContextStartAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest begin----------"); + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest start ability----------"); + auto abilityContext = std::make_shared(); + int requestCode = -1; + Want want; + std::string targetBundle = "com.ix.ServiceaAbility"; + std::string targetAbility = "MainServiceAbilityDemo"; + want.SetElementName(targetBundle, targetAbility); + abilityContext->StartAbility(want, requestCode); + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest start ability end----------"); + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest end----------"); +} + +void ConnectServiceAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + if (abilityContext_ == nullptr) { + APP_LOGI("----------ConnectServiceAbilityTest::OnReceiveEvent abilityContext_ == nullptr----------"); + return; + } + + Want want_service; + std::string targetBundle = "com.ix.ServiceaAbility"; + std::string targetAbility = "MainServiceAbilityDemo"; + want_service.SetElementName(targetBundle, targetAbility); + switch (data.GetCode()) { + case CONNECT_SERVICE_ABILITY: { + auto ret = abilityContext_->ConnectAbility(want_service, conne_); + APP_LOGI("connect ability return %{public}d", ret); + break; + } + case DISCONNECT_SERVICE_ABILITY: { + abilityContext_->DisconnectAbility(conne_); + break; + } + case START_SERVICE_ABILITY: { + abilityContext_->StartAbility(want_service, 0); + break; + } + case STOP_SERVICE_ABILITY: { + auto ret = abilityContext_->StopAbility(want_service); + APP_LOGI("stop ability return %{public}d", ret); + break; + } + default: + APP_LOGI("---------- ConnectServiceAbilityTest OnReceiveEvent default----------"); + break; + } +} +REGISTER_AA(VerifyActFirstAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..81e72023cd4a42d937f8ea1cefcfb1676438125f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("taskDispatcherTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/include", + ] + defines = [ + "APP_LOG_TAG = \"taskDispatcherTestA\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("taskDispatcherTestA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/src/task_dispatcher_tools.cpp", + ] + configs = [ + ":taskDispatcherTestAConfig", + "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher:system_test_task_dispatcher_config", + ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/config.json b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bc23c52d72f4a69fd62b7fd0bfd9f6a4dbe8fa83 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/config.json @@ -0,0 +1,53 @@ +{ + "app":{ + "bundleName": "com.ohos.TaskDispatcherA", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.TaskDispatcherA.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Second Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "service", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..076d475addf04a2de635da80055cbcd5522313d0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/main_ability.h @@ -0,0 +1,845 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H +#define AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "task_dispatcher_tools.h" +#include "task_dispatcher_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + MainAbility() + { + initGlobal(); + initParallel(); + initSerial(); + initSpec(); + initHybrid(); + initMultiApp(); + initPriority(); + initCancelTask(); + initExtra(); + } + void initGlobal() + { + mapCase_[(int)TestFunc::GLOBAL] = { + [this](int code) { GlobalCase1(code); }, + [this](int code) { GlobalCase2(code); }, + [this](int code) { GlobalCase3(code); }, + [this](int code) { GlobalCase4(code); }, + [this](int code) { GlobalCase5(code); }, + [this](int code) { GlobalCase6(code); }, + [this](int code) { GlobalCase7(code); }, + [this](int code) { GlobalCase8(code); }, + [this](int code) { GlobalCase9(code); }, + [this](int code) { GlobalCase10(code); }, + [this](int code) { GlobalCase11(code); }, + [this](int code) { GlobalCase12(code); }, + [this](int code) { GlobalCase13(code); }, + [this](int code) { GlobalCase14(code); }, + [this](int code) { GlobalCase15(code); }, + [this](int code) { GlobalCase16(code); }, + [this](int code) { GlobalCase17(code); }, + [this](int code) { GlobalCase18(code); }, + [this](int code) { GlobalCase19(code); }, + [this](int code) { GlobalCase20(code); }, + [this](int code) { GlobalCase21(code); }, + [this](int code) { GlobalCase22(code); }, + [this](int code) { GlobalCase23(code); }, + [this](int code) { GlobalCase24(code); }, + [this](int code) { GlobalCase25(code); }, + [this](int code) { GlobalCase26(code); }, + [this](int code) { GlobalCase27(code); }, + [this](int code) { GlobalCase28(code); }, + [this](int code) { GlobalCase29(code); }, + [this](int code) { GlobalCase30(code); }, + [this](int code) { GlobalCase31(code); }, + [this](int code) { GlobalCase32(code); }, + [this](int code) { GlobalCase33(code); }, + [this](int code) { GlobalCase34(code); }, + [this](int code) { GlobalCase35(code); }, + [this](int code) { GlobalCase36(code); }, + [this](int code) { GlobalCase37(code); }, + [this](int code) { GlobalCase38(code); }, + [this](int code) { GlobalCase39(code); }, + [this](int code) { GlobalCase40(code); }, + [this](int code) { GlobalCase41(code); }, + [this](int code) { GlobalCase42(code); }, + [this](int code) { GlobalCase43(code); }, + [this](int code) { GlobalCase44(code); }, + [this](int code) { GlobalCase45(code); }, + [this](int code) { GlobalCase46(code); }, + [this](int code) { GlobalCase47(code); }, + [this](int code) { GlobalCase48(code); }, + [this](int code) { GlobalCase49(code); }, + [this](int code) { GlobalCase50(code); }, + [this](int code) { GlobalCase51(code); }, + [this](int code) { GlobalCase52(code); }, + [this](int code) { GlobalCase53(code); }, + [this](int code) { GlobalCase54(code); }, + [this](int code) { GlobalCase55(code); }, + [this](int code) { GlobalCase56(code); }, + [this](int code) { GlobalCase57(code); }, + [this](int code) { GlobalCase58(code); }, + [this](int code) { GlobalCase59(code); }, + [this](int code) { GlobalCase60(code); }, + [this](int code) { GlobalCase61(code); }, + [this](int code) { GlobalCase62(code); }, + [this](int code) { GlobalCase63(code); }, + [this](int code) { GlobalCase64(code); }, + [this](int code) { GlobalCase65(code); }, + [this](int code) { GlobalCase66(code); }, + [this](int code) { GlobalCase67(code); }, + [this](int code) { GlobalCase68(code); }, + [this](int code) { GlobalCase69(code); }, + [this](int code) { GlobalCase70(code); }, + [this](int code) { GlobalCase71(code); }, + [this](int code) { GlobalCase72(code); }, + [this](int code) { GlobalCase73(code); }, + [this](int code) { GlobalCase74(code); }, + [this](int code) { GlobalCase75(code); }, + [this](int code) { GlobalCase76(code); }, + [this](int code) { GlobalCase77(code); }, + [this](int code) { GlobalCase78(code); }, + [this](int code) { GlobalCase79(code); }, + [this](int code) { GlobalCase80(code); }, + [this](int code) { GlobalCase81(code); }, + [this](int code) { GlobalCase82(code); }, + [this](int code) { GlobalCase83(code); }, + [this](int code) { GlobalCase84(code); }, + [this](int code) { GlobalCase85(code); }, + [this](int code) { GlobalCase86(code); }, + [this](int code) { GlobalCase87(code); }, + [this](int code) { GlobalCase88(code); }, + [this](int code) { GlobalCase89(code); }, + [this](int code) { GlobalCase90(code); }, + [this](int code) { GlobalCase91(code); }, + }; + } + + void initParallel() + { + mapCase_[(int)TestFunc::PARALLEL] = { + [this](int code) { ParallelCase1(code); }, + [this](int code) { ParallelCase2(code); }, + [this](int code) { ParallelCase3(code); }, + [this](int code) { ParallelCase4(code); }, + [this](int code) { ParallelCase5(code); }, + [this](int code) { ParallelCase6(code); }, + [this](int code) { ParallelCase7(code); }, + [this](int code) { ParallelCase8(code); }, + [this](int code) { ParallelCase9(code); }, + [this](int code) { ParallelCase10(code); }, + [this](int code) { ParallelCase11(code); }, + [this](int code) { ParallelCase12(code); }, + [this](int code) { ParallelCase13(code); }, + [this](int code) { ParallelCase14(code); }, + [this](int code) { ParallelCase15(code); }, + [this](int code) { ParallelCase16(code); }, + [this](int code) { ParallelCase17(code); }, + [this](int code) { ParallelCase18(code); }, + [this](int code) { ParallelCase19(code); }, + [this](int code) { ParallelCase20(code); }, + [this](int code) { ParallelCase21(code); }, + [this](int code) { ParallelCase22(code); }, + [this](int code) { ParallelCase23(code); }, + [this](int code) { ParallelCase24(code); }, + [this](int code) { ParallelCase25(code); }, + [this](int code) { ParallelCase26(code); }, + [this](int code) { ParallelCase27(code); }, + [this](int code) { ParallelCase28(code); }, + [this](int code) { ParallelCase29(code); }, + [this](int code) { ParallelCase30(code); }, + [this](int code) { ParallelCase31(code); }, + [this](int code) { ParallelCase32(code); }, + [this](int code) { ParallelCase33(code); }, + [this](int code) { ParallelCase34(code); }, + [this](int code) { ParallelCase35(code); }, + [this](int code) { ParallelCase36(code); }, + [this](int code) { ParallelCase37(code); }, + [this](int code) { ParallelCase38(code); }, + [this](int code) { ParallelCase39(code); }, + [this](int code) { ParallelCase40(code); }, + [this](int code) { ParallelCase41(code); }, + [this](int code) { ParallelCase42(code); }, + [this](int code) { ParallelCase43(code); }, + [this](int code) { ParallelCase44(code); }, + [this](int code) { ParallelCase45(code); }, + [this](int code) { ParallelCase46(code); }, + [this](int code) { ParallelCase47(code); }, + [this](int code) { ParallelCase48(code); }, + [this](int code) { ParallelCase49(code); }, + [this](int code) { ParallelCase50(code); }, + [this](int code) { ParallelCase51(code); }, + [this](int code) { ParallelCase52(code); }, + [this](int code) { ParallelCase53(code); }, + [this](int code) { ParallelCase54(code); }, + [this](int code) { ParallelCase55(code); }, + [this](int code) { ParallelCase56(code); }, + [this](int code) { ParallelCase57(code); }, + [this](int code) { ParallelCase58(code); }, + [this](int code) { ParallelCase59(code); }, + [this](int code) { ParallelCase60(code); }, + [this](int code) { ParallelCase61(code); }, + [this](int code) { ParallelCase62(code); }, + [this](int code) { ParallelCase63(code); }, + [this](int code) { ParallelCase64(code); }, + [this](int code) { ParallelCase65(code); }, + [this](int code) { ParallelCase66(code); }, + [this](int code) { ParallelCase67(code); }, + [this](int code) { ParallelCase68(code); }, + [this](int code) { ParallelCase69(code); }, + [this](int code) { ParallelCase70(code); }, + [this](int code) { ParallelCase71(code); }, + [this](int code) { ParallelCase72(code); }, + [this](int code) { ParallelCase73(code); }, + [this](int code) { ParallelCase74(code); }, + [this](int code) { ParallelCase75(code); }, + [this](int code) { ParallelCase76(code); }, + [this](int code) { ParallelCase77(code); }, + [this](int code) { ParallelCase78(code); }, + [this](int code) { ParallelCase79(code); }, + [this](int code) { ParallelCase80(code); }, + [this](int code) { ParallelCase81(code); }, + [this](int code) { ParallelCase82(code); }, + [this](int code) { ParallelCase83(code); }, + [this](int code) { ParallelCase84(code); }, + [this](int code) { ParallelCase85(code); }, + [this](int code) { ParallelCase86(code); }, + [this](int code) { ParallelCase87(code); }, + [this](int code) { ParallelCase88(code); }, + [this](int code) { ParallelCase89(code); }, + [this](int code) { ParallelCase90(code); }, + [this](int code) { ParallelCase91(code); }, + [this](int code) { ParallelCase92(code); }, + [this](int code) { ParallelCase93(code); }, + [this](int code) { ParallelCase94(code); }, + [this](int code) { ParallelCase95(code); }, + [this](int code) { ParallelCase96(code); }, + [this](int code) { ParallelCase97(code); }, + [this](int code) { ParallelCase98(code); }, + [this](int code) { ParallelCase99(code); }, + [this](int code) { ParallelCase100(code); }, + [this](int code) { ParallelCase101(code); }, + [this](int code) { ParallelCase102(code); }, + [this](int code) { ParallelCase103(code); }, + [this](int code) { ParallelCase104(code); }, + [this](int code) { ParallelCase105(code); }, + [this](int code) { ParallelCase106(code); }, + [this](int code) { ParallelCase107(code); }, + [this](int code) { ParallelCase108(code); }, + [this](int code) { ParallelCase109(code); }, + [this](int code) { ParallelCase110(code); }, + [this](int code) { ParallelCase111(code); }, + [this](int code) { ParallelCase112(code); }, + [this](int code) { ParallelCase113(code); }, + [this](int code) { ParallelCase114(code); }, + [this](int code) { ParallelCase115(code); }, + [this](int code) { ParallelCase116(code); }, + [this](int code) { ParallelCase117(code); }, + }; + } + void initSerial() + { + mapCase_[(int)TestFunc::SERIAL] = { + [this](int code) { SerialCase1(code); }, + [this](int code) { SerialCase2(code); }, + [this](int code) { SerialCase3(code); }, + [this](int code) { SerialCase4(code); }, + [this](int code) { SerialCase5(code); }, + [this](int code) { SerialCase6(code); }, + [this](int code) { SerialCase7(code); }, + [this](int code) { SerialCase8(code); }, + [this](int code) { SerialCase9(code); }, + [this](int code) { SerialCase10(code); }, + [this](int code) { SerialCase11(code); }, + [this](int code) { SerialCase12(code); }, + [this](int code) { SerialCase13(code); }, + [this](int code) { SerialCase14(code); }, + [this](int code) { SerialCase15(code); }, + [this](int code) { SerialCase16(code); }, + [this](int code) { SerialCase17(code); }, + [this](int code) { SerialCase18(code); }, + [this](int code) { SerialCase19(code); }, + [this](int code) { SerialCase20(code); }, + [this](int code) { SerialCase21(code); }, + [this](int code) { SerialCase22(code); }, + [this](int code) { SerialCase23(code); }, + [this](int code) { SerialCase24(code); }, + [this](int code) { SerialCase25(code); }, + [this](int code) { SerialCase26(code); }, + [this](int code) { SerialCase27(code); }, + [this](int code) { SerialCase28(code); }, + [this](int code) { SerialCase29(code); }, + [this](int code) { SerialCase30(code); }, + [this](int code) { SerialCase31(code); }, + [this](int code) { SerialCase32(code); }, + [this](int code) { SerialCase33(code); }, + [this](int code) { SerialCase34(code); }, + [this](int code) { SerialCase35(code); }, + [this](int code) { SerialCase36(code); }, + [this](int code) { SerialCase37(code); }, + [this](int code) { SerialCase38(code); }, + [this](int code) { SerialCase39(code); }, + [this](int code) { SerialCase40(code); }, + [this](int code) { SerialCase41(code); }, + [this](int code) { SerialCase42(code); }, + [this](int code) { SerialCase43(code); }, + [this](int code) { SerialCase44(code); }, + [this](int code) { SerialCase45(code); }, + [this](int code) { SerialCase46(code); }, + [this](int code) { SerialCase47(code); }, + [this](int code) { SerialCase48(code); }, + [this](int code) { SerialCase49(code); }, + [this](int code) { SerialCase50(code); }, + [this](int code) { SerialCase51(code); }, + [this](int code) { SerialCase52(code); }, + }; + } + void initSpec() + { + mapCase_[(int)TestFunc::SPEC] = { + [this](int code) { SpecCase1(code); }, + [this](int code) { SpecCase2(code); }, + [this](int code) { SpecCase3(code); }, + [this](int code) { SpecCase4(code); }, + [this](int code) { SpecCase5(code); }, + [this](int code) { SpecCase6(code); }, + [this](int code) { SpecCase7(code); }, + [this](int code) { SpecCase8(code); }, + [this](int code) { SpecCase9(code); }, + [this](int code) { SpecCase10(code); }, + [this](int code) { SpecCase11(code); }, + [this](int code) { SpecCase12(code); }, + [this](int code) { SpecCase13(code); }, + [this](int code) { SpecCase14(code); }, + [this](int code) { SpecCase15(code); }, + [this](int code) { SpecCase16(code); }, + [this](int code) { SpecCase17(code); }, + [this](int code) { SpecCase18(code); }, + [this](int code) { SpecCase19(code); }, + [this](int code) { SpecCase20(code); }, + [this](int code) { SpecCase21(code); }, + [this](int code) { SpecCase22(code); }, + [this](int code) { SpecCase23(code); }, + [this](int code) { SpecCase24(code); }, + [this](int code) { SpecCase25(code); }, + [this](int code) { SpecCase26(code); }, + [this](int code) { SpecCase27(code); }, + [this](int code) { SpecCase28(code); }, + [this](int code) { SpecCase29(code); }, + [this](int code) { SpecCase30(code); }, + [this](int code) { SpecCase31(code); }, + [this](int code) { SpecCase32(code); }, + [this](int code) { SpecCase33(code); }, + [this](int code) { SpecCase34(code); }, + [this](int code) { SpecCase35(code); }, + [this](int code) { SpecCase36(code); }, + [this](int code) { SpecCase37(code); }, + [this](int code) { SpecCase38(code); }, + [this](int code) { SpecCase39(code); }, + [this](int code) { SpecCase40(code); }, + [this](int code) { SpecCase41(code); }, + [this](int code) { SpecCase42(code); }, + [this](int code) { SpecCase43(code); }, + [this](int code) { SpecCase44(code); }, + [this](int code) { SpecCase45(code); }, + [this](int code) { SpecCase46(code); }, + [this](int code) { SpecCase47(code); }, + [this](int code) { SpecCase48(code); }, + [this](int code) { SpecCase49(code); }, + [this](int code) { SpecCase50(code); }, + [this](int code) { SpecCase51(code); }, + [this](int code) { SpecCase52(code); }, + }; + } + void initHybrid() + { + mapCase_[(int)TestFunc::HYBRID] = { + [this](int code) { HybridCase1(code); }, + [this](int code) { HybridCase2(code); }, + [this](int code) { HybridCase3(code); }, + [this](int code) { HybridCase4(code); }, + [this](int code) { HybridCase5(code); }, + [this](int code) { HybridCase6(code); }, + [this](int code) { HybridCase7(code); }, + [this](int code) { HybridCase8(code); }, + [this](int code) { HybridCase9(code); }, + [this](int code) { HybridCase10(code); }, + [this](int code) { HybridCase11(code); }, + [this](int code) { HybridCase12(code); }, + [this](int code) { HybridCase13(code); }, + [this](int code) { HybridCase14(code); }, + [this](int code) { HybridCase15(code); }, + [this](int code) { HybridCase16(code); }, + [this](int code) { HybridCase17(code); }, + [this](int code) { HybridCase18(code); }, + [this](int code) { HybridCase19(code); }, + [this](int code) { HybridCase20(code); }, + [this](int code) { HybridCase21(code); }, + [this](int code) { HybridCase22(code); }, + [this](int code) { HybridCase23(code); }, + [this](int code) { HybridCase24(code); }, + [this](int code) { HybridCase25(code); }, + [this](int code) { HybridCase26(code); }, + [this](int code) { HybridCase27(code); }, + }; + } + void initMultiApp() + { + mapCase_[(int)TestFunc::MULTI_APP] = { + [this](int code) { MultiAppCase1(code); }, + [this](int code) { MultiAppCase2(code); }, + [this](int code) { MultiAppCase3(code); }, + [this](int code) { MultiAppCase4(code); }, + }; + } + void initPriority() + { + mapCase_[(int)TestFunc::PRIORITY] = { + [this](int code) { PriorityCase1(code); }, + [this](int code) { PriorityCase2(code); }, + [this](int code) { PriorityCase3(code); }, + [this](int code) { PriorityCase4(code); }, + [this](int code) { PriorityCase5(code); }, + }; + } + void initCancelTask() + { + mapCase_[(int)TestFunc::CANCEL_TASK] = { + [this](int code) { RevokeCase1(code); }, + [this](int code) { RevokeCase2(code); }, + [this](int code) { RevokeCase3(code); }, + [this](int code) { RevokeCase4(code); }, + [this](int code) { RevokeCase5(code); }, + [this](int code) { RevokeCase6(code); }, + }; + } + void initExtra() + { + mapCase_[(int)TestFunc::EXTRA] = { + [this](int code) { ExtraCase1(code); }, + }; + } + + void SubscribeEvent(); + void TestDispatcher(int apiIndex, int caseIndex, int code); + int Dispatch(STtools::TestSetting outer, STtools::TestSetting inner); + + void GlobalCase1(int code); + void GlobalCase2(int code); + void GlobalCase3(int code); + void GlobalCase4(int code); + void GlobalCase5(int code); + void GlobalCase6(int code); + void GlobalCase7(int code); + void GlobalCase8(int code); + void GlobalCase9(int code); + void GlobalCase10(int code); + void GlobalCase11(int code); + void GlobalCase12(int code); + void GlobalCase13(int code); + void GlobalCase14(int code); + void GlobalCase15(int code); + void GlobalCase16(int code); + void GlobalCase17(int code); + void GlobalCase18(int code); + void GlobalCase19(int code); + void GlobalCase20(int code); + void GlobalCase21(int code); + void GlobalCase22(int code); + void GlobalCase23(int code); + void GlobalCase24(int code); + void GlobalCase25(int code); + void GlobalCase26(int code); + void GlobalCase27(int code); + void GlobalCase28(int code); + void GlobalCase29(int code); + void GlobalCase30(int code); + void GlobalCase31(int code); + void GlobalCase32(int code); + void GlobalCase33(int code); + void GlobalCase34(int code); + void GlobalCase35(int code); + void GlobalCase36(int code); + void GlobalCase37(int code); + void GlobalCase38(int code); + void GlobalCase39(int code); + void GlobalCase40(int code); + void GlobalCase41(int code); + void GlobalCase42(int code); + void GlobalCase43(int code); + void GlobalCase44(int code); + void GlobalCase45(int code); + void GlobalCase46(int code); + void GlobalCase47(int code); + void GlobalCase48(int code); + void GlobalCase49(int code); + void GlobalCase50(int code); + void GlobalCase51(int code); + void GlobalCase52(int code); + void GlobalCase53(int code); + void GlobalCase54(int code); + void GlobalCase55(int code); + void GlobalCase56(int code); + void GlobalCase57(int code); + void GlobalCase58(int code); + void GlobalCase59(int code); + void GlobalCase60(int code); + void GlobalCase61(int code); + void GlobalCase62(int code); + void GlobalCase63(int code); + void GlobalCase64(int code); + void GlobalCase65(int code); + void GlobalCase66(int code); + void GlobalCase67(int code); + void GlobalCase68(int code); + void GlobalCase69(int code); + void GlobalCase70(int code); + void GlobalCase71(int code); + void GlobalCase72(int code); + void GlobalCase73(int code); + void GlobalCase74(int code); + void GlobalCase75(int code); + void GlobalCase76(int code); + void GlobalCase77(int code); + void GlobalCase78(int code); + void GlobalCase79(int code); + void GlobalCase80(int code); + void GlobalCase81(int code); + void GlobalCase82(int code); + void GlobalCase83(int code); + void GlobalCase84(int code); + void GlobalCase85(int code); + void GlobalCase86(int code); + void GlobalCase87(int code); + void GlobalCase88(int code); + void GlobalCase89(int code); + void GlobalCase90(int code); + void GlobalCase91(int code); + void ParallelCase1(int code); + void ParallelCase2(int code); + void ParallelCase3(int code); + void ParallelCase4(int code); + void ParallelCase5(int code); + void ParallelCase6(int code); + void ParallelCase7(int code); + void ParallelCase8(int code); + void ParallelCase9(int code); + void ParallelCase10(int code); + void ParallelCase11(int code); + void ParallelCase12(int code); + void ParallelCase13(int code); + void ParallelCase14(int code); + void ParallelCase15(int code); + void ParallelCase16(int code); + void ParallelCase17(int code); + void ParallelCase18(int code); + void ParallelCase19(int code); + void ParallelCase20(int code); + void ParallelCase21(int code); + void ParallelCase22(int code); + void ParallelCase23(int code); + void ParallelCase24(int code); + void ParallelCase25(int code); + void ParallelCase26(int code); + void ParallelCase27(int code); + void ParallelCase28(int code); + void ParallelCase29(int code); + void ParallelCase30(int code); + void ParallelCase31(int code); + void ParallelCase32(int code); + void ParallelCase33(int code); + void ParallelCase34(int code); + void ParallelCase35(int code); + void ParallelCase36(int code); + void ParallelCase37(int code); + void ParallelCase38(int code); + void ParallelCase39(int code); + void ParallelCase40(int code); + void ParallelCase41(int code); + void ParallelCase42(int code); + void ParallelCase43(int code); + void ParallelCase44(int code); + void ParallelCase45(int code); + void ParallelCase46(int code); + void ParallelCase47(int code); + void ParallelCase48(int code); + void ParallelCase49(int code); + void ParallelCase50(int code); + void ParallelCase51(int code); + void ParallelCase52(int code); + void ParallelCase53(int code); + void ParallelCase54(int code); + void ParallelCase55(int code); + void ParallelCase56(int code); + void ParallelCase57(int code); + void ParallelCase58(int code); + void ParallelCase59(int code); + void ParallelCase60(int code); + void ParallelCase61(int code); + void ParallelCase62(int code); + void ParallelCase63(int code); + void ParallelCase64(int code); + void ParallelCase65(int code); + void ParallelCase66(int code); + void ParallelCase67(int code); + void ParallelCase68(int code); + void ParallelCase69(int code); + void ParallelCase70(int code); + void ParallelCase71(int code); + void ParallelCase72(int code); + void ParallelCase73(int code); + void ParallelCase74(int code); + void ParallelCase75(int code); + void ParallelCase76(int code); + void ParallelCase77(int code); + void ParallelCase78(int code); + void ParallelCase79(int code); + void ParallelCase80(int code); + void ParallelCase81(int code); + void ParallelCase82(int code); + void ParallelCase83(int code); + void ParallelCase84(int code); + void ParallelCase85(int code); + void ParallelCase86(int code); + void ParallelCase87(int code); + void ParallelCase88(int code); + void ParallelCase89(int code); + void ParallelCase90(int code); + void ParallelCase91(int code); + void ParallelCase92(int code); + void ParallelCase93(int code); + void ParallelCase94(int code); + void ParallelCase95(int code); + void ParallelCase96(int code); + void ParallelCase97(int code); + void ParallelCase98(int code); + void ParallelCase99(int code); + void ParallelCase100(int code); + void ParallelCase101(int code); + void ParallelCase102(int code); + void ParallelCase103(int code); + void ParallelCase104(int code); + void ParallelCase105(int code); + void ParallelCase106(int code); + void ParallelCase107(int code); + void ParallelCase108(int code); + void ParallelCase109(int code); + void ParallelCase110(int code); + void ParallelCase111(int code); + void ParallelCase112(int code); + void ParallelCase113(int code); + void ParallelCase114(int code); + void ParallelCase115(int code); + void ParallelCase116(int code); + void ParallelCase117(int code); + void SerialCase1(int code); + void SerialCase2(int code); + void SerialCase3(int code); + void SerialCase4(int code); + void SerialCase5(int code); + void SerialCase6(int code); + void SerialCase7(int code); + void SerialCase8(int code); + void SerialCase9(int code); + void SerialCase10(int code); + void SerialCase11(int code); + void SerialCase12(int code); + void SerialCase13(int code); + void SerialCase14(int code); + void SerialCase15(int code); + void SerialCase16(int code); + void SerialCase17(int code); + void SerialCase18(int code); + void SerialCase19(int code); + void SerialCase20(int code); + void SerialCase21(int code); + void SerialCase22(int code); + void SerialCase23(int code); + void SerialCase24(int code); + void SerialCase25(int code); + void SerialCase26(int code); + void SerialCase27(int code); + void SerialCase28(int code); + void SerialCase29(int code); + void SerialCase30(int code); + void SerialCase31(int code); + void SerialCase32(int code); + void SerialCase33(int code); + void SerialCase34(int code); + void SerialCase35(int code); + void SerialCase36(int code); + void SerialCase37(int code); + void SerialCase38(int code); + void SerialCase39(int code); + void SerialCase40(int code); + void SerialCase41(int code); + void SerialCase42(int code); + void SerialCase43(int code); + void SerialCase44(int code); + void SerialCase45(int code); + void SerialCase46(int code); + void SerialCase47(int code); + void SerialCase48(int code); + void SerialCase49(int code); + void SerialCase50(int code); + void SerialCase51(int code); + void SerialCase52(int code); + void SpecCase1(int code); + void SpecCase2(int code); + void SpecCase3(int code); + void SpecCase4(int code); + void SpecCase5(int code); + void SpecCase6(int code); + void SpecCase7(int code); + void SpecCase8(int code); + void SpecCase9(int code); + void SpecCase10(int code); + void SpecCase11(int code); + void SpecCase12(int code); + void SpecCase13(int code); + void SpecCase14(int code); + void SpecCase15(int code); + void SpecCase16(int code); + void SpecCase17(int code); + void SpecCase18(int code); + void SpecCase19(int code); + void SpecCase20(int code); + void SpecCase21(int code); + void SpecCase22(int code); + void SpecCase23(int code); + void SpecCase24(int code); + void SpecCase25(int code); + void SpecCase26(int code); + void SpecCase27(int code); + void SpecCase28(int code); + void SpecCase29(int code); + void SpecCase30(int code); + void SpecCase31(int code); + void SpecCase32(int code); + void SpecCase33(int code); + void SpecCase34(int code); + void SpecCase35(int code); + void SpecCase36(int code); + void SpecCase37(int code); + void SpecCase38(int code); + void SpecCase39(int code); + void SpecCase40(int code); + void SpecCase41(int code); + void SpecCase42(int code); + void SpecCase43(int code); + void SpecCase44(int code); + void SpecCase45(int code); + void SpecCase46(int code); + void SpecCase47(int code); + void SpecCase48(int code); + void SpecCase49(int code); + void SpecCase50(int code); + void SpecCase51(int code); + void SpecCase52(int code); + void HybridCase1(int code); + void HybridCase2(int code); + void HybridCase3(int code); + void HybridCase4(int code); + void HybridCase5(int code); + void HybridCase6(int code); + void HybridCase7(int code); + void HybridCase8(int code); + void HybridCase9(int code); + void HybridCase10(int code); + void HybridCase11(int code); + void HybridCase12(int code); + void HybridCase13(int code); + void HybridCase14(int code); + void HybridCase15(int code); + void HybridCase16(int code); + void HybridCase17(int code); + void HybridCase18(int code); + void HybridCase19(int code); + void HybridCase20(int code); + void HybridCase21(int code); + void HybridCase22(int code); + void HybridCase23(int code); + void HybridCase24(int code); + void HybridCase25(int code); + void HybridCase26(int code); + void HybridCase27(int code); + void MultiAppCase1(int code); + void MultiAppCase2(int code); + void MultiAppCase3(int code); + void MultiAppCase4(int code); + void ExtraCase1(int code); + void PriorityCase1(int code); + void PriorityCase2(int code); + void PriorityCase3(int code); + void PriorityCase4(int code); + void PriorityCase5(int code); + void RevokeCase1(int code); + void RevokeCase2(int code); + void RevokeCase3(int code); + void RevokeCase4(int code); + void RevokeCase5(int code); + void RevokeCase6(int code); + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + + void FillInDispathcer(); + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Dispatcher", + [this](int apiIndex, int caseIndex, int code) { TestDispatcher(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestDispatcher(int apiIndex, int caseIndex, int code) + { + mainAbility->TestDispatcher(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..bd7527c37acf482f781837431d87b3f85fd6ed73 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/second_ability.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_KIT_SYSTEM_TEST_A_SECOND_ABILITY_H +#define AMS_KIT_SYSTEM_TEST_A_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "task_dispatcher_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestDispatcher(int apiIndex, int caseIndex, int code); + + void ExtraCase1(int code); + + SecondAbility() + { + mapCase_ = { + {(int)TestFunc::EXTRA, + { + [this](int code) { ExtraCase1(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + int callingTime = 0; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + std::shared_ptr subscriber_; +}; +class SecondEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Dispatcher", + [this](int apiIndex, int caseIndex, int code) { TestDispatcher(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestDispatcher(int apiIndex, int caseIndex, int code) + { + mainAbility->TestDispatcher(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~SecondEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_KIT_SYSTEM_TEST_A_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f0ffaa195385b9f13d7fb5035a070d365485fe00 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_lifecycle.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ce8b83fe29fff7f7a1e7a40181e72f37bbb4ac5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp @@ -0,0 +1,10859 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" +#include +#include +#include +#include +#include +#include + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +namespace { +int terminated_task_num = 0; +std::condition_variable cv; +std::mutex cv_mutex; +constexpr int testTaskCount = 3; +std::string innerSyncBarrierId = "innerSyncBarrierId"; +std::string innerAsyncBarrierId = "innerAsyncBarrierId"; +std::string innerGroupWaitId = "innerGroupWaitId"; +std::string innerGroupNotifyId = "innerGroupNotifyId"; +std::string outerSyncBarrierId = "outerSyncBarrierId"; +std::string outerAsyncBarrierId = "outerAsyncBarrierId"; +std::string outerGroupWaitId = "outerGroupWaitId"; +std::string outerGroupNotifyId = "outerGroupNotifyId"; +constexpr int applyNum = 3; +constexpr int delayMs = 200; +constexpr int groupWait = 1000; +std::string delimiter = "_"; +std::string innerDelimiter = "-"; +std::string task_execution_sequence = delimiter; +std::vector> allDispatchers; +std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} // namespace + +bool Wait(const int task_num) +{ + std::unique_lock ulock(cv_mutex); + using namespace std::chrono_literals; + bool result = cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + if (result) { + allDispatchers.clear(); + } + return result; +} + +void TestTask(const std::string task_id) +{ + { + std::lock_guard lock(cv_mutex); + terminated_task_num++; + task_execution_sequence += task_id + delimiter; + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, terminated_task_num, task_execution_sequence); + cv.notify_one(); +} + +void Reset() +{ + terminated_task_num = 0; + task_execution_sequence = delimiter; + allDispatchers.clear(); +} + +bool IsAscend(const std::vector &vec) +{ + auto pos = std::adjacent_find(std::begin(vec), std::end(vec), std::greater()); + return pos == std::end(vec); +} + +bool OuterTaskExecuted(TestSetting setting) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::OuterTaskExecuted begin"); + std::string expectedTaskId; + bool executed = true; + for (int i = 0; i < testTaskCount; i++) { + expectedTaskId = delimiter + std::to_string(i) + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + if (!executed) { + return executed; + } + } + if (setting.sync_barrier) { + expectedTaskId = delimiter + outerSyncBarrierId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + if (setting.async_barrier) { + expectedTaskId = delimiter + outerAsyncBarrierId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + if (setting.group_notify) { + expectedTaskId = delimiter + outerGroupNotifyId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + APP_LOGI("-- -- -- -- -- --MainAbility::OuterTaskExecuted end result:%{public}d", executed); + return executed; +} + +bool InnerTaskExecuted(TestSetting setting) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::InnerTaskExecuted begin"); + std::string expectedTaskId; + bool executed = true; + for (int i = 0; i < testTaskCount; i++) { + for (int j = 0; j < testTaskCount; j++) { + expectedTaskId = delimiter + std::to_string(i) + innerDelimiter + std::to_string(j) + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + if (!executed) { + return executed; + } + } + } + if (setting.sync_barrier) { + for (int i = 0; i < testTaskCount; i++) { + expectedTaskId = delimiter + innerSyncBarrierId + std::to_string(i) + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + } + if (setting.async_barrier) { + for (int i = 0; i < testTaskCount; i++) { + expectedTaskId = delimiter + innerAsyncBarrierId + std::to_string(i) + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + } + if (setting.group_notify) { + for (int i = 0; i < testTaskCount; i++) { + expectedTaskId = delimiter + innerGroupNotifyId + std::to_string(i) + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + } + APP_LOGI("-- -- -- -- -- --MainAbility::InnerTaskExecuted end result:%{public}d", executed); + return executed; +} + +int countSubstr(std::string str, std::string substr) +{ + std::regex m(substr); + std::sregex_iterator itr(str.begin(), str.end(), m); + std::sregex_iterator end; + return std::distance(itr, end); +} + +int countSubstrOverlap(std::string str, std::string substr) +{ + int count = 0; + std::string::size_type pos = 0; + while ((pos = str.find(substr, pos)) != std::string::npos) { + pos++; + count++; + } + return count; +} + +bool applyExecuted(const TestSetting &outerSetting, const TestSetting &innerSetting) +{ + bool result = true; + bool isOuterApply = outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0; + bool isInnerApply = innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0; + if (!isOuterApply && !isInnerApply) { + return result; + } + if (isOuterApply) { + for (int i = 0; i < testTaskCount; i++) { + std::string taskId = delimiter + std::to_string(i) + delimiter; + result = result && countSubstrOverlap(task_execution_sequence, taskId) == outerSetting.apply; + } + } + int innerTimes = 0; + if (isInnerApply && isOuterApply) { + innerTimes = outerSetting.apply * innerSetting.apply; + } else if (isOuterApply) { + innerTimes = outerSetting.apply; + } else { + innerTimes = innerSetting.apply; + } + + for (int i = 0; i < testTaskCount; i++) { + for (int j = 0; j < testTaskCount; j++) { + std::string taskId = std::to_string(i) + innerDelimiter + std::to_string(j); + result = result && countSubstr(task_execution_sequence, taskId) == innerTimes; + } + } + return result; +} +bool OuterExecutedAfter(const std::string baseTaskId) +{ + bool result = true; + string::size_type waitPos = task_execution_sequence.find(baseTaskId); + for (int i = 0; i < testTaskCount; i++) { + std::string taskId = delimiter + std::to_string(i) + delimiter; + result = result && waitPos > task_execution_sequence.find(taskId); + } + return result; +} + +bool InnerExecutedAfter(const std::string baseTaskId) +{ + bool result = true; + for (int i = 0; i < testTaskCount; i++) { + std::string waitTaskId = delimiter + baseTaskId + std::to_string(i) + delimiter; + string::size_type waitPos = task_execution_sequence.find(waitTaskId); + for (int j = 0; j < testTaskCount; j++) { + std::string taskId = delimiter + std::to_string(i) + innerDelimiter + std::to_string(j) + delimiter; + result = result && waitPos > task_execution_sequence.find(taskId); + } + } + return result; +} + +void setTaskIndex(std::string taskId, std::vector &taskIndex) +{ + std::size_t indx = task_execution_sequence.find(taskId); + if (indx != string::npos) { + taskIndex.push_back(indx); + } +} + +void GetTaskIndex(std::vector &outerTaskIndex, std::vector> &innerTaskIndex, + const int outerCnt = testTaskCount, const int innerCnt = testTaskCount) +{ + std::string outerTaskId; + std::string innerTaskId; + outerTaskIndex.resize(outerCnt); + innerTaskIndex.resize(outerCnt); + for (auto &inner : innerTaskIndex) { + inner.resize(innerCnt); + } + for (int i = 0; i < outerCnt; i++) { + outerTaskId = delimiter + std::to_string(i) + delimiter; + outerTaskIndex[i] = task_execution_sequence.find(outerTaskId); + for (int j = 0; j < innerCnt; j++) { + innerTaskId = delimiter + std::to_string(i) + innerDelimiter + std::to_string(j) + delimiter; + innerTaskIndex[i][j] = task_execution_sequence.find(innerTaskId); + } + std::string taskId = innerSyncBarrierId + std::to_string(i); + setTaskIndex(taskId, innerTaskIndex[i]); + taskId = innerAsyncBarrierId + std::to_string(i); + setTaskIndex(taskId, innerTaskIndex[i]); + taskId = innerGroupNotifyId + std::to_string(i); + setTaskIndex(taskId, innerTaskIndex[i]); + } + setTaskIndex(outerSyncBarrierId, outerTaskIndex); + setTaskIndex(outerAsyncBarrierId, outerTaskIndex); + setTaskIndex(outerGroupNotifyId, outerTaskIndex); + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex end"); +} + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, Ability::GetState(), "onStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, Ability::GetState(), "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, 0, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, Ability::GetState(), "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, Ability::GetState(), "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, Ability::GetState(), "OnForeground"); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIRST, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) +{ + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SetInnerTask(TaskList &innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) +{ + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} + +void SetInnerTaskOther(TaskList &innerDispatcher, TestSetting innerSetting, int outerTaskSeq) +{ + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList &outerDispatcher, TestSetting outerSetting) +{ + if (outerSetting.sync_barrier) { + auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (outerSetting.async_barrier) { + auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (outerSetting.group_wait) { + outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); + } + if (outerSetting.group_notify) { + auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); + outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) +{ + int taskCount = 0; + taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; + if (innerSetting.sync_barrier) { + taskCount++; + } + if (innerSetting.async_barrier) { + taskCount++; + } + if (innerSetting.group_notify) { + taskCount++; + } + taskCount = (outerSetting.op == TestOperation::APPLY) + ? (outerSetting.apply * testTaskCount + outerSetting.apply * testTaskCount * taskCount) + : (testTaskCount + testTaskCount * taskCount); + if (outerSetting.sync_barrier) { + taskCount++; + } + if (outerSetting.async_barrier) { + taskCount++; + } + if (outerSetting.group_notify) { + taskCount++; + } + return taskCount; +} + +int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) +{ + std::string outerName = "outerDispatcher"; + std::string innerName = "innerDispatcher"; + std::string outerTaskId; + auto context = GetContext(); + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; + if (outerSetting.create_group) { + outerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int i = 0; i < testTaskCount; i++) { + outerTaskId = std::to_string(i); + auto outerTask = std::make_shared([=]() { + auto context = this->GetContext(); + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; + if (innerSetting.create_group) { + innerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int j = 0; j < testTaskCount; j++) { + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); + } + SetInnerTaskOther(innerDispatcher, innerSetting, i); + innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } + TestTask(outerTaskId); + }); + outerDispatcher.addOperation(outerSetting.op); + if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { + outerDispatcher.addApply(outerSetting.apply); + } + if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { + outerDispatcher.addDelay(outerSetting.delay); + } + outerDispatcher.addFunc(outerTask); + } + SetOuterTaskOther(outerDispatcher, outerSetting); + outerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); + return taskCount; +} + +// level1:global, sync level2:parallel, sync +void MainAbility::GlobalCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && applyExecuted(outerSetting, innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, async +void MainAbility::GlobalCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, delay +void MainAbility::GlobalCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, group +void MainAbility::GlobalCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, group wait +void MainAbility::GlobalCase5(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, group notify +void MainAbility::GlobalCase6(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, sync barrier +void MainAbility::GlobalCase7(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, async barrier +void MainAbility::GlobalCase8(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:parallel, apply +void MainAbility::GlobalCase9(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:serial, sync +void MainAbility::GlobalCase10(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:serial, async +void MainAbility::GlobalCase11(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:serial, delay +void MainAbility::GlobalCase12(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, sync level2:serial, apply +void MainAbility::GlobalCase13(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, sync +void MainAbility::GlobalCase14(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, async +void MainAbility::GlobalCase15(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, delay +void MainAbility::GlobalCase16(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, group +void MainAbility::GlobalCase17(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, group wait +void MainAbility::GlobalCase18(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, group notify +void MainAbility::GlobalCase19(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, sync barrier +void MainAbility::GlobalCase20(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, async barrier +void MainAbility::GlobalCase21(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:parallel, apply +void MainAbility::GlobalCase22(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:serial, sync +void MainAbility::GlobalCase23(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:serial, async +void MainAbility::GlobalCase24(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:serial, delay +void MainAbility::GlobalCase25(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, async level2:serial, apply +void MainAbility::GlobalCase26(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, sync +void MainAbility::GlobalCase27(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, async +void MainAbility::GlobalCase28(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, delay +void MainAbility::GlobalCase29(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, group +void MainAbility::GlobalCase30(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, group wait +void MainAbility::GlobalCase31(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, group notify +void MainAbility::GlobalCase32(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, sync barrier +void MainAbility::GlobalCase33(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, async barrier +void MainAbility::GlobalCase34(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:parallel, apply +void MainAbility::GlobalCase35(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:serial, sync +void MainAbility::GlobalCase36(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:serial, async +void MainAbility::GlobalCase37(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:serial, delay +void MainAbility::GlobalCase38(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, delay level2:serial, apply +void MainAbility::GlobalCase39(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, sync +void MainAbility::GlobalCase40(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, async +void MainAbility::GlobalCase41(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, delay +void MainAbility::GlobalCase42(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, group +void MainAbility::GlobalCase43(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, group wait +void MainAbility::GlobalCase44(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, group notify +void MainAbility::GlobalCase45(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, sync barrier +void MainAbility::GlobalCase46(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, async barrier +void MainAbility::GlobalCase47(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:parallel, apply +void MainAbility::GlobalCase48(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:serial, sync +void MainAbility::GlobalCase49(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:serial, async +void MainAbility::GlobalCase50(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:serial, delay +void MainAbility::GlobalCase51(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group level2:serial, apply +void MainAbility::GlobalCase52(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, sync +void MainAbility::GlobalCase53(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, async +void MainAbility::GlobalCase54(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, delay +void MainAbility::GlobalCase55(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, group +void MainAbility::GlobalCase56(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, group wait +void MainAbility::GlobalCase57(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, group notify +void MainAbility::GlobalCase58(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, sync barrier +void MainAbility::GlobalCase59(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, async barrier +void MainAbility::GlobalCase60(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:parallel, apply +void MainAbility::GlobalCase61(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:serial, sync +void MainAbility::GlobalCase62(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:serial, async +void MainAbility::GlobalCase63(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:serial, delay +void MainAbility::GlobalCase64(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group wait level2:serial, apply +void MainAbility::GlobalCase65(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, sync +void MainAbility::GlobalCase66(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, async +void MainAbility::GlobalCase67(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, delay +void MainAbility::GlobalCase68(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, group +void MainAbility::GlobalCase69(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, group wait +void MainAbility::GlobalCase70(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, group notify +void MainAbility::GlobalCase71(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, sync barrier +void MainAbility::GlobalCase72(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, async barrier +void MainAbility::GlobalCase73(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:parallel, apply +void MainAbility::GlobalCase74(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:serial, sync +void MainAbility::GlobalCase75(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:serial, async +void MainAbility::GlobalCase76(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:serial, delay +void MainAbility::GlobalCase77(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, group notify level2:serial, apply +void MainAbility::GlobalCase78(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, sync +void MainAbility::GlobalCase79(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, async +void MainAbility::GlobalCase80(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, delay +void MainAbility::GlobalCase81(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, group +void MainAbility::GlobalCase82(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, group wait +void MainAbility::GlobalCase83(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, group notify +void MainAbility::GlobalCase84(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, sync barrier +void MainAbility::GlobalCase85(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, async barrier +void MainAbility::GlobalCase86(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:parallel, apply +void MainAbility::GlobalCase87(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:serial, sync +void MainAbility::GlobalCase88(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:serial, async +void MainAbility::GlobalCase89(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:serial, delay +void MainAbility::GlobalCase90(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:global, apply level2:serial, apply +void MainAbility::GlobalCase91(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::GLOBAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, sync +void MainAbility::ParallelCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, async +void MainAbility::ParallelCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, delay +void MainAbility::ParallelCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, group +void MainAbility::ParallelCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, group wait +void MainAbility::ParallelCase5(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, group notify +void MainAbility::ParallelCase6(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, sync barrier +void MainAbility::ParallelCase7(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, async barrier +void MainAbility::ParallelCase8(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:parallel, apply +void MainAbility::ParallelCase9(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:serial, sync +void MainAbility::ParallelCase10(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:serial, async +void MainAbility::ParallelCase11(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:serial, delay +void MainAbility::ParallelCase12(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync level2:serial, apply +void MainAbility::ParallelCase13(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, sync +void MainAbility::ParallelCase14(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, async +void MainAbility::ParallelCase15(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, delay +void MainAbility::ParallelCase16(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, group +void MainAbility::ParallelCase17(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, group wait +void MainAbility::ParallelCase18(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, group notify +void MainAbility::ParallelCase19(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, sync barrier +void MainAbility::ParallelCase20(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, async barrier +void MainAbility::ParallelCase21(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:parallel, apply +void MainAbility::ParallelCase22(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:serial, sync +void MainAbility::ParallelCase23(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:serial, async +void MainAbility::ParallelCase24(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:serial, delay +void MainAbility::ParallelCase25(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async level2:serial, apply +void MainAbility::ParallelCase26(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, sync +void MainAbility::ParallelCase27(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, async +void MainAbility::ParallelCase28(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, delay +void MainAbility::ParallelCase29(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, group +void MainAbility::ParallelCase30(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, group wait +void MainAbility::ParallelCase31(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, group notify +void MainAbility::ParallelCase32(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, sync barrier +void MainAbility::ParallelCase33(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, async barrier +void MainAbility::ParallelCase34(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:parallel, apply +void MainAbility::ParallelCase35(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:serial, sync +void MainAbility::ParallelCase36(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:serial, async +void MainAbility::ParallelCase37(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:serial, delay +void MainAbility::ParallelCase38(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, delay level2:serial, apply +void MainAbility::ParallelCase39(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, sync +void MainAbility::ParallelCase40(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, async +void MainAbility::ParallelCase41(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, delay +void MainAbility::ParallelCase42(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, group +void MainAbility::ParallelCase43(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, group wait +void MainAbility::ParallelCase44(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, group notify +void MainAbility::ParallelCase45(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, sync barrier +void MainAbility::ParallelCase46(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, async barrier +void MainAbility::ParallelCase47(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:parallel, apply +void MainAbility::ParallelCase48(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:serial, sync +void MainAbility::ParallelCase49(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:serial, async +void MainAbility::ParallelCase50(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:serial, delay +void MainAbility::ParallelCase51(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group level2:serial, apply +void MainAbility::ParallelCase52(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, sync +void MainAbility::ParallelCase53(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, async +void MainAbility::ParallelCase54(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, delay +void MainAbility::ParallelCase55(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, group +void MainAbility::ParallelCase56(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, group wait +void MainAbility::ParallelCase57(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, group notify +void MainAbility::ParallelCase58(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, sync barrier +void MainAbility::ParallelCase59(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, async barrier +void MainAbility::ParallelCase60(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:parallel, apply +void MainAbility::ParallelCase61(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:serial, sync +void MainAbility::ParallelCase62(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:serial, async +void MainAbility::ParallelCase63(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:serial, delay +void MainAbility::ParallelCase64(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group wait level2:serial, apply +void MainAbility::ParallelCase65(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.group_wait = true; + outerSetting.group_timeout = groupWait; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, sync +void MainAbility::ParallelCase66(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, async +void MainAbility::ParallelCase67(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, delay +void MainAbility::ParallelCase68(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, group +void MainAbility::ParallelCase69(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, group wait +void MainAbility::ParallelCase70(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, group notify +void MainAbility::ParallelCase71(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, sync barrier +void MainAbility::ParallelCase72(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, async barrier +void MainAbility::ParallelCase73(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:parallel, apply +void MainAbility::ParallelCase74(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:serial, sync +void MainAbility::ParallelCase75(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:serial, async +void MainAbility::ParallelCase76(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:serial, delay +void MainAbility::ParallelCase77(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, group notify level2:serial, apply +void MainAbility::ParallelCase78(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.create_group = true; + outerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, sync +void MainAbility::ParallelCase79(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, async +void MainAbility::ParallelCase80(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, delay +void MainAbility::ParallelCase81(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, group +void MainAbility::ParallelCase82(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, group wait +void MainAbility::ParallelCase83(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, group notify +void MainAbility::ParallelCase84(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, sync barrier +void MainAbility::ParallelCase85(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, async barrier +void MainAbility::ParallelCase86(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:parallel, apply +void MainAbility::ParallelCase87(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:serial, sync +void MainAbility::ParallelCase88(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:serial, async +void MainAbility::ParallelCase89(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:serial, delay +void MainAbility::ParallelCase90(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, sync barrier level2:serial, apply +void MainAbility::ParallelCase91(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.sync_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, sync +void MainAbility::ParallelCase92(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, async +void MainAbility::ParallelCase93(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, delay +void MainAbility::ParallelCase94(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, group +void MainAbility::ParallelCase95(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, group wait +void MainAbility::ParallelCase96(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, group notify +void MainAbility::ParallelCase97(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, sync barrier +void MainAbility::ParallelCase98(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, async barrier +void MainAbility::ParallelCase99(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:parallel, apply +void MainAbility::ParallelCase100(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:serial, sync +void MainAbility::ParallelCase101(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:serial, async +void MainAbility::ParallelCase102(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:serial, delay +void MainAbility::ParallelCase103(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, async barrier level2:serial, apply +void MainAbility::ParallelCase104(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.async_barrier = true; + outerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC_GROUP; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && OuterExecutedAfter(outerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, sync +void MainAbility::ParallelCase105(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, async +void MainAbility::ParallelCase106(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, delay +void MainAbility::ParallelCase107(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, group +void MainAbility::ParallelCase108(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, group wait +void MainAbility::ParallelCase109(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, group notify +void MainAbility::ParallelCase110(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, sync barrier +void MainAbility::ParallelCase111(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, async barrier +void MainAbility::ParallelCase112(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:parallel, apply +void MainAbility::ParallelCase113(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:serial, sync +void MainAbility::ParallelCase114(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:serial, async +void MainAbility::ParallelCase115(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:serial, delay +void MainAbility::ParallelCase116(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:parallel, apply level2:serial, apply +void MainAbility::ParallelCase117(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, sync +void MainAbility::SerialCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, async +void MainAbility::SerialCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, delay +void MainAbility::SerialCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, group +void MainAbility::SerialCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, group wait +void MainAbility::SerialCase5(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, group notify +void MainAbility::SerialCase6(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, sync barrier +void MainAbility::SerialCase7(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, async barrier +void MainAbility::SerialCase8(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:parallel, apply +void MainAbility::SerialCase9(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:serial, sync +void MainAbility::SerialCase10(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:serial, async +void MainAbility::SerialCase11(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:serial, delay +void MainAbility::SerialCase12(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, sync level2:serial, apply +void MainAbility::SerialCase13(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, sync +void MainAbility::SerialCase14(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, async +void MainAbility::SerialCase15(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, delay +void MainAbility::SerialCase16(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, group +void MainAbility::SerialCase17(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, group wait +void MainAbility::SerialCase18(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, group notify +void MainAbility::SerialCase19(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, sync barrier +void MainAbility::SerialCase20(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, async barrier +void MainAbility::SerialCase21(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:parallel, apply +void MainAbility::SerialCase22(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:serial, sync +void MainAbility::SerialCase23(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:serial, async +void MainAbility::SerialCase24(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:serial, delay +void MainAbility::SerialCase25(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, async level2:serial, apply +void MainAbility::SerialCase26(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, sync +void MainAbility::SerialCase27(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, async +void MainAbility::SerialCase28(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, delay +void MainAbility::SerialCase29(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, group +void MainAbility::SerialCase30(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, group wait +void MainAbility::SerialCase31(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, group notify +void MainAbility::SerialCase32(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, sync barrier +void MainAbility::SerialCase33(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, async barrier +void MainAbility::SerialCase34(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:parallel, apply +void MainAbility::SerialCase35(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:serial, sync +void MainAbility::SerialCase36(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:serial, async +void MainAbility::SerialCase37(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:serial, delay +void MainAbility::SerialCase38(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, delay level2:serial, apply +void MainAbility::SerialCase39(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, sync +void MainAbility::SerialCase40(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, async +void MainAbility::SerialCase41(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, delay +void MainAbility::SerialCase42(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, group +void MainAbility::SerialCase43(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, group wait +void MainAbility::SerialCase44(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, group notify +void MainAbility::SerialCase45(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, sync barrier +void MainAbility::SerialCase46(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, async barrier +void MainAbility::SerialCase47(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:parallel, apply +void MainAbility::SerialCase48(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:serial, sync +void MainAbility::SerialCase49(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:serial, async +void MainAbility::SerialCase50(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:serial, delay +void MainAbility::SerialCase51(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:serial, apply level2:serial, apply +void MainAbility::SerialCase52(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, sync +void MainAbility::SpecCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, async +void MainAbility::SpecCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, delay +void MainAbility::SpecCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, group +void MainAbility::SpecCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, group wait +void MainAbility::SpecCase5(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, group notify +void MainAbility::SpecCase6(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, sync barrier +void MainAbility::SpecCase7(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, async barrier +void MainAbility::SpecCase8(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:parallel, apply +void MainAbility::SpecCase9(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:serial, sync +void MainAbility::SpecCase10(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:serial, async +void MainAbility::SpecCase11(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:serial, delay +void MainAbility::SpecCase12(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, sync level2:serial, apply +void MainAbility::SpecCase13(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::SYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + result = result && IsAscend(outerTaskIndex); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, sync +void MainAbility::SpecCase14(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, async +void MainAbility::SpecCase15(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, delay +void MainAbility::SpecCase16(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, group +void MainAbility::SpecCase17(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, group wait +void MainAbility::SpecCase18(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, group notify +void MainAbility::SpecCase19(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, sync barrier +void MainAbility::SpecCase20(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, async barrier +void MainAbility::SpecCase21(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:parallel, apply +void MainAbility::SpecCase22(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:serial, sync +void MainAbility::SpecCase23(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:serial, async +void MainAbility::SpecCase24(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:serial, delay +void MainAbility::SpecCase25(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, async level2:serial, apply +void MainAbility::SpecCase26(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::ASYNC; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, sync +void MainAbility::SpecCase27(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, async +void MainAbility::SpecCase28(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, delay +void MainAbility::SpecCase29(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, group +void MainAbility::SpecCase30(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, group wait +void MainAbility::SpecCase31(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, group notify +void MainAbility::SpecCase32(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, sync barrier +void MainAbility::SpecCase33(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, async barrier +void MainAbility::SpecCase34(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:parallel, apply +void MainAbility::SpecCase35(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:serial, sync +void MainAbility::SpecCase36(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:serial, async +void MainAbility::SpecCase37(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:serial, delay +void MainAbility::SpecCase38(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, delay level2:serial, apply +void MainAbility::SpecCase39(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.delay = delayMs; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::DELAY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, sync +void MainAbility::SpecCase40(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, async +void MainAbility::SpecCase41(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, delay +void MainAbility::SpecCase42(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, group +void MainAbility::SpecCase43(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, group wait +void MainAbility::SpecCase44(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + innerSetting.group_wait = true; + innerSetting.group_timeout = groupWait; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, group notify +void MainAbility::SpecCase45(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.create_group = true; + innerSetting.group_notify = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerGroupNotifyId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, sync barrier +void MainAbility::SpecCase46(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.sync_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerSyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, async barrier +void MainAbility::SpecCase47(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.async_barrier = true; + innerSetting.create_group = true; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC_GROUP; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + result = result && InnerExecutedAfter(innerAsyncBarrierId); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:parallel, apply +void MainAbility::SpecCase48(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::PARALLEL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:serial, sync +void MainAbility::SpecCase49(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::SYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:serial, async +void MainAbility::SpecCase50(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::ASYNC; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:serial, delay +void MainAbility::SpecCase51(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.delay = delayMs; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::DELAY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex); + for (int i = 0; i < testTaskCount; i++) { + result = result && IsAscend(innerTaskIndex[i]); + } + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +// level1:spec, apply level2:serial, apply +void MainAbility::SpecCase52(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + TestSetting outerSetting; + TestSetting innerSetting; + outerSetting.dispatcher = TestDispatcher::MAIN; + innerSetting.dispatcher = TestDispatcher::SERIAL; + outerSetting.apply = applyNum; + innerSetting.apply = applyNum; + outerSetting.op = TestOperation::APPLY; + innerSetting.op = TestOperation::APPLY; + int taskCount = Dispatch(outerSetting, innerSetting); + bool result = Wait(taskCount); + result = result && task_execution_sequence.size() > 1; + if (result) { + result = result && applyExecuted(outerSetting, innerSetting); + result = result && OuterTaskExecuted(outerSetting); + result = result && InnerTaskExecuted(innerSetting); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +static void addTaskFromList(TaskList &dispatcher, const std::vector &operationList, int &taskId, + const int apply = 0, const long delay = 0) +{ + for (auto op : operationList) { + if (op == TestOperation::CREATE_GROUP) { + dispatcher.addOperation(op); + continue; + } + if (op == TestOperation::APPLY) { + dispatcher.addApply(apply); + } + if (op == TestOperation::DELAY) { + dispatcher.addDelay(delay); + } + dispatcher.addOperation(op).addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })); + taskId++; + } +} +void MainAbility::HybridCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + std::vector operationList = { + TestOperation::SYNC, + TestOperation::ASYNC, + TestOperation::DELAY, + TestOperation::CREATE_GROUP, + TestOperation::ASYNC_GROUP, + TestOperation::GROUP_NOTIFY, + TestOperation::APPLY, + }; + int taskId = 0; + const int apply = 2; + const int delay = 10; + addTaskFromList(globalDispatcher, operationList, taskId, apply, delay); + globalDispatcher.executedTask(); + Wait(taskId + apply - 1); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; + std::vector operationList = { + TestOperation::SYNC, + TestOperation::ASYNC, + TestOperation::DELAY, + TestOperation::CREATE_GROUP, + TestOperation::ASYNC_GROUP, + TestOperation::SYNC_BARRIER, + TestOperation::CREATE_GROUP, + TestOperation::ASYNC_GROUP, + TestOperation::GROUP_NOTIFY, + TestOperation::ASYNC_BARRIER, + TestOperation::APPLY, + }; + int taskId = 0; + const int apply = 2; + const int delay = 10; + addTaskFromList(parallelDispatcher, operationList, taskId, apply, delay); + parallelDispatcher.executedTask(); + Wait(taskId + apply - 1); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; + std::vector operationList = { + TestOperation::SYNC, + TestOperation::ASYNC, + TestOperation::DELAY, + TestOperation::APPLY, + }; + int taskId = 0; + const int apply = 2; + const int delay = 10; + addTaskFromList(serialDispatcher, operationList, taskId, apply, delay); + serialDispatcher.executedTask(); + Wait(taskId + apply - 1); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + std::vector operationList = { + TestOperation::SYNC, + TestOperation::ASYNC, + TestOperation::DELAY, + TestOperation::APPLY, + }; + int taskId = 0; + const int apply = 2; + const int delay = 10; + addTaskFromList(mainDispatcher, operationList, taskId, apply, delay); + mainDispatcher.executedTask(); + Wait(taskId + apply - 1); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase5(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + globalDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher2.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher2.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + mainDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase6(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + globalDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + mainDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase7(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + const long delay = 10; + globalDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + parallelDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + parallelDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + serialDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + serialDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + mainDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase8(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher2.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + mainDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase9(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + mainDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase10(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + const long delay = 10; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + serialDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + mainDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase11(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId += numTwo; + parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId += numTwo; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId += numTwo; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + mainDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase12(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + globalDispatcher.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + parallelDispatcher1.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + parallelDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher1.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + mainDispatcher.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase13(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 1; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount += apply; + parallelDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount += apply; + parallelDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount += apply; + mainDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount += apply; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase14(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher1.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase15(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId++; + taskCount += numTwo; + parallelDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + mainDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase16(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + parallelDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId++; + taskCount += numTwo; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase17(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + globalDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase18(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher1.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase19(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase20(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId++; + taskCount += numTwo; + serialDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase21(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId++; + taskCount += numTwo; + parallelDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase22(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + parallelDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase23(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId++; + taskCount += numTwo; + serialDispatcher1.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher2.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase24(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const long apply = 2; + const long delay = 10; + globalDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId += numTwo; + taskCount += numTwo; + parallelDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::APPLY) + .addApply(apply) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher1.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::APPLY) + .addApply(apply) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::DELAY) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount += apply; + mainDispatcher.addOperation(TestOperation::APPLY) + .addApply(apply) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::DELAY) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount += apply; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase25(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + globalDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId++; + taskCount += numTwo; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase26(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + globalDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount = taskCount + apply; + serialDispatcher1.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + mainDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; +void MainAbility::HybridCase27(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + int taskId = 0; + int taskCount = 0; + const int apply = 2; + const int delay = 10; + globalDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + taskCount++; + parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::GROUP_NOTIFY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) + .executedTask(); + taskId++; + taskCount += numTwo; + parallelDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + serialDispatcher1.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + serialDispatcher2.addOperation(TestOperation::APPLY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addApply(apply) + .executedTask(); + taskId++; + taskCount += apply; + mainDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delay) + .executedTask(); + taskId++; + taskCount++; + Wait(taskCount); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +}; + +void MainAbility::MultiAppCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(globalDispatcher, operationList, taskId); + globalDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::MultiAppCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(parallelDispatcher, operationList, taskId); + parallelDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::MultiAppCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(serialDispatcher, operationList, taskId); + serialDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::MultiAppCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(mainDispatcher, operationList, taskId); + mainDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::ExtraCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + int taskId = 0; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + bool result = globalDispatcher.addOperation(TestOperation::SYNC) + .addFunc(std::make_shared([=]() { + std::string targetBundleName = "com.ohos.TaskDispatcherA"; + std::string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundleName, targetAbility); + StartAbility(want); + TestTask(std::to_string(taskId)); + })) + .executedTask(); + taskId++; + Wait(taskId); + result = task_execution_sequence.size() > 1; + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} + +void MainAbility::FillInDispathcer() +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + const int fullThreadNum = 32; + const int waitTime = 2; + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; + parallelDispatcher.setTaskPriority(AppExecFwk::TaskPriority::HIGH); + parallelDispatcher.addOperation(TestOperation::ASYNC).addFunc(std::make_shared([=]() { + sleep(waitTime - 1); + })); + for (int i = 1; i < fullThreadNum; i++) { + parallelDispatcher.addOperation(TestOperation::ASYNC).addFunc(std::make_shared([=]() { + sleep(waitTime); + })); + } + parallelDispatcher.executedTask(); +} +void MainAbility::PriorityCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + FillInDispathcer(); + Reset(); + auto context = GetContext(); + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globalLow"}; + TaskList globalDispatcherDefault = TaskList {TestDispatcher::GLOBAL, context, "globalDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; + int taskId = 0; + globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + globalDispatcherDefault.setTaskPriority(AppExecFwk::TaskPriority::DEFAULT) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + globalDispatcherHigh.setTaskPriority(AppExecFwk::TaskPriority::HIGH) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && + (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +void MainAbility::PriorityCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + FillInDispathcer(); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList parallelDispatcherHigh = TaskList {TestDispatcher::PARALLEL, context, "parallelHigh"}; + int taskId = 0; + parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcherDefault.setTaskPriority(AppExecFwk::TaskPriority::DEFAULT) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcherHigh.setTaskPriority(AppExecFwk::TaskPriority::HIGH) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && + (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +void MainAbility::PriorityCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + FillInDispathcer(); + Reset(); + auto context = GetContext(); + TaskList serialDispatcherLow = TaskList {TestDispatcher::SERIAL, context, "serialLow"}; + TaskList serialDispatcherDefault = TaskList {TestDispatcher::SERIAL, context, "serialDefault"}; + TaskList serialDispatcherHigh = TaskList {TestDispatcher::SERIAL, context, "serialHigh"}; + int taskId = 0; + serialDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcherDefault.setTaskPriority(AppExecFwk::TaskPriority::DEFAULT) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + serialDispatcherHigh.setTaskPriority(AppExecFwk::TaskPriority::HIGH) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && + (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +void MainAbility::PriorityCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + FillInDispathcer(); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList mainDispatcherHigh = TaskList {TestDispatcher::MAIN, context, "mainHigh"}; + int taskId = 0; + parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcherDefault.setTaskPriority(AppExecFwk::TaskPriority::DEFAULT) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + mainDispatcherHigh.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && + (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +void MainAbility::PriorityCase5(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + FillInDispathcer(); + Reset(); + auto context = GetContext(); + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globallLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; + int taskId = 0; + globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + parallelDispatcherDefault.setTaskPriority(AppExecFwk::TaskPriority::DEFAULT) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + globalDispatcherHigh.setTaskPriority(AppExecFwk::TaskPriority::HIGH) + .addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && + (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +void MainAbility::RevokeCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + FillInDispathcer(); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; + int taskId = 0; + bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); + taskId++; + result = !result || Wait(taskId); + result = result || task_execution_sequence.size() > 1; + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(!result)); +} +void MainAbility::RevokeCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; + int taskId = 0; + bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + result = result && Wait(taskId); + result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); + result = result && task_execution_sequence.size() > 1; + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +void MainAbility::RevokeCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; + int taskId = 0; + bool result = parallelDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); + taskId++; + result = !result || Wait(taskId); + result = result || task_execution_sequence.size() > 1; + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(!result)); +} +void MainAbility::RevokeCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; + int taskId = 0; + bool result = parallelDispatcher.addOperation(TestOperation::DELAY) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .executedTask(); + taskId++; + result = result && Wait(taskId); + result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); + result = result && task_execution_sequence.size() > 1; + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +void MainAbility::RevokeCase5(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + FillInDispathcer(); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; + int taskId = 0; + bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); + taskId++; + result = !result || Wait(taskId); + result = result || task_execution_sequence.size() > 1; + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(!result)); +} +void MainAbility::RevokeCase6(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; + int taskId = 0; + bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); + taskId++; + result = result && Wait(taskId); + result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); + result = result && task_execution_sequence.size() > 1; + + TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); +} +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81343ce39939753186429347138ac660960d61ed --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} // namespace + + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "onStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnStop"); +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnActive"); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, Ability::GetState(), "OnForeground"); +} +void SecondAbility::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("SecondAbility::OnCommand"); + + Ability::OnCommand(want, restart, startId); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestDispatcher(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::ExtraCase1(int code) +{} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..773b9781b8c7a37eac7e67361e93c109ba2e478d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("taskDispatcherTestBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/include", + ] + defines = [ + "APP_LOG_TAG = \"taskDispatcherTestB\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("taskDispatcherTestB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/src/task_dispatcher_tools.cpp", + ] + configs = [ + ":taskDispatcherTestBConfig", + "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher:system_test_task_dispatcher_config", + ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/config.json b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..551bf938a9f40f2411493af153640d9558c71da5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/config.json @@ -0,0 +1,53 @@ +{ + "app":{ + "bundleName": "com.ohos.TaskDispatcherB", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.TaskDispatcherB.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Main Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowflakes", + "srcLanguage": "c++", + "label": "Second Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..a132d231376f5d71b7f657f16f7f3955534dbf25 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/main_ability.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_KIT_SYSTEM_TEST_B_MAIN_ABILITY_H +#define AMS_KIT_SYSTEM_TEST_B_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "task_dispatcher_tools.h" +#include "task_dispatcher_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + MainAbility() + { + initGlobal(); + initParallel(); + initSerial(); + initSpec(); + initHybrid(); + initMultiApp(); + initPriority(); + initCancelTask(); + initExtra(); + } + void initGlobal() + { + mapCase_[(int)TestFunc::GLOBAL] = {}; + } + void initParallel() + { + mapCase_[(int)TestFunc::PARALLEL] = {}; + } + void initSerial() + { + mapCase_[(int)TestFunc::SERIAL] = {}; + } + void initSpec() + { + mapCase_[(int)TestFunc::SPEC] = {}; + } + void initHybrid() + { + mapCase_[(int)TestFunc::HYBRID] = {}; + } + void initMultiApp() + { + mapCase_[(int)TestFunc::MULTI_APP] = { + [this](int code) { MultiAppCase1(code); }, + [this](int code) { MultiAppCase2(code); }, + [this](int code) { MultiAppCase3(code); }, + [this](int code) { MultiAppCase4(code); }, + }; + } + void initPriority() + { + mapCase_[(int)TestFunc::PRIORITY] = {}; + } + void initCancelTask() + { + mapCase_[(int)TestFunc::CANCEL_TASK] = {}; + } + void initExtra() + { + mapCase_[(int)TestFunc::EXTRA] = {}; + } + + void SubscribeEvent(); + void TestDispatcher(int apiIndex, int caseIndex, int code); + int Dispatch(STtools::TestSetting outer, STtools::TestSetting inner); + + void MultiAppCase1(int code); + void MultiAppCase2(int code); + void MultiAppCase3(int code); + void MultiAppCase4(int code); + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Dispatcher", + [this](int apiIndex, int caseIndex, int code) { TestDispatcher(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestDispatcher(int apiIndex, int caseIndex, int code) + { + mainAbility->TestDispatcher(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_KIT_SYSTEM_TEST_B_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..2a3c79f8078fce89a0a4d231967d8a3e1b5b02fd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/second_ability.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_KIT_SYSTEM_TEST_B_SECOND_ABILITY_H +#define AMS_KIT_SYSTEM_TEST_B_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "task_dispatcher_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestDispatcher(int apiIndex, int caseIndex, int code); + + void ExtraCase1(int code); + + SecondAbility() + { + mapCase_ = { + {(int)TestFunc::EXTRA, {}}, + }; + } + + std::unordered_map>> mapCase_; + int callingTime = 0; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + std::shared_ptr subscriber_; +}; +class SecondEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"Dispatcher", + [this](int apiIndex, int caseIndex, int code) { TestDispatcher(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestDispatcher(int apiIndex, int caseIndex, int code) + { + mainAbility->TestDispatcher(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~SecondEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_KIT_SYSTEM_TEST_B_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f0ffaa195385b9f13d7fb5035a070d365485fe00 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_lifecycle.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fddb141750e2083b2539793e245985556320dc09 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp @@ -0,0 +1,582 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" +#include +#include +#include +#include + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +namespace { +int terminated_task_num = 0; +std::condition_variable cv; +std::mutex cv_mutex; +constexpr int testTaskCount = 3; +std::string innerSyncBarrierId = "innerSyncBarrierId"; +std::string innerAsyncBarrierId = "innerAsyncBarrierId"; +std::string innerGroupWaitId = "innerGroupWaitId"; +std::string innerGroupNotifyId = "innerGroupNotifyId"; +std::string outerSyncBarrierId = "outerSyncBarrierId"; +std::string outerAsyncBarrierId = "outerAsyncBarrierId"; +std::string outerGroupWaitId = "outerGroupWaitId"; +std::string outerGroupNotifyId = "outerGroupNotifyId"; +std::string delimiter = "_"; +std::string innerDelimiter = "-"; +std::string task_execution_sequence = delimiter; +std::vector> allDispatchers; +std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} // namespace + +bool Wait(const int task_num) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::Wait"); + std::unique_lock ulock(cv_mutex); + using namespace std::chrono_literals; + bool result = cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + if (result) { + allDispatchers.clear(); + } + APP_LOGI("-- -- -- -- -- --MainAbility::Wait result:%{public}d", result); + return result; +} + +void TestTask(const std::string &task_id) +{ + { + std::lock_guard lock(cv_mutex); + terminated_task_num++; + task_execution_sequence += task_id + delimiter; + } + APP_LOGI("-- -- -- -- -- --MainAbility::TestTask: %{public}d %{public}s", terminated_task_num, task_id.c_str()); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, terminated_task_num, task_execution_sequence); + cv.notify_one(); +} + +void Reset() +{ + APP_LOGI("-- -- -- -- -- --MainAbility::Reset"); + terminated_task_num = 0; + task_execution_sequence = delimiter; + allDispatchers.clear(); +} + +bool IsAscend(const std::vector &vec) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::IsAscend begin"); + auto pos = std::adjacent_find(std::begin(vec), std::end(vec), std::greater()); + return pos == std::end(vec); + APP_LOGI("-- -- -- -- -- --MainAbility::IsAscend end"); +} + +bool OuterTaskExecuted(TestSetting setting) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::OuterTaskExecuted begin"); + std::string expectedTaskId; + bool executed = true; + for (int i = 0; i < testTaskCount; i++) { + expectedTaskId = delimiter + std::to_string(i) + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + if (!executed) { + return executed; + } + } + if (setting.sync_barrier) { + expectedTaskId = delimiter + outerSyncBarrierId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + if (setting.async_barrier) { + expectedTaskId = delimiter + outerAsyncBarrierId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + if (setting.group_notify) { + expectedTaskId = delimiter + outerGroupNotifyId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + APP_LOGI("-- -- -- -- -- --MainAbility::OuterTaskExecuted end"); + return executed; +} + +bool InnerTaskExecuted(TestSetting setting) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::InnerTaskExecuted begin"); + std::string expectedTaskId; + bool executed = true; + for (int i = 0; i < testTaskCount; i++) { + for (int j = 0; j < testTaskCount; j++) { + expectedTaskId = delimiter + std::to_string(i) + innerDelimiter + std::to_string(j) + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + if (!executed) { + return executed; + } + } + } + if (setting.sync_barrier) { + expectedTaskId = delimiter + innerSyncBarrierId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + if (setting.async_barrier) { + expectedTaskId = delimiter + innerAsyncBarrierId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + if (setting.group_notify) { + expectedTaskId = delimiter + innerGroupNotifyId + delimiter; + executed = executed && (task_execution_sequence.find(expectedTaskId) != string::npos); + } + APP_LOGI("-- -- -- -- -- --MainAbility::InnerTaskExecuted end"); + return executed; +} + +void setTaskIndex(std::string taskId, std::vector &taskIndex) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::setTaskIndex begin"); + std::size_t indx = task_execution_sequence.find(taskId); + if (indx != string::npos) { + taskIndex.push_back(indx); + } + APP_LOGI("-- -- -- -- -- --MainAbility::setTaskIndex end"); +} + +void GetTaskIndex(std::vector &outerTaskIndex, std::vector> &innerTaskIndex, + const int outerCnt = testTaskCount, const int innerCnt = testTaskCount) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex begin"); + std::string outerTaskId; + std::string innerTaskId; + outerTaskIndex.resize(outerCnt); + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex outersize : %{public}zu", outerTaskIndex.size()); + innerTaskIndex.resize(outerCnt); + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex innersize : %{public}zu", innerTaskIndex.size()); + for (auto &inner : innerTaskIndex) { + inner.resize(innerCnt); + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex inner :%{public}zu", inner.size()); + } + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex mid1"); + for (int i = 0; i < outerCnt; i++) { + outerTaskId = delimiter + std::to_string(i) + delimiter; + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex mid2"); + outerTaskIndex[i] = task_execution_sequence.find(outerTaskId); + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex mid3"); + for (int j = 0; j < innerCnt; j++) { + innerTaskId = delimiter + std::to_string(i) + innerDelimiter + std::to_string(j) + delimiter; + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex mid4"); + innerTaskIndex[i][j] = task_execution_sequence.find(innerTaskId); + APP_LOGI("-- -- -- -- -- --MainAbility::GetTaskIndex mid5"); + } + std::string taskId = innerSyncBarrierId + std::to_string(i); + setTaskIndex(taskId, innerTaskIndex[i]); + taskId = innerAsyncBarrierId + std::to_string(i); + setTaskIndex(taskId, innerTaskIndex[i]); + taskId = innerGroupNotifyId + std::to_string(i); + setTaskIndex(taskId, innerTaskIndex[i]); + } + setTaskIndex(outerSyncBarrierId, outerTaskIndex); + setTaskIndex(outerAsyncBarrierId, outerTaskIndex); + setTaskIndex(outerGroupNotifyId, outerTaskIndex); + APP_LOGI("-- -- -- -- -- --MainAbility:: end"); +} + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, Ability::GetState(), "onStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, Ability::GetState(), "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, 0, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, Ability::GetState(), "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, Ability::GetState(), "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, Ability::GetState(), "OnForeground"); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_FIRST_B, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST_B.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) +{ + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SetInnerTask(TaskList &innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) +{ + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} + +void SetInnerTaskOther(TaskList &innerDispatcher, TestSetting innerSetting, int outerTaskSeq) +{ + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList &outerDispatcher, TestSetting outerSetting) +{ + if (outerSetting.sync_barrier) { + auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (outerSetting.async_barrier) { + auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (outerSetting.group_wait) { + outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); + } + if (outerSetting.group_notify) { + auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); + outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) +{ + int taskCount = 0; + taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; + if (innerSetting.sync_barrier) { + taskCount++; + } + if (innerSetting.async_barrier) { + taskCount++; + } + if (innerSetting.group_notify) { + taskCount++; + } + taskCount = (outerSetting.op == TestOperation::APPLY) + ? (outerSetting.apply * testTaskCount + outerSetting.apply * testTaskCount * taskCount) + : (testTaskCount + testTaskCount * taskCount); + if (outerSetting.sync_barrier) { + taskCount++; + } + if (outerSetting.async_barrier) { + taskCount++; + } + if (outerSetting.group_notify) { + taskCount++; + } + return taskCount; +} + +int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) +{ + std::string outerName = "outerDispatcher"; + std::string innerName = "innerDispatcher"; + std::string outerTaskId; + auto context = GetContext(); + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; + if (outerSetting.create_group) { + outerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int i = 0; i < testTaskCount; i++) { + outerTaskId = std::to_string(i); + auto outerTask = std::make_shared([=]() { + auto context = this->GetContext(); + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; + if (innerSetting.create_group) { + innerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int j = 0; j < testTaskCount; j++) { + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); + } + SetInnerTaskOther(innerDispatcher, innerSetting, i); + innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } + TestTask(outerTaskId); + }); + outerDispatcher.addOperation(outerSetting.op); + if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { + outerDispatcher.addApply(outerSetting.apply); + } + if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { + outerDispatcher.addDelay(outerSetting.delay); + } + outerDispatcher.addFunc(outerTask); + } + SetOuterTaskOther(outerDispatcher, outerSetting); + outerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); + return taskCount; +} + +static void addTaskFromList(TaskList &dispatcher, const std::vector &operationList, int &taskId, + const int apply = 0, const long delay = 0) +{ + for (auto op : operationList) { + if (op == TestOperation::CREATE_GROUP) { + dispatcher.addOperation(op); + continue; + } + if (op == TestOperation::APPLY) { + dispatcher.addApply(apply); + } + if (op == TestOperation::DELAY) { + dispatcher.addDelay(delay); + } + dispatcher.addOperation(op).addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })); + taskId++; + } +} + +void MainAbility::MultiAppCase1(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(globalDispatcher, operationList, taskId); + globalDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, code, std::to_string(result)); +} + +void MainAbility::MultiAppCase2(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(globalDispatcher, operationList, taskId); + globalDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, code, std::to_string(result)); +} + +void MainAbility::MultiAppCase3(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(globalDispatcher, operationList, taskId); + globalDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, code, std::to_string(result)); +} + +void MainAbility::MultiAppCase4(int code) +{ + APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); + Reset(); + auto context = GetContext(); + TaskList globalDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; + std::vector operationList = { + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + TestOperation::ASYNC, + }; + int taskId = 0; + addTaskFromList(globalDispatcher, operationList, taskId); + globalDispatcher.executedTask(); + Wait(taskId); + bool result = task_execution_sequence.size() > 1; + std::vector outerTaskIndex; + std::vector> innerTaskIndex; + GetTaskIndex(outerTaskIndex, innerTaskIndex, taskId, 0); + for (auto index : outerTaskIndex) { + result = result && (index != std::string::npos); + } + TestUtils::PublishEvent(g_EVENT_RESP_FIRST_B, code, std::to_string(result)); +} +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c770b1249159f651d0c48fcc98ac92003660c94 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::onStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_B, Ability::GetState(), "onStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_B, Ability::GetState(), "OnStop"); +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_B, Ability::GetState(), "OnActive"); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_B, Ability::GetState(), "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_B, Ability::GetState(), "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_B, Ability::GetState(), "OnForeground"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND_B, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND_B.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < numThree) { + return; + } + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestDispatcher(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::ExtraCase1(int code) +{} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/event.h b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h new file mode 100644 index 0000000000000000000000000000000000000000..451dd3cc154c0e022e45f5813f4649e24f3bf435 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _ABILITY_MANAGER_SERVICE_EVENT_H_ +#define _ABILITY_MANAGER_SERVICE_EVENT_H_ + +#include +#include +#include + +namespace STtools { +class Event { +public: + Event(); + ~Event(); + bool Compare(); + int WaitingMessage(const std::string &message, int timeout_ms, bool locked); + void CompleteMessage(const std::string &message); + void Clean(); + +private: + std::mutex mutex_; + std::condition_variable cv_; + std::string waiting_message_; + std::vector complete_message_; +}; + +int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 60); +void Completed(Event &event, const std::string &eventName, const int code); +void CleanMsg(Event &event); +} // namespace STtools +#endif // _ABILITY_MANAGER_SERVICE_EVENT_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h new file mode 100644 index 0000000000000000000000000000000000000000..de302b0a00294e88ba04d85c518ca4857c5ec08c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _ABILITY_MANAGER_SERVICE_ST_OPERATOR_H_ +#define _ABILITY_MANAGER_SERVICE_ST_OPERATOR_H_ + +#include +#include +#include + +namespace STtools { +using std::string; +class StOperator; +std::vector SerializationStOperatorToVector(StOperator &ParentOperator); +void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector &vectorOperator); +class StOperator { +private: + std::vector> g_childOperator; + std::shared_ptr g_parentOperator; + string g_abilityType; + string g_bundleName; + string g_abilityName; + string g_operatorName; // data ability + string g_message; + /* data */ + static int countChild; + +public: + StOperator(); + StOperator(const string &type, const string &bundle, const string &ability, const string &operatorName = "", + const string &message = ""); + ~StOperator(); + static int GetCountChild(); + string GetAbilityType(); + StOperator &SetAbilityType(const string &type); + string GetBundleName(); + StOperator &SetBundleName(const string &bundleName); + string GetAbilityName(); + StOperator &SetAbilityName(const string &abilityName); + string GetOperatorName(); + StOperator &SetOperatorName(const string &operatorName); + string GetMessage(); + StOperator &SetMessage(const string &message); + StOperator &AddChildOperator(std::shared_ptr childOperator); + std::vector> GetChildOperator(); + std::vector> PopChildOperator(); +}; +} // namespace STtools +#endif // _ABILITY_MANAGER_SERVICE_ST_OPERATOR_H_ + diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h new file mode 100644 index 0000000000000000000000000000000000000000..716d3aabad84b07db79c14d84d10d1288d6c48da --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_ST_PAGE_ABILITY_EVENT_H_ +#define _AMS_ST_PAGE_ABILITY_EVENT_H_ + +#include +#include +#include +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "ability_manager.h" +#include "running_process_info.h" + +namespace OHOS { +namespace AppExecFwk { +namespace STEventName { +const std::string g_eventName = "resp_st_page_ability_callback"; +const std::string g_eventNameProcessMemory = "resp_st_process_memory_info"; +const std::string g_pidEventName = "resp_st_page_ability_pid_callback"; +const std::string g_abilityStateInit = ":Init"; +const std::string g_abilityStateOnStart = ":OnStart"; +const std::string g_abilityStateOnStop = ":OnStop"; +const std::string g_abilityStateOnActive = ":OnActive"; +const std::string g_abilityStateOnInactive = ":OnInactive"; +const std::string g_abilityStateOnBackground = ":OnBackground"; +const std::string g_abilityStateOnForeground = ":OnForeground"; +const std::string g_abilityStateOnNewWant = ":OnNewWant"; +const std::string g_abilityStateOnCommand = ":OnCommand"; +const std::string g_abilityStateOnConnect = ":OnConnect"; +const std::string g_abilityStateOnDisconnect = ":OnDisconnect"; +const std::string g_abilityStateInsert = ":Insert"; +const std::string g_abilityStateDelete = ":Delete"; +const std::string g_abilityStateUpdate = ":Update"; +const std::string g_abilityStateQuery = ":Query"; +const std::string g_abilityStateGetFileTypes = ":GetFileTypes"; +const std::string g_abilityStateOpenFile = ":OpenFile"; +const std::string g_getWantAgentState = ":GetWantAgentFail"; +const std::string g_triggerWantAgentState = ":TriggerWantAgentSuccess"; +const int g_defeventCode = 0; +const std::vector g_eventList = { + "requ_page_ability_terminate", + "requ_get_process_memory_info", + "requ_disconnect_service", + "requ_page_ability_terminate_caller", + "requ_page_ability_terminate_result", +}; + +static constexpr uint32_t LOAD_TIMEOUT = 3000; // ms +static constexpr uint32_t ACTIVE_TIMEOUT = 5000; // ms +static constexpr uint32_t INACTIVE_TIMEOUT = 500; // ms +static constexpr uint32_t BACKGROUND_TIMEOUT = 10000; // ms +static constexpr uint32_t TERMINATE_TIMEOUT = 10000; // ms +static constexpr uint32_t CONNECT_TIMEOUT = 500; // ms +static constexpr uint32_t DISCONNECT_TIMEOUT = 500; // ms +static constexpr uint32_t COMMAND_TIMEOUT = 5000; // ms +static constexpr uint32_t SYSTEM_UI_TIMEOUT = 5000; // ms +static constexpr uint32_t RESTART_TIMEOUT = 5000; // ms +static constexpr uint32_t RESTART_ABILITY_TIMEOUT = 500; // ms +} // namespace STEventName + +class STPageAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + STPageAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, std::shared_ptr ability, + sptr &stub) + : CommonEventSubscriber(sp), ability_(ability), stub_(stub) + {} + ~STPageAbilityEventSubscriber() + {} + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + std::string RunningProcessInfoToString(std::vector &infos); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + +private: + std::weak_ptr ability_; + wptr stub_; +}; + +class STPageAbilityEvent { +public: + STPageAbilityEvent() = default; + STPageAbilityEvent(const std::string &className); + ~STPageAbilityEvent() = default; + + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void SubscribeEvent(std::vector eventList, std::shared_ptr ability, + sptr stub = nullptr); + void UnsubscribeEvent(); + std::string GetEventDate(const std::string &stateCallbackCount); + std::string GetCallBackPath(const std::string &callBackPath); + std::string GetAbilityStatus(const std::string &abilityStatus); + + int GetOnStartCount(); + int GetOnStopCount(); + int GetOnActiveCount(); + int GetOnInactiveCount(); + int GetOnBackgroundCount(); + int GetOnForegroundCount(); + int GetOnNewWantCount(); + int GetOnCommandCount(); + int GetOnConnectCount(); + int GetOnDisconnectCount(); + +private: + std::shared_ptr subscriber_; + int onStartCount_ = 0; + int onStopCount_ = 0; + int onActiveCount_ = 0; + int onInactiveCount_ = 0; + int onBackgroundCount_ = 0; + int onForegroundCount_ = 0; + int onNewWantCount_ = 0; + int onCommandCount_ = 0; + int onConnectCount_ = 0; + int onDisconnectCount_ = 0; + std::string className_; + std::string callBackPath_; + std::string abilityStatus_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ST_PAGE_ABILITY_EVENT_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..933a13149cedd0306a45973a8d488359257eb0c8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "event.h" +#include +#include + +namespace STtools { +int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) +{ + return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); +} + +void Completed(Event &event, const std::string &eventName, const int code) +{ + return event.CompleteMessage(std::to_string(code) + eventName); +} + +void CleanMsg(Event &event) +{ + return event.Clean(); +} + +Event::Event() +{ + waiting_message_ = ""; + complete_message_.clear(); +} + +Event::~Event() +{ + waiting_message_ = ""; + std::vector tmp_vector; + tmp_vector.swap(complete_message_); + complete_message_.clear(); +} + +bool Event::Compare() +{ + if (!waiting_message_.empty()) { + for (size_t i = 0; i < complete_message_.size(); i++) { + if (waiting_message_.compare(complete_message_.at(i)) == 0) { + complete_message_.erase(std::begin(complete_message_) + i, std::begin(complete_message_) + i + 1); + waiting_message_ = ""; + return true; + } + } + } + return false; +} + +int Event::WaitingMessage(const std::string &message, int timeout_ms, bool locked) +{ + std::unique_lock lock(mutex_); + waiting_message_ = message; + if (Compare()) { + return 0; + } + + if (locked) { + cv_.wait(lock); + return 0; + } + + if (cv_.wait_for(lock, std::chrono::seconds(timeout_ms)) == std::cv_status::timeout) { + waiting_message_ = ""; + return -1; + } + return 0; +} + +void Event::CompleteMessage(const std::string &message) +{ + std::unique_lock lock(mutex_); + if (waiting_message_.compare(message) == 0) { + waiting_message_ = ""; + cv_.notify_all(); + return; + } + complete_message_.push_back(message); + return; +} + +void Event::Clean() +{ + waiting_message_ = ""; + complete_message_.clear(); +} +} // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7be2b438ffd2fcbd6f9c8bf3cf6f79be3030a5c9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "stoperator.h" +#include + +namespace STtools { +using std::string; + +void PushOperatorInVector(std::vector &vectorOperator, StOperator &ParentOperator) +{ + vectorOperator.emplace_back(std::to_string(ParentOperator.GetChildOperator().size())); + vectorOperator.emplace_back(ParentOperator.GetAbilityType()); + vectorOperator.emplace_back(ParentOperator.GetBundleName()); + vectorOperator.emplace_back(ParentOperator.GetAbilityName()); + vectorOperator.emplace_back(ParentOperator.GetOperatorName()); + vectorOperator.emplace_back(ParentOperator.GetMessage()); + for (auto child : ParentOperator.GetChildOperator()) { + PushOperatorInVector(vectorOperator, *child); + } +} + +std::vector SerializationStOperatorToVector(StOperator &ParentOperator) +{ + std::vector vectorOperator; + PushOperatorInVector(vectorOperator, ParentOperator); + return vectorOperator; +} + +void PullOperatorFromVector(StOperator &ParentOperator, std::vector &vectorOperator) +{ + int childnum = std::stoi(vectorOperator.front()); + vectorOperator.erase(vectorOperator.begin()); + string abilityType = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + string bundleName = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + string abilityName = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + string operatorName = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + string message = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + ParentOperator.SetAbilityType(abilityType) + .SetBundleName(bundleName) + .SetAbilityName(abilityName) + .SetOperatorName(operatorName) + .SetMessage(message); + for (int i = 0; i < childnum; i++) { + auto child = std::make_shared(); + if (child == nullptr) { + return; + } + ParentOperator.AddChildOperator(child); + PullOperatorFromVector(*(child.get()), vectorOperator); + } +} + +void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector &vectorOperator) +{ + PullOperatorFromVector(ParentOperator, vectorOperator); +} + +int StOperator::countChild = 0; + +StOperator::StOperator() + : g_parentOperator(nullptr), g_abilityType("0"), + g_bundleName(""), g_abilityName(""), g_operatorName(""), g_message("") +{ + g_childOperator.clear(); + StOperator::countChild++; +} + +StOperator::StOperator( + const string &type, const string &bundle, const string &ability, const string &operatorName, const string &message) + : g_parentOperator(nullptr), + g_abilityType(type), + g_bundleName(bundle), + g_abilityName(ability), + g_operatorName(operatorName), + g_message("") +{ + g_childOperator.clear(); + StOperator::countChild++; +} + +StOperator::~StOperator() +{ + g_childOperator.clear(); + StOperator::countChild--; +} + +int StOperator::GetCountChild() +{ + return StOperator::countChild; +} + +string StOperator::GetAbilityType() +{ + return g_abilityType; +} + +StOperator &StOperator::SetAbilityType(const string &type) +{ + g_abilityType = type; + return *this; +} + +string StOperator::GetBundleName() +{ + return g_bundleName; +} + +StOperator &StOperator::SetBundleName(const string &bundleName) +{ + g_bundleName = bundleName; + return *this; +} + +string StOperator::GetAbilityName() +{ + return g_abilityName; +} + +StOperator &StOperator::SetAbilityName(const string &abilityName) +{ + g_abilityName = abilityName; + return *this; +} + +string StOperator::GetOperatorName() +{ + return g_operatorName; +} + +StOperator &StOperator::SetOperatorName(const string &operatorName) +{ + g_operatorName = operatorName; + return *this; +} + +string StOperator::GetMessage() +{ + return g_message; +} + +StOperator &StOperator::SetMessage(const string &message) +{ + g_message = message; + return *this; +} + +StOperator &StOperator::AddChildOperator(std::shared_ptr childOperator) +{ + if (childOperator == nullptr) { + return *this; + } + childOperator->g_parentOperator = std::make_shared(*this); + g_childOperator.emplace_back(childOperator); + return *this; +} + +std::vector> StOperator::GetChildOperator() +{ + return g_childOperator; +} + +std::vector> StOperator::PopChildOperator() +{ + std::vector> popChildOperator = g_childOperator; + for (auto child : popChildOperator) { + child->g_parentOperator = nullptr; + } + g_childOperator.clear(); + return popChildOperator; +} +} // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f13a7db485f029b3c0cf0c7a1b68f2d85d2bd663 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "stpageabilityevent.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +STPageAbilityEvent::STPageAbilityEvent(const std::string &className) +{ + this->className_ = className; +} + +bool STPageAbilityEvent::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void STPageAbilityEvent::SubscribeEvent( + std::vector eventList, std::shared_ptr ability, sptr stub) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo, ability, stub); + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void STPageAbilityEvent::UnsubscribeEvent() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::string STPageAbilityEvent::GetEventDate(const std::string &stateCallbackCount) +{ + return this->className_ + stateCallbackCount; +} + +std::string STPageAbilityEvent::GetCallBackPath(const std::string &callBackPath) +{ + this->callBackPath_ += callBackPath; + return this->callBackPath_; +} + +std::string STPageAbilityEvent::GetAbilityStatus(const std::string &abilityStatus) +{ + this->abilityStatus_ += abilityStatus; + return this->abilityStatus_; +} + +int STPageAbilityEvent::GetOnStartCount() +{ + onStartCount_++; + return onStartCount_; +} + +int STPageAbilityEvent::GetOnStopCount() +{ + onStopCount_++; + return onStopCount_; +} + +int STPageAbilityEvent::GetOnActiveCount() +{ + onActiveCount_++; + return onActiveCount_; +} + +int STPageAbilityEvent::GetOnInactiveCount() +{ + onInactiveCount_++; + return onInactiveCount_; +} + +int STPageAbilityEvent::GetOnBackgroundCount() +{ + onBackgroundCount_++; + return onBackgroundCount_; +} + +int STPageAbilityEvent::GetOnForegroundCount() +{ + onForegroundCount_++; + return onForegroundCount_; +} + +int STPageAbilityEvent::GetOnNewWantCount() +{ + onNewWantCount_++; + return onNewWantCount_; +} + +int STPageAbilityEvent::GetOnCommandCount() +{ + onCommandCount_++; + return onCommandCount_; +} + +int STPageAbilityEvent::GetOnConnectCount() +{ + onConnectCount_++; + return onConnectCount_; +} + +int STPageAbilityEvent::GetOnDisconnectCount() +{ + onDisconnectCount_++; + return onDisconnectCount_; +} + +void STPageAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (!this->ability_.lock()) { + APP_LOGI("STPageAbilityEventSubscriber:ability_ is nullptr"); + } + if (eventName.compare("requ_page_ability_terminate") == 0) { + std::string target = data.GetData(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + (this->ability_.lock())->TerminateAbility(); + } + } + if (eventName.compare("requ_get_process_memory_info") == 0) { + } + if (eventName.compare("requ_disconnect_service") == 0) { + std::string target = data.GetData(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + if (stub_.promote()) { + (this->ability_.lock())->DisconnectAbility(stub_.promote()); + } + APP_LOGI("GetMyProcessMemoryInfo:stub_ is nullptr"); + } + } + if (eventName.compare("requ_page_ability_terminate_caller") == 0) { + std::string target = data.GetData(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + int requestCode = data.GetCode(); + (this->ability_.lock())->TerminateAbility(requestCode); + } + } + if (eventName.compare("requ_page_ability_terminate_result") == 0) { + std::string target = data.GetData(); + int startId = data.GetCode(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + (this->ability_.lock())->TerminateAbilityResult(startId); + } + } +} + +std::string STPageAbilityEventSubscriber::RunningProcessInfoToString(std::vector &infos) +{ + std::string data = ""; + return data; +} + +bool STPageAbilityEventSubscriber::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostCommonA-signed.hap b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostCommonA-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..7366fbf7c2e442eb9a0e69c5f98fe1d2753df135 Binary files /dev/null and b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostCommonA-signed.hap differ diff --git a/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostCommonB-signed.hap b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostCommonB-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..dec57d49f67a8acce1f7b1b340e28c3b14a15238 Binary files /dev/null and b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostCommonB-signed.hap differ diff --git a/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNoPerm-signed.hap b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNoPerm-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..af2b3aa0076b116cc8a6bddf80a8229f40cb69ba Binary files /dev/null and b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNoPerm-signed.hap differ diff --git a/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormal-signed.hap b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormal-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..d33264218d22cfe8adead95fb17f7d1a179b9ab3 Binary files /dev/null and b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormal-signed.hap differ diff --git a/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormalB-signed.hap b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormalB-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..1aae96bdca4b315127cd11b7783f7cfdac667fe5 Binary files /dev/null and b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormalB-signed.hap differ diff --git a/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormalC-signed.hap b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormalC-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..dd698b11e995049eb75251121ab1625dea566cd1 Binary files /dev/null and b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNormalC-signed.hap differ diff --git a/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNotSys-signed.hap b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNotSys-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..66631e8bdda3a03806b481fbde8aef285702125a Binary files /dev/null and b/test/resource/fms/fms_host_ability_bundle/native/fmsSystemTestHostNotSys-signed.hap differ diff --git a/test/resource/fms/fms_provider_ability_bundle/native/formSystemTestServiceA-signed.hap b/test/resource/fms/fms_provider_ability_bundle/native/formSystemTestServiceA-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..a3844af47d7af173bdff35ae5283fb3bc758cd7e Binary files /dev/null and b/test/resource/fms/fms_provider_ability_bundle/native/formSystemTestServiceA-signed.hap differ diff --git a/test/resource/fms/fms_provider_ability_bundle/native/formSystemTestServiceB-signed.hap b/test/resource/fms/fms_provider_ability_bundle/native/formSystemTestServiceB-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..9ed696779567fcb639fc0e074142788840dd5840 Binary files /dev/null and b/test/resource/fms/fms_provider_ability_bundle/native/formSystemTestServiceB-signed.hap differ diff --git a/test/resource/fms/fms_self_starting_host_bundle/fmsSystemTestSelfStartingA-signed.hap b/test/resource/fms/fms_self_starting_host_bundle/fmsSystemTestSelfStartingA-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..6400fd7419717874242452134fc5ed217a33a1ea Binary files /dev/null and b/test/resource/fms/fms_self_starting_host_bundle/fmsSystemTestSelfStartingA-signed.hap differ diff --git a/test/resource/fms/fms_self_starting_host_bundle/fmsSystemTestSelfStartingB-signed.hap b/test/resource/fms/fms_self_starting_host_bundle/fmsSystemTestSelfStartingB-signed.hap new file mode 100644 index 0000000000000000000000000000000000000000..a28de7950d6edcd31877260c6560179b6d40e1ff Binary files /dev/null and b/test/resource/fms/fms_self_starting_host_bundle/fmsSystemTestSelfStartingB-signed.hap differ diff --git a/test/resource/formsystemtestability/BUILD.gn b/test/resource/formsystemtestability/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..45d2135c87bdbeaed20a6256e3dffd0568baf2dd --- /dev/null +++ b/test/resource/formsystemtestability/BUILD.gn @@ -0,0 +1,33 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. + +group("fms_system_test_app") { + deps = [ + "fmsSystemPerformance:fmsSystemPerformance", + "fmsSystemStress:fmsSystemStress", + "fmsSystemTestHostCommonA:fmsSystemTestHostCommonA", + "fmsSystemTestHostCommonB:fmsSystemTestHostCommonB", + "fmsSystemTestHostNoPerm:fmsSystemTestHostNoPerm", + "fmsSystemTestHostNormal:fmsSystemTestHostNormal", + "fmsSystemTestHostNormalB:fmsSystemTestHostNormalB", + "fmsSystemTestHostNormalC:fmsSystemTestHostNormalC", + "fmsSystemTestHostNotSys:fmsSystemTestHostNotSys", + "fmsSystemTestSelfStarting/selfStartingTestHostA:selfStartingTestHostA", + "fmsSystemTestSelfStarting/selfStartingTestHostB:selfStartingTestHostB", + "formSystemTestServiceA:formSystemTestServiceA", + "formSystemTestServiceB:formSystemTestServiceB", + "formSystemTestServiceC:formSystemTestServiceC", + "formSystemTestServiceD:formSystemTestServiceD", + "formSystemTestServiceE:formSystemTestServiceE", + ] +} diff --git a/test/resource/formsystemtestability/fmsSystemPerformance/BUILD.gn b/test/resource/formsystemtestability/fmsSystemPerformance/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..6963ef0dedd6ea7245e8060bf89587994dd4922d --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemPerformance/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemPerformanceConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemPerformance") { + sources = [ + "../tool/src/form_test_utils.cpp", + "src/form_ability_performance.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":fmsSystemPerformanceConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemPerformance/config.json b/test/resource/formsystemtestability/fmsSystemPerformance/config.json new file mode 100755 index 0000000000000000000000000000000000000000..09e073e97b6ea28c410b61510f45c588210e2110 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemPerformance/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.performance", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.performance.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityPerformance", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability Performance", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmssystemperformance", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemPerformance/include/form_ability_performance.h b/test/resource/formsystemtestability/fmsSystemPerformance/include/form_ability_performance.h new file mode 100755 index 0000000000000000000000000000000000000000..98267ecc813449326c2e9d644aeba06043cfb3c4 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemPerformance/include/form_ability_performance.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_PERFORMANCE_H_ +#define _FORM_ABILITY_PERFORMANCE_H_ +#include +#include +#include +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +using std::string; + +namespace OHOS { +namespace AppExecFwk { +typedef bool (*FunctionPtr)(); + +class FormEventSubscriber; +class FormAbilityPerformance : public Ability { +public: + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + + // Test case list + void FMS_performanceTest_0100(std::string data); + void FMS_performanceTest_0200(std::string data); + void FMS_performanceTest_0300(std::string data); + void FMS_performanceTest_0400(std::string data); + void FMS_performanceTest_0500(std::string data); + void FMS_performanceTest_0600(std::string data); + void FMS_performanceTest_0700(std::string data); + void FMS_performanceTest_1300(std::string data); + void FMS_performanceTest_1400(std::string data); + void FMS_performanceTest_1500(std::string data); + void FMS_performanceTest_1600(std::string data); + + std::shared_ptr subscriber_; + + class PerformanceFormCallback : public FormCallback { + public: + PerformanceFormCallback(std::string name, int code):caseName_(name), code_(code) { } + virtual ~PerformanceFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_ = ""; + int code_ = 0; + FormAbilityPerformance *ability_ = nullptr; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + using FormFunc = void (FormAbilityPerformance::*)(std::string data); + std::map memberFuncMap_; + std::map calledFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityPerformance *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_PERFORMANCE_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemPerformance/src/form_ability_performance.cpp b/test/resource/formsystemtestability/fmsSystemPerformance/src/form_ability_performance.cpp new file mode 100755 index 0000000000000000000000000000000000000000..eb7b1e1ab4feb394c512cfb1dcd837d71c2c8c02 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemPerformance/src/form_ability_performance.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include + +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "form_ability_performance.h" + +namespace { + using namespace OHOS::AAFwk; + using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +const int ONE = 1; +const int TWO = 2; +std::vector eventList = { + FORM_EVENT_REQ_PERFORMANCE_TEST_0100, + FORM_EVENT_REQ_PERFORMANCE_TEST_0200, + FORM_EVENT_REQ_PERFORMANCE_TEST_0300, + FORM_EVENT_REQ_PERFORMANCE_TEST_0400, + FORM_EVENT_REQ_PERFORMANCE_TEST_0500, + FORM_EVENT_REQ_PERFORMANCE_TEST_0600, + FORM_EVENT_REQ_PERFORMANCE_TEST_0700, + FORM_EVENT_REQ_PERFORMANCE_TEST_1300, + FORM_EVENT_REQ_PERFORMANCE_TEST_1400, + FORM_EVENT_REQ_PERFORMANCE_TEST_1500, + FORM_EVENT_REQ_PERFORMANCE_TEST_1600, +}; + +static std::string g_formId = 0; +static std::string g_bundleName = "com.form.formsystemtestservicea"; +static std::string g_moduleName = "formmodule001"; +void FormAbilityPerformance::PerformanceFormCallback::OnAcquired( + const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s formId: %{public}s", __func__, std::to_string(formJsInfo.formId).c_str()); + APP_LOGI("%{public}s bundleName: %{public}s", __func__, formJsInfo.bundleName.c_str()); + APP_LOGI("%{public}s abilityName: %{public}s", __func__, formJsInfo.abilityName.c_str()); + APP_LOGI("%{public}s formName: %{public}s", __func__, formJsInfo.formName.c_str()); + APP_LOGI("%{public}s formTempFlg: %{public}d", __func__, formJsInfo.formTempFlg); + APP_LOGI("%{public}s jsFormCodePath: %{public}s", __func__, formJsInfo.jsFormCodePath.c_str()); + APP_LOGI("%{public}s formData: %{public}s", __func__, formJsInfo.formData.c_str()); + APP_LOGI("%{public}s formProviderData GetDataString: %{public}s", + __func__, formJsInfo.formProviderData.GetDataString().c_str()); + + g_formId = std::to_string(formJsInfo.formId); + + if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0100) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_101, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0200) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_201, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0300) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_301, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0400) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_401, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0500) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_501, std::to_string(formJsInfo.formId)); + } else { + FormTestUtils::PublishEvent(this->caseName_, this->code_ + ONE, std::to_string(formJsInfo.formId)); + } +} + +void FormAbilityPerformance::PerformanceFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s formId: %{public}s", __func__, std::to_string(formJsInfo.formId).c_str()); + APP_LOGI("%{public}s bundleName: %{public}s", __func__, formJsInfo.bundleName.c_str()); + APP_LOGI("%{public}s abilityName: %{public}s", __func__, formJsInfo.abilityName.c_str()); + APP_LOGI("%{public}s formName: %{public}s", __func__, formJsInfo.formName.c_str()); + APP_LOGI("%{public}s formTempFlg: %{public}d", __func__, formJsInfo.formTempFlg); + APP_LOGI("%{public}s jsFormCodePath: %{public}s", __func__, formJsInfo.jsFormCodePath.c_str()); + APP_LOGI("%{public}s formData: %{public}s", __func__, formJsInfo.formData.c_str()); + APP_LOGI("%{public}s formProviderData GetDataString: %{public}s", + __func__, formJsInfo.formProviderData.GetDataString().c_str()); + + if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0100) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_102, "true"); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0200) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_202, "true"); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0300) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_302, "true"); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0400) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_402, "true"); + } else if (this->caseName_ == FORM_EVENT_RECV_PERFORMANCE_TEST_0500) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_502, "true"); + } else { + FormTestUtils::PublishEvent(this->caseName_, this->code_ + TWO, "true"); + } +} + +void FormAbilityPerformance::PerformanceFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +void FormAbilityPerformance::FMS_performanceTest_0100(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_PERFORMANCE_TEST_0100, EVENT_CODE_100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[FMS_performanceTest_0100] AcquireForm end"); + } else { + APP_LOGE("[FMS_performanceTest_0100] AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0100, EVENT_CODE_100, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_0200(std::string data) +{ + bool bResult = DeleteForm(atoll(g_formId.c_str())); + if (bResult) { + APP_LOGI("[FMS_performanceTest_0200] DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0200, EVENT_CODE_200, "true"); + } else { + APP_LOGE("[FMS_performanceTest_0200] DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0200, EVENT_CODE_200, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_0300(std::string data) +{ + bool isReleaseCache = false; + bool bResult = ReleaseForm(atoll(g_formId.c_str()), isReleaseCache); + if (bResult) { + APP_LOGI("[FMS_performanceTest_0300] ReleaseForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0300, EVENT_CODE_300, "true"); + } else { + APP_LOGE("[FMS_performanceTest_0300] ReleaseForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0300, EVENT_CODE_300, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_0400(std::string data) +{ + bool bResult = CastTempForm(atoll(g_formId.c_str())); + if (bResult) { + APP_LOGI("[FMS_performanceTest_0400] CastTempForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0400, EVENT_CODE_400, "true"); + } else { + APP_LOGE("[FMS_performanceTest_0400] CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0400, EVENT_CODE_400, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_0500(std::string data) +{ + std::vector formIds; + formIds.push_back(atoll(g_formId.c_str())); + bool bResult = NotifyVisibleForms(formIds); + if (bResult) { + APP_LOGI("[FMS_performanceTest_0500] NotifyVisibleForms end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0500, EVENT_CODE_500, "true"); + } else { + APP_LOGE("[FMS_performanceTest_0500] NotifyVisibleForms error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0500, EVENT_CODE_500, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_0600(std::string data) +{ + std::vector formIds; + formIds.push_back(atoll(g_formId.c_str())); + bool bResult = NotifyInvisibleForms(formIds); + if (bResult) { + APP_LOGI("[FMS_performanceTest_0600] NotifyInvisibleForms end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0600, EVENT_CODE_600, "true"); + } else { + APP_LOGE("[FMS_performanceTest_0600] NotifyInvisibleForms error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0600, EVENT_CODE_600, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_0700(std::string data) +{ + bool bResult = RequestForm(atoll(g_formId.c_str())); + if (bResult) { + APP_LOGI("[FMS_performanceTest_0700] RequestForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0700, EVENT_CODE_700, "true"); + } else { + APP_LOGE("[FMS_performanceTest_0700] RequestForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1300, EVENT_CODE_700, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_1300(std::string data) +{ + std::vector formInfos; + bool bResult = GetAllFormsInfo(formInfos); + if (bResult) { + APP_LOGI("[FMS_performanceTest_1300] GetAllFormsInfo end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1300, EVENT_CODE_1300, "true"); + } else { + APP_LOGE("[FMS_performanceTest_1300] GetAllFormsInfo error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1300, EVENT_CODE_1300, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_1400(std::string data) +{ + std::vector formInfos; + bool bResult = GetFormsInfoByApp(g_bundleName, formInfos); + if (bResult) { + APP_LOGI("[FMS_performanceTest_1400] GetFormsInfoByApp end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1400, EVENT_CODE_1400, "true"); + } else { + APP_LOGE("[FMS_performanceTest_1400] GetFormsInfoByApp error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1400, EVENT_CODE_1400, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_1500(std::string data) +{ + std::vector formInfos; + bool bResult = GetFormsInfoByModule(g_bundleName, g_moduleName, formInfos); + if (bResult) { + APP_LOGI("[FMS_performanceTest_1500] GetFormsInfoByModule end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1500, EVENT_CODE_1500, "true"); + } else { + APP_LOGE("[FMS_performanceTest_1500] GetFormsInfoByModule error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1500, EVENT_CODE_1500, "false"); + } +} + +void FormAbilityPerformance::FMS_performanceTest_1600(std::string data) +{ + bool bResult = CheckFMSReady(); + if (bResult) { + APP_LOGI("[FMS_performanceTest_1600] CheckFMSReady end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1600, EVENT_CODE_1600, "true"); + } else { + APP_LOGE("[FMS_performanceTest_1600] CheckFMSReady error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1600, EVENT_CODE_1600, "false"); + } +} + +void FormAbilityPerformance::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityPerformance::onStart"); + Ability::OnStart(want); +} + +void FormAbilityPerformance::OnActive() +{ + APP_LOGI("FormAbilityPerformance::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityPerformance::OnStop() +{ + APP_LOGI("FormAbilityPerformance::OnStop"); + + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void FormAbilityPerformance::OnInactive() +{ + APP_LOGI("FormAbilityPerformance::OnInactive"); + + Ability::OnInactive(); +} + +void FormAbilityPerformance::OnBackground() +{ + APP_LOGI("FormAbilityPerformance::OnBackground"); + + Ability::OnBackground(); +} + +void FormAbilityPerformance::SubscribeEvent() +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityPerformance::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityPerformance::Init"); + Ability::Init(abilityInfo, application, handler, token); + + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_0100] = &FormAbilityPerformance::FMS_performanceTest_0100; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_0200] = &FormAbilityPerformance::FMS_performanceTest_0200; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_0300] = &FormAbilityPerformance::FMS_performanceTest_0300; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_0400] = &FormAbilityPerformance::FMS_performanceTest_0400; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_0500] = &FormAbilityPerformance::FMS_performanceTest_0500; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_0600] = &FormAbilityPerformance::FMS_performanceTest_0600; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_0700] = &FormAbilityPerformance::FMS_performanceTest_0700; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_1300] = &FormAbilityPerformance::FMS_performanceTest_1300; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_1400] = &FormAbilityPerformance::FMS_performanceTest_1400; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_1500] = &FormAbilityPerformance::FMS_performanceTest_1500; + memberFuncMap_[FORM_EVENT_REQ_PERFORMANCE_TEST_1600] = &FormAbilityPerformance::FMS_performanceTest_1600; + + SubscribeEvent(); +} + +void FormAbilityPerformance::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + if (calledFuncMap_.find(action) != calledFuncMap_.end()) { + return; + } + calledFuncMap_.emplace(action, 0); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilityPerformance::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s, code=%{public}d, data=%{public}s", + data.GetWant().GetAction().c_str(), data.GetCode(), data.GetData().c_str()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityPerformance) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemStress/BUILD.gn b/test/resource/formsystemtestability/fmsSystemStress/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..fe15268f31d65964c99edd17173df80a351e1941 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemStress/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemStressConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemStress") { + sources = [ + "../tool/src/form_test_utils.cpp", + "src/form_ability_stress.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":fmsSystemStressConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemStress/config.json b/test/resource/formsystemtestability/fmsSystemStress/config.json new file mode 100755 index 0000000000000000000000000000000000000000..8124df3ddcc8ea64002bcdc98d8626c8f1053aa7 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemStress/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.stress", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.stress.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityStress", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability Stress", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsstresstest", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemStress/include/form_ability_stress.h b/test/resource/formsystemtestability/fmsSystemStress/include/form_ability_stress.h new file mode 100755 index 0000000000000000000000000000000000000000..4cc9556ee3f6e67e5dda9eebdab1a605d511766a --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemStress/include/form_ability_stress.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_STRESS_H_ +#define _FORM_ABILITY_STRESS_H_ +#include +#include +#include +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + + +using std::string; + +namespace OHOS { +namespace AppExecFwk { +typedef bool (*FunctionPtr)(); + +class FormEventSubscriber; +class FormAbilityStress : public Ability { +public: + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + + // Test case list + void FMS_stressTest_0100(std::string data); + void FMS_stressTest_0100_sub01(std::string form_id); + void FMS_stressTest_0200(std::string data); + void FMS_stressTest_0200_sub01(std::string form_id); + void FMS_stressTest_0200_sub02(std::string form_id); + void FMS_stressTest_0200_sub03(std::string form_id); + void FMS_stressTest_0300(std::string data); + void FMS_stressTest_0300_sub01(std::string form_id); + void FMS_stressTest_0300_sub02(std::string form_id); + void FMS_stressTest_0400(std::string data); + void FMS_stressTest_0500(std::string data); + void FMS_stressTest_0600(std::string data); + void FMS_stressTest_0700(std::string data); + void FMS_stressTest_0800(std::string data); + void FMS_stressTest_0900(std::string data); + void FMS_stressTest_1000(std::string data); + void FMS_stressTest_1100(std::string data); + void FMS_stressTest_1100_sub01(std::string form_id); + void FMS_stressTest_1100_sub02(std::string form_id); + void FMS_stressTest_1100_sub03(std::string form_id); + void FMS_stressTest_1200(std::string data); + void FMS_stressTest_1300(std::string data); + void FMS_stressTest_1300_sub01(std::string form_id); + void FMS_stressTest_1300_sub02(std::string form_id); + void FMS_stressTest_1300_sub03(std::string form_id); + void FMS_stressTest_1400(std::string data); + void FMS_stressTest_1500(std::string data); + void FMS_stressTest_1600(std::string data); + void FMS_stressTest_1700(std::string data); + void FMS_stressTest_1700_sub01(std::string data); + void FMS_stressTest_1700_sub02(std::string data); + void FMS_stressTest_1800(std::string data); + + std::shared_ptr subscriber_; + + class StressFormCallback : public FormCallback { + public: + StressFormCallback(std::string name, int code):caseName_(name), code_(code) { } + virtual ~StressFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_ = ""; + int code_ = 0; + FormAbilityStress *ability_ = nullptr; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + using FormFunc = void (FormAbilityStress::*)(std::string data); + std::map memberFuncMap_; + std::map calledFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityStress *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_STRESS_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemStress/src/form_ability_stress.cpp b/test/resource/formsystemtestability/fmsSystemStress/src/form_ability_stress.cpp new file mode 100755 index 0000000000000000000000000000000000000000..6d0f6b52edfa9222f2de311dae99d9dcec18261c --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemStress/src/form_ability_stress.cpp @@ -0,0 +1,631 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include + +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "form_ability_stress.h" + +namespace { + using namespace OHOS::AAFwk; + using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +const int ONE = 1; +const int TWO = 2; +std::vector eventList = { + FORM_EVENT_REQ_STRESS_TEST_0100, FORM_EVENT_REQ_STRESS_TEST_0100_01, FORM_EVENT_REQ_STRESS_TEST_0200, + FORM_EVENT_REQ_STRESS_TEST_0200_01, FORM_EVENT_REQ_STRESS_TEST_0200_02, FORM_EVENT_REQ_STRESS_TEST_0200_03, + FORM_EVENT_REQ_STRESS_TEST_0300, FORM_EVENT_REQ_STRESS_TEST_0300_01, FORM_EVENT_REQ_STRESS_TEST_0300_02, + FORM_EVENT_REQ_STRESS_TEST_0400, FORM_EVENT_REQ_STRESS_TEST_0500, + FORM_EVENT_REQ_STRESS_TEST_1100, FORM_EVENT_REQ_STRESS_TEST_1100_01, FORM_EVENT_REQ_STRESS_TEST_1100_02, + FORM_EVENT_REQ_STRESS_TEST_1100_03, FORM_EVENT_REQ_STRESS_TEST_1300, FORM_EVENT_REQ_STRESS_TEST_1300_01, + FORM_EVENT_REQ_STRESS_TEST_1300_02, FORM_EVENT_REQ_STRESS_TEST_1300_03, + FORM_EVENT_REQ_STRESS_TEST_1700, FORM_EVENT_REQ_STRESS_TEST_1700_01, FORM_EVENT_REQ_STRESS_TEST_1700_02, + FORM_EVENT_REQ_STRESS_TEST_1800, +}; + +static std::string g_bundleName = "com.form.formsystemtestservicea"; +static std::string g_moduleName = "formmodule001"; +void FormAbilityStress::StressFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s formId: %{public}s", __func__, std::to_string(formJsInfo.formId).c_str()); + APP_LOGI("%{public}s bundleName: %{public}s", __func__, formJsInfo.bundleName.c_str()); + APP_LOGI("%{public}s abilityName: %{public}s", __func__, formJsInfo.abilityName.c_str()); + APP_LOGI("%{public}s formName: %{public}s", __func__, formJsInfo.formName.c_str()); + APP_LOGI("%{public}s formTempFlg: %{public}d", __func__, formJsInfo.formTempFlg); + APP_LOGI("%{public}s jsFormCodePath: %{public}s", __func__, formJsInfo.jsFormCodePath.c_str()); + APP_LOGI("%{public}s formData: %{public}s", __func__, formJsInfo.formData.c_str()); + APP_LOGI("%{public}s formProviderData GetDataString: %{public}s", + __func__, formJsInfo.formProviderData.GetDataString().c_str()); + + APP_LOGI("%{public}s caseName_: %{public}s, code_: %{public}d", __func__, this->caseName_.c_str(), this->code_); + + if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0100) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_101, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0200) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_201, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0200_02) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_204, "true"); + ability_->FMS_stressTest_0200_sub03(std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0300) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_301, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0400) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_401, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1100) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1101, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1300) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1301, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1700) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1701, std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1800) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1801, std::to_string(formJsInfo.formId)); + } else { + FormTestUtils::PublishEvent(this->caseName_, this->code_ + ONE, std::to_string(formJsInfo.formId)); + } +} + +void FormAbilityStress::StressFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s formId: %{public}s", __func__, std::to_string(formJsInfo.formId).c_str()); + APP_LOGI("%{public}s bundleName: %{public}s", __func__, formJsInfo.bundleName.c_str()); + APP_LOGI("%{public}s abilityName: %{public}s", __func__, formJsInfo.abilityName.c_str()); + APP_LOGI("%{public}s formName: %{public}s", __func__, formJsInfo.formName.c_str()); + APP_LOGI("%{public}s formTempFlg: %{public}d", __func__, formJsInfo.formTempFlg); + APP_LOGI("%{public}s jsFormCodePath: %{public}s", __func__, formJsInfo.jsFormCodePath.c_str()); + APP_LOGI("%{public}s formData: %{public}s", __func__, formJsInfo.formData.c_str()); + APP_LOGI("%{public}s formProviderData GetDataString: %{public}s", + __func__, formJsInfo.formProviderData.GetDataString().c_str()); + + APP_LOGI("%{public}s caseName_: %{public}s, code_: %{public}d", __func__, this->caseName_.c_str(), this->code_); + + if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0100) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_102, "true"); + ability_->FMS_stressTest_0100_sub01(std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0200) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_202, "true"); + ability_->FMS_stressTest_0200_sub01(std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0300) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_302, "true"); + ability_->FMS_stressTest_0300_sub01(std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_0400) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_402, "true"); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1100) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1102, "true"); + ability_->FMS_stressTest_1100_sub01(std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1300) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1302, "true"); + ability_->FMS_stressTest_1300_sub01(std::to_string(formJsInfo.formId)); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1700) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1702, "true"); + } else if (this->caseName_ == FORM_EVENT_RECV_STRESS_TEST_1800) { + FormTestUtils::PublishEvent(this->caseName_, EVENT_CODE_1802, "true"); + } else { + FormTestUtils::PublishEvent(this->caseName_, this->code_ + TWO, "true"); + } +} + +void FormAbilityStress::StressFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +void FormAbilityStress::FMS_stressTest_0100(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_STRESS_TEST_0100, EVENT_CODE_100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[FMS_stressTest_0100] AcquireForm end"); + } else { + APP_LOGE("[FMS_stressTest_0100] AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0100, EVENT_CODE_100, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_0100_sub01(std::string form_id) +{ + bool bResult = DeleteForm(atoll(form_id.c_str())); + if (bResult) { + APP_LOGI("[FMS_stressTest_0100] DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0100_01, EVENT_CODE_103, "true"); + } else { + APP_LOGE("[FMS_stressTest_0100] DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0100_01, EVENT_CODE_103, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_0200(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_STRESS_TEST_0200, EVENT_CODE_200); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[FMS_stressTest_0200] AcquireForm end"); + } else { + APP_LOGE("[FMS_stressTest_0200] AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0200, EVENT_CODE_200, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_0200_sub01(std::string form_id) +{ + bool isReleaseCache = false; + bool bResult = ReleaseForm(atoll(form_id.c_str()), isReleaseCache); + if (bResult) { + APP_LOGI("[FMS_stressTest_0200] ReleaseForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0200_01, EVENT_CODE_203, "true"); + } else { + APP_LOGE("[FMS_stressTest_0200] ReleaseForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0200_01, EVENT_CODE_203, "false"); + } + + FormAbilityStress::FMS_stressTest_0200_sub02(form_id); +} + +void FormAbilityStress::FMS_stressTest_0200_sub02(std::string form_id) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_STRESS_TEST_0200_02, EVENT_CODE_204); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(atoll(form_id.c_str()), want, callback); + if (bResult) { + APP_LOGI("[FMS_stressTest_0200] AcquireForm sub02 end"); + } else { + APP_LOGE("[FMS_stressTest_0200] AcquireForm sub02 error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0200_02, EVENT_CODE_204, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_0200_sub03(std::string form_id) +{ + bool bResult = DeleteForm(atoll(form_id.c_str())); + if (bResult) { + APP_LOGI("[FMS_stressTest_0200] DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0200_03, EVENT_CODE_205, "true"); + } else { + APP_LOGE("[FMS_stressTest_0200] DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0200_03, EVENT_CODE_205, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_0300(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_STRESS_TEST_0300, EVENT_CODE_300); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[FMS_stressTest_0300] AcquireForm end"); + } else { + APP_LOGE("[FMS_stressTest_0300] AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0300, EVENT_CODE_300, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_0300_sub01(std::string form_id) +{ + bool bResult = CastTempForm(atoll(form_id.c_str())); + if (bResult) { + APP_LOGI("[FMS_stressTest_0300] CastTempForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0300_01, EVENT_CODE_303, "true"); + } else { + APP_LOGE("[FMS_stressTest_0300] CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0300_01, EVENT_CODE_303, "false"); + } + + FormAbilityStress::FMS_stressTest_0300_sub02(form_id); +} + +void FormAbilityStress::FMS_stressTest_0300_sub02(std::string form_id) +{ + bool bResult = DeleteForm(atoll(form_id.c_str())); + if (bResult) { + APP_LOGI("[FMS_stressTest_0300] DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0300_02, EVENT_CODE_304, "true"); + } else { + APP_LOGE("[FMS_stressTest_0300] DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_0300_02, EVENT_CODE_304, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_0400(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_0500(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_0600(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_0700(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_1000(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_1100(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_STRESS_TEST_1100, EVENT_CODE_1100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[FMS_stressTest_1100] AcquireForm end"); + } else { + APP_LOGE("[FMS_stressTest_1100] AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1100, EVENT_CODE_1100, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_1100_sub01(std::string form_id) +{ + std::vector formIds; + formIds.push_back(atoll(form_id.c_str())); + bool bResult = NotifyInvisibleForms(formIds); + if (bResult) { + APP_LOGI("[FMS_stressTest_1100] NotifyInvisibleForms end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1100_01, EVENT_CODE_1103, "true"); + } else { + APP_LOGE("[FMS_stressTest_1100] NotifyInvisibleForms error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1100_01, EVENT_CODE_1103, "false"); + } + + FormAbilityStress::FMS_stressTest_1100_sub02(form_id); +} + +void FormAbilityStress::FMS_stressTest_1100_sub02(std::string form_id) +{ + std::vector formIds; + formIds.push_back(atoll(form_id.c_str())); + bool bResult = NotifyVisibleForms(formIds); + if (bResult) { + APP_LOGI("[FMS_stressTest_1100] NotifyVisibleForms end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1100_02, EVENT_CODE_1104, "true"); + } else { + APP_LOGE("[FMS_stressTest_1100] NotifyVisibleForms error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1100_02, EVENT_CODE_1104, "false"); + } + + FormAbilityStress::FMS_stressTest_1100_sub03(form_id); +} + +void FormAbilityStress::FMS_stressTest_1100_sub03(std::string form_id) +{ + bool bResult = DeleteForm(atoll(form_id.c_str())); + if (bResult) { + APP_LOGI("[FMS_stressTest_1100] DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1100_03, EVENT_CODE_1105, "true"); + } else { + APP_LOGE("[FMS_stressTest_1100] DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1100_03, EVENT_CODE_1105, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_1200(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_1300(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_STRESS_TEST_1300, EVENT_CODE_1300); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[FMS_stressTest_1300] AcquireForm end"); + } else { + APP_LOGE("[FMS_stressTest_1300] AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1300, EVENT_CODE_1300, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_1300_sub01(std::string form_id) +{ + std::vector formIds; + formIds.push_back(atoll(form_id.c_str())); + bool bResult = EnableUpdateForm(formIds); + if (bResult) { + APP_LOGI("[FMS_stressTest_1300] EnableUpdateForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1300_01, EVENT_CODE_1303, "true"); + } else { + APP_LOGE("[FMS_stressTest_1300] EnableUpdateForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1300_01, EVENT_CODE_1303, "false"); + } + + FormAbilityStress::FMS_stressTest_1300_sub02(form_id); +} + +void FormAbilityStress::FMS_stressTest_1300_sub02(std::string form_id) +{ + std::vector formIds; + formIds.push_back(atoll(form_id.c_str())); + bool bResult = DisableUpdateForm(formIds); + if (bResult) { + APP_LOGI("[FMS_stressTest_1300] DisableUpdateForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1300_02, EVENT_CODE_1304, "true"); + } else { + APP_LOGE("[FMS_stressTest_1300] DisableUpdateForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1300_02, EVENT_CODE_1304, "false"); + } + + FormAbilityStress::FMS_stressTest_1300_sub03(form_id); +} + +void FormAbilityStress::FMS_stressTest_1300_sub03(std::string form_id) +{ + bool bResult = DeleteForm(atoll(form_id.c_str())); + if (bResult) { + APP_LOGI("[FMS_stressTest_1300] DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1300_03, EVENT_CODE_1305, "true"); + } else { + APP_LOGE("[FMS_stressTest_1300] DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1300_03, EVENT_CODE_1305, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_1400(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_1500(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_1600(std::string data) +{ +} + +void FormAbilityStress::FMS_stressTest_1700(std::string data) +{ + std::vector formInfos; + bool bResult = GetAllFormsInfo(formInfos); + if (bResult) { + APP_LOGI("[FMS_stressTest_1700] GetAllFormsInfo end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1700, EVENT_CODE_1700, "true"); + } else { + APP_LOGE("[FMS_stressTest_1700] GetAllFormsInfo error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1700, EVENT_CODE_1700, "false"); + } + + FormAbilityStress::FMS_stressTest_1700_sub01(data); +} + +void FormAbilityStress::FMS_stressTest_1700_sub01(std::string data) +{ + std::vector formInfos; + bool bResult = GetFormsInfoByApp(g_bundleName, formInfos); + if (bResult) { + APP_LOGI("[FMS_stressTest_1700] GetFormsInfoByApp end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1700_01, EVENT_CODE_1701, "true"); + } else { + APP_LOGE("[FMS_stressTest_1700] GetFormsInfoByApp error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1700_01, EVENT_CODE_1701, "false"); + } + + FormAbilityStress::FMS_stressTest_1700_sub02(data); +} + +void FormAbilityStress::FMS_stressTest_1700_sub02(std::string data) +{ + std::vector formInfos; + bool bResult = GetFormsInfoByModule(g_bundleName, g_moduleName, formInfos); + if (bResult) { + APP_LOGI("[FMS_stressTest_1700] GetFormsInfoByModule end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1700_02, EVENT_CODE_1702, "true"); + } else { + APP_LOGE("[FMS_stressTest_1700] GetFormsInfoByModule error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1700_02, EVENT_CODE_1702, "false"); + } +} + +void FormAbilityStress::FMS_stressTest_1800(std::string data) +{ + bool bResult = CheckFMSReady(); + if (bResult) { + APP_LOGI("[FMS_stressTest_1800] CheckFMSReady end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1800, EVENT_CODE_1800, "true"); + } else { + APP_LOGE("[FMS_stressTest_1800] CheckFMSReady error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_STRESS_TEST_1800, EVENT_CODE_1800, "false"); + } +} + +void FormAbilityStress::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityStress::onStart"); + Ability::OnStart(want); +} + +void FormAbilityStress::OnActive() +{ + APP_LOGI("FormAbilityStress::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityStress::OnStop() +{ + APP_LOGI("FormAbilityStress::OnStop"); + + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void FormAbilityStress::OnInactive() +{ + APP_LOGI("FormAbilityStress::OnInactive"); + + Ability::OnInactive(); +} + +void FormAbilityStress::OnBackground() +{ + APP_LOGI("FormAbilityStress::OnBackground"); + + Ability::OnBackground(); +} + +void FormAbilityStress::SubscribeEvent() +{ + APP_LOGI("FormAbilityStress::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityStress::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityStress::Init"); + Ability::Init(abilityInfo, application, handler, token); + + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0100] = &FormAbilityStress::FMS_stressTest_0100; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0100_01] = &FormAbilityStress::FMS_stressTest_0100_sub01; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0200] = &FormAbilityStress::FMS_stressTest_0200; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0200_01] = &FormAbilityStress::FMS_stressTest_0200_sub01; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0200_02] = &FormAbilityStress::FMS_stressTest_0200_sub02; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0200_03] = &FormAbilityStress::FMS_stressTest_0200_sub03; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0300] = &FormAbilityStress::FMS_stressTest_0300; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0300_01] = &FormAbilityStress::FMS_stressTest_0300_sub01; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0300_02] = &FormAbilityStress::FMS_stressTest_0300_sub02; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0400] = &FormAbilityStress::FMS_stressTest_0400; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_0500] = &FormAbilityStress::FMS_stressTest_0500; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1100] = &FormAbilityStress::FMS_stressTest_1100; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1100_01] = &FormAbilityStress::FMS_stressTest_1100_sub01; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1100_02] = &FormAbilityStress::FMS_stressTest_1100_sub02; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1100_03] = &FormAbilityStress::FMS_stressTest_1100_sub03; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1300] = &FormAbilityStress::FMS_stressTest_1300; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1300_01] = &FormAbilityStress::FMS_stressTest_1300_sub01; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1300_02] = &FormAbilityStress::FMS_stressTest_1300_sub02; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1300_03] = &FormAbilityStress::FMS_stressTest_1300_sub03; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1700] = &FormAbilityStress::FMS_stressTest_1700; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1700_01] = &FormAbilityStress::FMS_stressTest_1700_sub01; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1700_02] = &FormAbilityStress::FMS_stressTest_1700_sub02; + memberFuncMap_[FORM_EVENT_REQ_STRESS_TEST_1800] = &FormAbilityStress::FMS_stressTest_1800; + + SubscribeEvent(); +} + +void FormAbilityStress::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + if (calledFuncMap_.find(action) != calledFuncMap_.end()) { + return; + } + calledFuncMap_.emplace(action, 0); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilityStress::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s, code=%{public}d, data=%{public}s", + data.GetWant().GetAction().c_str(), data.GetCode(), data.GetData().c_str()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityStress) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonA/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..377c03097d8eafefc412938a10c3ba1c3970f48c --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemTestHostCommonAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemTestHostCommonA") { + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "../tool/src/form_test_utils.cpp", + "src/form_ability_commona.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ + ":fmsSystemTestHostCommonAConfig", + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonA/config.json b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..81bf59d215595e0f8ac116c53ee2bdc7689b0d9e --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.commona", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.commona.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityCommonA", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonA/include/form_ability_commona.h b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/include/form_ability_commona.h new file mode 100644 index 0000000000000000000000000000000000000000..89ae25797a8519d67509d0860d9832ea2a9a887b --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/include/form_ability_commona.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_COMMONA_H_ +#define _FORM_ABILITY_COMMONA_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriberForCommonA; +class FormAbilityCommonA : public Ability { +public: + ~FormAbilityCommonA(); + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + void FMS_acquireForm(std::string data); + void FMS_deleteForm(std::string data); + void FMS_acquireForm_batch(std::string data); + void FMS_deleteFormBatch(std::string data); + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback() + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + using FormFunc = void (FormAbilityCommonA::*)(std::string data); + std::map memberFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriberForCommonA : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriberForCommonA(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriberForCommonA() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityCommonA *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_COMMONA_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonA/src/form_ability_commona.cpp b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/src/form_ability_commona.cpp new file mode 100644 index 0000000000000000000000000000000000000000..401b391d0da4f05d8a717ec874ef315ad4e29403 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/src/form_ability_commona.cpp @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_commona.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "system_test_form_util.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +std::vector eventList = { + FORM_EVENT_REQ_ONE_NORMAL_FORM, + FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, + FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, + FORM_EVENT_REQ_CLEAR_FORM_BATCH +}; +void FormAbilityCommonA::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called[%{public}s]", __func__, std::to_string(formJsInfo.formId).c_str()); +} +void FormAbilityCommonA::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100, std::to_string(formJsInfo.formId)); +} + +void FormAbilityCommonA::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +// Create one form(temp/normal) +void FormAbilityCommonA::FMS_acquireForm(std::string data) +{ + APP_LOGI("%{public}s called, data: %{public}s", __func__, data.c_str()); + std::shared_ptr callback = std::make_shared(); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + if (data == "true") { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + } else { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + } + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[form_ability_commonA]AcquireForm end"); + } else { + APP_LOGE("[form_ability_commonA]AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100, ""); + } +} +void FormAbilityCommonA::FMS_deleteForm(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, "false"); + } +} +void FormAbilityCommonA::FMS_acquireForm_batch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "false"); + } +} +void FormAbilityCommonA::FMS_deleteFormBatch(std::string strFormId) +{ + APP_LOGI("%{public}s called", __func__); + int result = STtools::SystemTestFormUtil::ClearFormRecords(); + if (result == ERR_OK) { + APP_LOGI("Clear form records end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "true"); + } else { + APP_LOGE("Clear form records error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "false"); + } +} +FormAbilityCommonA::~FormAbilityCommonA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} +void FormAbilityCommonA::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityCommonA::onStart"); + Ability::OnStart(want); +} +void FormAbilityCommonA::OnActive() +{ + APP_LOGI("FormAbilityCommonA::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityCommonA::OnStop() +{ + APP_LOGI("FormAbilityCommonA::OnStop"); + + Ability::OnStop(); +} +void FormAbilityCommonA::OnInactive() +{ + APP_LOGI("FormAbilityCommonA::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityCommonA::OnBackground() +{ + APP_LOGI("FormAbilityCommonA::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityCommonA::SubscribeEvent() +{ + APP_LOGI("FormAbilityCommonA::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityCommonA::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityCommonA::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_ONE_NORMAL_FORM] = &FormAbilityCommonA::FMS_acquireForm; + memberFuncMap_[FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL] = &FormAbilityCommonA::FMS_deleteForm; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_BATCH] = &FormAbilityCommonA::FMS_acquireForm_batch; + memberFuncMap_[FORM_EVENT_REQ_CLEAR_FORM_BATCH] = &FormAbilityCommonA::FMS_deleteFormBatch; + SubscribeEvent(); +} + +void FormAbilityCommonA::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormEventSubscriberForCommonA::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriberForCommonA::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FormEventSubscriberForCommonA::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + if (eventName == FORM_EVENT_REQ_ONE_NORMAL_FORM && data.GetCode() == EVENT_CODE_100) { + return; + } + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriberForCommonA::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityCommonA) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonB/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4c105ec8a2370c521e7165ddaebbba161f6ad2e2 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemTestHostCommonBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemTestHostCommonB") { + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "../tool/src/form_test_utils.cpp", + "src/form_ability_commonb.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ + ":fmsSystemTestHostCommonBConfig", + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonB/config.json b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..052634ce88b35d009ce76b28ee08b91fddeebb44 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.commonb", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.commonb.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityCommonB", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonB/include/form_ability_commonb.h b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/include/form_ability_commonb.h new file mode 100644 index 0000000000000000000000000000000000000000..fcce3fb32c2b08b5b713291d9a74e970b629386d --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/include/form_ability_commonb.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_COMMONB_H_ +#define _FORM_ABILITY_COMMONB_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriberForCommonB; +class FormAbilityCommonB : public Ability { +public: + ~FormAbilityCommonB(); + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + void FMS_acquireForm(std::string data); + void FMS_deleteForm(std::string data); + void FMS_acquireForm_batch(std::string data); + void FMS_deleteFormBatch(std::string data); + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback() + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + using FormFunc = void (FormAbilityCommonB::*)(std::string data); + std::map memberFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriberForCommonB : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriberForCommonB(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriberForCommonB() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityCommonB *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_COMMONB_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonB/src/form_ability_commonb.cpp b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/src/form_ability_commonb.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a8add0eef427b284519aad229b43a92f5a42df13 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/src/form_ability_commonb.cpp @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_commonb.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "system_test_form_util.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +std::vector eventList = { + FORM_EVENT_REQ_ONE_NORMAL_FORM_B, + FORM_EVENT_REQ_ONE_NORMAL_FORM_B_DEL, + FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, + FORM_EVENT_REQ_CLEAR_FORM_BATCH +}; +void FormAbilityCommonB::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called[%{public}s]", __func__, std::to_string(formJsInfo.formId).c_str()); +} +void FormAbilityCommonB::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM_B, EVENT_CODE_100, std::to_string(formJsInfo.formId)); +} + +void FormAbilityCommonB::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +// Create one form(temp/normal) +void FormAbilityCommonB::FMS_acquireForm(std::string data) +{ + APP_LOGI("%{public}s called, data: %{public}s", __func__, data.c_str()); + std::shared_ptr callback = std::make_shared(); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + if (data == "true") { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + } else { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + } + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("[form_ability_commonB]AcquireForm end"); + } else { + APP_LOGE("[form_ability_commonB]AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM_B, EVENT_CODE_100, ""); + } +} +void FormAbilityCommonB::FMS_acquireForm_batch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "false"); + } +} +void FormAbilityCommonB::FMS_deleteFormBatch(std::string strFormId) +{ + APP_LOGI("%{public}s called", __func__); + int result = STtools::SystemTestFormUtil::ClearFormRecords(); + if (result == ERR_OK) { + APP_LOGI("Clear form records end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "true"); + } else { + APP_LOGE("Clear form records error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "false"); + } +} +void FormAbilityCommonB::FMS_deleteForm(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM_B_DEL, EVENT_CODE_101, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ONE_NORMAL_FORM_B_DEL, EVENT_CODE_101, "false"); + } +} +FormAbilityCommonB::~FormAbilityCommonB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} +void FormAbilityCommonB::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityCommonB::onStart"); + Ability::OnStart(want); +} +void FormAbilityCommonB::OnActive() +{ + APP_LOGI("FormAbilityCommonB::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityCommonB::OnStop() +{ + APP_LOGI("FormAbilityCommonB::OnStop"); + + Ability::OnStop(); +} +void FormAbilityCommonB::OnInactive() +{ + APP_LOGI("FormAbilityCommonB::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityCommonB::OnBackground() +{ + APP_LOGI("FormAbilityCommonB::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityCommonB::SubscribeEvent() +{ + APP_LOGI("FormAbilityCommonB::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityCommonB::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityCommonB::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_ONE_NORMAL_FORM_B] = &FormAbilityCommonB::FMS_acquireForm; + memberFuncMap_[FORM_EVENT_REQ_ONE_NORMAL_FORM_B_DEL] = &FormAbilityCommonB::FMS_deleteForm; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_BATCH] = &FormAbilityCommonB::FMS_acquireForm_batch; + memberFuncMap_[FORM_EVENT_REQ_CLEAR_FORM_BATCH] = &FormAbilityCommonB::FMS_deleteFormBatch; + SubscribeEvent(); +} + +void FormAbilityCommonB::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormEventSubscriberForCommonB::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriberForCommonB::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FormEventSubscriberForCommonB::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriberForCommonB::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityCommonB) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..be7b877759737abbcb7e44dabd93ebd0e207515d --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemTestHostNoPermConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemTestHostNoPerm") { + sources = [ + "../tool/src/form_test_utils.cpp", + "src/form_ability_no_perm.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":fmsSystemTestHostNoPermConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/config.json b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/config.json new file mode 100644 index 0000000000000000000000000000000000000000..662ab9e31ab7d97cb406562c00d676ce6a37229d --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/config.json @@ -0,0 +1,60 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.nopermission", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.nopermission.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityNoPerm", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/include/form_ability_no_perm.h b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/include/form_ability_no_perm.h new file mode 100644 index 0000000000000000000000000000000000000000..4e4fc48d4ba99c98f022733fd659fb47513026a1 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/include/form_ability_no_perm.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_NO_PERM_H_ +#define _FORM_ABILITY_NO_PERM_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriber; +class FormAbilityNoPerm : public Ability { +public: + void SubscribeEvent(const std::vector &eventList); + void handleEvent(std::string action); + + void FMS_acquireForm_0200(); + void FMS_deleteForm_0200(); + void FMS_releaseForm_0200(); + + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback(std::string name):caseName_(name) + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + + using FormFunc = void (FormAbilityNoPerm::*)(); + std::map memberFuncMap_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityNoPerm *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_NO_PERM_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/src/form_ability_no_perm.cpp b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/src/form_ability_no_perm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0bab3eab502c8f0f49b1e7f9eed6c9962b89dde --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNoPerm/src/form_ability_no_perm.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_no_perm.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +void FormAbilityNoPerm::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityNoPerm::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityNoPerm::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +void FormAbilityNoPerm::FMS_acquireForm_0200() +{ + std::shared_ptr callback = std::make_shared("FMS_acquireForm_0200"); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_0200, EVENT_CODE_200, "false"); + } +} + +void FormAbilityNoPerm::FMS_deleteForm_0200() +{ + int64_t formId = 1; + bool bResult = DeleteForm(formId); + if (bResult) { + APP_LOGI("[FMS_deleteForm_0200] end"); + } else { + APP_LOGE("[FMS_deleteForm_0200] error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0200, EVENT_CODE_200, "false"); + } +} + +void FormAbilityNoPerm::FMS_releaseForm_0200() +{ + int64_t formId = 1; + bool isReleaseCache = true; + bool bResult = ReleaseForm(formId, isReleaseCache); + if (bResult) { + APP_LOGI("[FMS_releaseForm_0200] end"); + } else { + APP_LOGE("[FMS_releaseForm_0200] error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0200, EVENT_CODE_200, "false"); + } +} + + +void FormAbilityNoPerm::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityNoPerm::onStart"); + Ability::OnStart(want); + + std::vector eventList = { + FORM_EVENT_REQ_ACQUIRE_FORM_0200, + FORM_EVENT_REQ_DELETE_FORM_0200, + FORM_EVENT_REQ_RELEASE_FORM_0200, + }; + SubscribeEvent(eventList); +} +void FormAbilityNoPerm::OnActive() +{ + APP_LOGI("FormAbilityNoPerm::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityNoPerm::OnStop() +{ + APP_LOGI("FormAbilityNoPerm::OnStop"); + + Ability::OnStop(); +} +void FormAbilityNoPerm::OnInactive() +{ + APP_LOGI("FormAbilityNoPerm::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityNoPerm::OnBackground() +{ + APP_LOGI("FormAbilityNoPerm::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityNoPerm::SubscribeEvent(const std::vector &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityNoPerm::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityNoPerm::Init"); + Ability::Init(abilityInfo, application, handler, token); + + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_0200] = &FormAbilityNoPerm::FMS_acquireForm_0200; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0200] = &FormAbilityNoPerm::FMS_deleteForm_0200; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0200] = &FormAbilityNoPerm::FMS_releaseForm_0200; +} + +void FormAbilityNoPerm::handleEvent(std::string action) +{ + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(); + } + } +} + +void FormAbilityNoPerm::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FormEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityNoPerm) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNormal/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..cc66a9564179b857bff0bc8726830559877ee22a --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemTestHostNormalConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemTestHostNormal") { + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "../tool/src/form_test_utils.cpp", + "src/form_ability_a.cpp", + "src/form_ability_deleteform.cpp", + "src/form_ability_releaseform.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ + ":fmsSystemTestHostNormalConfig", + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/config.json b/test/resource/formsystemtestability/fmsSystemTestHostNormal/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e3ec3c806ab171beda5cf2c4bc5bfdfe62792c54 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/config.json @@ -0,0 +1,122 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.normal", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.normal.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityA", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }, + { + "name": "FormAbilityDeleteForm", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }, + { + "name": "FormAbilityReleaseForm", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_a.h b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_a.h new file mode 100644 index 0000000000000000000000000000000000000000..66a648f87c8b61072681500a20abb1b46ff86b2a --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_a.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_A_H_ +#define _FORM_ABILITY_A_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriber; +class FormAbilityA : public Ability { +public: + ~FormAbilityA(); + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + + void FMS_deleteFormCommon(std::string strFormId); + + void FMS_acquireForm_0300(std::string data); + void FMS_acquireForm_0400(std::string data); + void FMS_acquireForm_0500(std::string data); + void FMS_acquireForm_0600(std::string data); + void FMS_acquireForm_0700(std::string data); + void FMS_acquireForm_1000(std::string data); + void FMS_acquireForm_1100(std::string data); + void FMS_acquireForm_1200(std::string data); + void FMS_acquireForm_1500_1(std::string data); + void FMS_acquireForm_1600(std::string data); + void FMS_acquireForm_1600_1(std::string data); + void FMS_acquireForm_1800(std::string data); + void FMS_acquireForm_1800_1(std::string data); + void FMS_acquireForm_1900(std::string data); + void FMS_acquireForm_2100(std::string data); + void FMS_acquireForm_2200(std::string data); + void FMS_acquireForm_2300(std::string data); + void FMS_acquireForm_2400(std::string data); + void FMS_acquireForm_2500(std::string data); + void FMS_acquireForm_2600(std::string data); + void FMS_acquireForm_2600_1(std::string data); + void FMS_acquireForm_2700(std::string data); + void FMS_acquireForm_2800(std::string data); + void FMS_acquireForm_2900(std::string data); + void FMS_acquireForm_2900_1(std::string data); + void FMS_acquireForm_3000(std::string data); + void FMS_acquireForm_3100(std::string data); + void FMS_acquireForm_3300(std::string data); + void FMS_acquireForm_3400(std::string data); + void FMS_acquireForm_3500(std::string data); + void FMS_acquireForm_tempForm(std::string data); + void FMS_acquireFormBatch(std::string data); + void FMS_acquireFormBatchB(std::string data); + void FMS_acquireFormTempBatch(std::string data); + void FMS_deleteFormBatch(std::string strFormId); + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback(std::string name, int code):caseName_(name), code_(code) + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_ = ""; + int code_ = 0; + FormAbilityA *ability_ = nullptr; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + + using FormFunc = void (FormAbilityA::*)(std::string data); + std::map memberFuncMap_; + std::map calledFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityA *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_A_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_deleteform.h b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_deleteform.h new file mode 100644 index 0000000000000000000000000000000000000000..19f53a8434869497dc775a3f390d27aa22f86274 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_deleteform.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_DELETEFORM_H_ +#define _FORM_ABILITY_DELETEFORM_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriberForDeleteForm; +class FormAbilityDeleteForm : public Ability { +public: + void SubscribeEvent(const std::vector &eventList); + void handleEvent(std::string action, std::string data); + void FMS_deleteForm_common(int64_t formId, std::string caseName); + void FMS_deleteForm_0300(std::string data); + void FMS_deleteForm_0400(std::string data); + void FMS_deleteForm_0500(std::string data); + void FMS_deleteForm_0600(std::string data); + void FMS_deleteForm_0700(std::string data); + void FMS_deleteForm_0800(std::string data); + void FMS_deleteForm_0900(std::string data); + void FMS_deleteForm_1000(std::string data); + void FMS_deleteForm_1100(std::string data); + void FMS_deleteForm_1200(std::string data); + void FMS_deleteForm_1201(std::string data); + void FMS_deleteForm_1400(std::string data); + void FMS_deleteForm_1401(std::string data); + void FMS_deleteForm_1500(std::string data); + void FMS_deleteForm_1501(std::string data); + void FMS_deleteForm_1502(std::string data); + void FMS_deleteForm_1600(std::string data); + void FMS_deleteForm_1601(std::string data); + void FMS_deleteForm_1602(std::string data); + void FMS_deleteForm_1700(std::string data); + void FMS_deleteForm_1701(std::string data); + void FMS_deleteForm_1702(std::string data); + void FMS_acquire_tempForm_batch(std::string data); + void FMS_acquireForm_batch(std::string data); + void FMS_deleteFormBatch(std::string data); + + std::shared_ptr subscriber_; + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback(std::string name):caseName_(name) + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + FormAbilityDeleteForm *ability_ = nullptr; + std::string caseName_; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(std::string case_id, int64_t form_id); + void DeleteForm_0300(int64_t form_id); + void DeleteForm_0400(int64_t form_id); + void DeleteForm_0500(int64_t form_id); + void DeleteForm_0600(int64_t form_id); + void DeleteForm_0700(int64_t form_id); + void DeleteForm_0800(int64_t form_id); + void DeleteForm_0900(int64_t form_id); + void DeleteForm_1000(int64_t form_id); + void DeleteForm_1100(int64_t form_id); + void DeleteForm_1200(int64_t form_id); + void DeleteForm_1400(int64_t form_id); + void DeleteForm_1500(int64_t form_id); + void DeleteForm_1501(int64_t form_id); + void DeleteForm_1600(int64_t form_id); + void DeleteForm_1601(int64_t form_id); + void DeleteForm_1700(int64_t form_id); + void DeleteForm_1701(int64_t form_id); + + using FormFunc = void (FormAbilityDeleteForm::*)(std::string data); + std::map memberFuncMap_; + std::shared_ptr callback_; +}; +class FormEventSubscriberForDeleteForm : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriberForDeleteForm(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriberForDeleteForm() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityDeleteForm *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_DELETEFORM_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_releaseform.h b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_releaseform.h new file mode 100644 index 0000000000000000000000000000000000000000..7bdbff428b2370a7f7f84fcc5760512eaab4a762 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_releaseform.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_RELEASEFORM_H_ +#define _FORM_ABILITY_RELEASEFORM_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriberForReleaseForm; +class FormAbilityReleaseForm : public Ability { +public: + void SubscribeEvent(const std::vector &eventList); + void handleEvent(std::string action, std::string data); + void FMS_releaseForm_common(int64_t formId, std::string caseName, std::string lastFormId); + void FMS_releaseForm_0300(std::string data); + void FMS_releaseForm_0400(std::string data); + void FMS_releaseForm_0500(std::string data); + void FMS_releaseForm_0600(std::string data); + void FMS_releaseForm_0700(std::string data); + void FMS_releaseForm_0800(std::string data); + void FMS_releaseForm_0900(std::string data); + void FMS_releaseForm_1000(std::string data); + void FMS_releaseForm_1100(std::string data); + void FMS_releaseForm_1200(std::string data); + void FMS_releaseForm_1300(std::string data); + void FMS_releaseForm_1400(std::string data); + void FMS_releaseForm_common_del(std::string data); + void Clear(std::string case_id, int64_t form_id); + + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback(std::string name, std::string id):caseName_(name), lastformId_(id) + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + FormAbilityReleaseForm *ability_ = nullptr; + std::string caseName_; + std::string lastformId_; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void ReleaseForm_0300(int64_t form_id); + void ReleaseForm_0400(int64_t form_id); + void ReleaseForm_0500(int64_t form_id); + void ReleaseForm_0600(int64_t form_id); + void ReleaseForm_0700(int64_t form_id); + void ReleaseForm_0800(int64_t form_id); + void ReleaseForm_0900(int64_t form_id); + void ReleaseForm_1000(int64_t form_id); + void ReleaseForm_1100(int64_t form_id); + void ReleaseForm_1200(int64_t form_id); + void ReleaseForm_1300(int64_t form_id, std::string lastFormId); + void ReleaseForm_1400(int64_t form_id); + + using FormFunc = void (FormAbilityReleaseForm::*)(std::string data); + std::map memberFuncMap_; + std::shared_ptr callback_; +}; +class FormEventSubscriberForReleaseForm : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriberForReleaseForm(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriberForReleaseForm() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityReleaseForm *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_RELEASEFORM_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_a.cpp b/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4349e0cb5a0b7c7bf729ce96378ce9217158086 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_a.cpp @@ -0,0 +1,904 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_a.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "system_test_form_util.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +std::vector eventList = { + FORM_EVENT_REQ_DELETE_FORM_COMMON, FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, + FORM_EVENT_REQ_ACQUIRE_FORM_0300, FORM_EVENT_REQ_ACQUIRE_FORM_0400, FORM_EVENT_REQ_ACQUIRE_FORM_0500, + FORM_EVENT_REQ_ACQUIRE_FORM_0600, FORM_EVENT_REQ_ACQUIRE_FORM_0700, FORM_EVENT_REQ_ACQUIRE_FORM_1000, + FORM_EVENT_REQ_ACQUIRE_FORM_1100, FORM_EVENT_REQ_ACQUIRE_FORM_1200, FORM_EVENT_REQ_ACQUIRE_FORM_1500_1, + FORM_EVENT_REQ_ACQUIRE_FORM_1600, FORM_EVENT_REQ_ACQUIRE_FORM_1600_1, FORM_EVENT_REQ_ACQUIRE_FORM_1800, + FORM_EVENT_REQ_ACQUIRE_FORM_1800_1, FORM_EVENT_REQ_ACQUIRE_FORM_1900, FORM_EVENT_REQ_ACQUIRE_FORM_2400, + FORM_EVENT_REQ_ACQUIRE_FORM_2100, FORM_EVENT_REQ_ACQUIRE_FORM_2200, FORM_EVENT_REQ_ACQUIRE_FORM_2300, + FORM_EVENT_REQ_ACQUIRE_FORM_2500, FORM_EVENT_REQ_ACQUIRE_FORM_2600, FORM_EVENT_REQ_ACQUIRE_FORM_2600_1, + FORM_EVENT_REQ_ACQUIRE_FORM_2700, FORM_EVENT_REQ_ACQUIRE_FORM_2800, FORM_EVENT_REQ_ACQUIRE_FORM_2900, + FORM_EVENT_REQ_ACQUIRE_FORM_2900_1, FORM_EVENT_REQ_ACQUIRE_FORM_3000, FORM_EVENT_REQ_ACQUIRE_FORM_3100, + FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH, FORM_EVENT_REQ_CLEAR_FORM_BATCH, + FORM_EVENT_REQ_ACQUIRE_FORM_BATCH_B, +}; +void FormAbilityA::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(this->caseName_, this->code_, std::to_string(formJsInfo.formId)); +} +void FormAbilityA::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(this->caseName_, this->code_ + 1, formJsInfo.formData); + + if (this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1200 + || this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1600 + || this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1600_1 + || this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1800 + || this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1800_1 + || this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1900) { + std::string strFormId = std::to_string(formJsInfo.formId); + APP_LOGI("%{public}s, delete form, formId: %{public}s", __func__, strFormId.c_str()); + ability_->FMS_deleteFormCommon(strFormId); + } +} + +void FormAbilityA::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityA::FMS_deleteFormCommon(std::string strFormId) +{ + APP_LOGI("%{public}s called, formId: %{public}s", __func__, strFormId.c_str()); + if (strFormId.empty()) { + APP_LOGE("DeleteForm error, formId is 0"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "false"); + return; + } + int64_t formId = std::stoll(strFormId); + sleep(1); + bool bResult = DeleteForm(formId); + sleep(1); + if (bResult) { + APP_LOGI("DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "true"); + } else { + APP_LOGE("DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "false"); + } +} + +void FormAbilityA::FMS_acquireForm_0300(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_0300, EVENT_CODE_300); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(-1, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_0300, EVENT_CODE_300, "false"); + } +} +void FormAbilityA::FMS_acquireForm_0400(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_0400, EVENT_CODE_400); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, "com.form.bundlename99", FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_0400, EVENT_CODE_400, "false"); + } +} +void FormAbilityA::FMS_acquireForm_0500(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_0500, EVENT_CODE_500); + // Set Want info begin + std::string moduleName = "moduleName99"; + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_0500, EVENT_CODE_500, "false"); + } +} +void FormAbilityA::FMS_acquireForm_0600(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_0600, EVENT_CODE_600); + // Set Want info begin + std::string formName = "formName999"; + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_0600, EVENT_CODE_600, "false"); + } +} +void FormAbilityA::FMS_acquireForm_0700(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_0700, EVENT_CODE_700); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, "abilityName9"); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_0700, EVENT_CODE_700, "false"); + } +} +void FormAbilityA::FMS_acquireForm_1000(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1000, EVENT_CODE_1000); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, 0); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1000, EVENT_CODE_1000, "false"); + } +} +void FormAbilityA::FMS_acquireForm_1100(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1100, EVENT_CODE_1100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1100, EVENT_CODE_1100, ""); + } +} +void FormAbilityA::FMS_acquireForm_1200(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1200, EVENT_CODE_1200); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME2); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME2); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME2, FORM_PROVIDER_ABILITY_NAME2); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1200, EVENT_CODE_1200, ""); + } +} + +void FormAbilityA::FMS_acquireForm_1500_1(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1500_1, EVENT_CODE_1510); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1500_1, EVENT_CODE_1510, ""); + } +} + +void FormAbilityA::FMS_acquireForm_1600(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1600, EVENT_CODE_1600); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1600, EVENT_CODE_1600, ""); + } +} +void FormAbilityA::FMS_acquireForm_1600_1(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1600_1, EVENT_CODE_1610); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1600_1, EVENT_CODE_1610, ""); + } +} +void FormAbilityA::FMS_acquireForm_1800(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1800, EVENT_CODE_1800); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1800, EVENT_CODE_1800, ""); + } +} +void FormAbilityA::FMS_acquireForm_1800_1(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1800_1, EVENT_CODE_1810); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1800_1, EVENT_CODE_1810, ""); + } +} +void FormAbilityA::FMS_acquireForm_1900(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1900, EVENT_CODE_1900); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1900, EVENT_CODE_1900, ""); + } +} +void FormAbilityA::FMS_acquireForm_2100(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2100, EVENT_CODE_2100); + callback->ability_ = this; + // Set Want info begin + int64_t formId = std::stoll(data); + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(formId, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2100, EVENT_CODE_2100, "false"); + } +} +void FormAbilityA::FMS_acquireForm_2200(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2200, EVENT_CODE_2200); + + // Set Want info end + bool bResult = CastTempForm(-1); + if (bResult) { + APP_LOGI("CastTempForm end"); + } else { + APP_LOGE("CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2200, EVENT_CODE_2200, "false"); + } +} +void FormAbilityA::FMS_acquireForm_2300(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2300, EVENT_CODE_2300); + + // Set Want info end + bool bResult = CastTempForm(0); + if (bResult) { + APP_LOGI("CastTempForm end"); + } else { + APP_LOGE("CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2300, EVENT_CODE_2300, "false"); + } +} +void FormAbilityA::FMS_acquireForm_2400(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2400, EVENT_CODE_2400); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2400, EVENT_CODE_2400, ""); + } +} + +void FormAbilityA::FMS_acquireForm_2500(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2500, EVENT_CODE_2500); + + // Set Want info end + bool bResult = CastTempForm(EVENT_CODE_1234); + if (bResult) { + APP_LOGI("CastTempForm end"); + } else { + APP_LOGE("CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2500, EVENT_CODE_2500, "false"); + } +} +void FormAbilityA::FMS_acquireForm_2600_1(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2600_1, EVENT_CODE_2610); + + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2600_1, EVENT_CODE_2610, ""); + } +} + +void FormAbilityA::FMS_acquireForm_2600(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2600, EVENT_CODE_2600); + callback->ability_ = this; + // Set Want info end + int64_t formId = std::stoll(data); + bool bResult = CastTempForm(formId); + if (bResult) { + APP_LOGI("CastTempForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2600, EVENT_CODE_2600, "true"); + } else { + APP_LOGE("CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2600, EVENT_CODE_2600, "false"); + } + + FMS_deleteFormCommon(data); +} + +void FormAbilityA::FMS_acquireForm_2700(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700); + + // Set Want info end + int64_t formId = std::stoll(data); + bool bResult = CastTempForm(formId); + if (bResult) { + APP_LOGI("CastTempForm end"); + } else { + APP_LOGE("CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700, "false"); + } + + FMS_deleteFormCommon(data); +} +void FormAbilityA::FMS_acquireForm_2800(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800); + + // Set Want info end + int64_t formId = std::stoll(data); + bool bResult = CastTempForm(formId); + if (bResult) { + APP_LOGI("CastTempForm end"); + } else { + APP_LOGE("CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800, "false"); + } + + FMS_deleteFormCommon(data); +} +void FormAbilityA::FMS_acquireForm_2900(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900, ""); + } +} + +void FormAbilityA::FMS_acquireForm_2900_1(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME2); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME2); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME2, FORM_PROVIDER_ABILITY_NAME2); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910, ""); + } +} +void FormAbilityA::FMS_acquireForm_3000(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000, "false"); + } +} +void FormAbilityA::FMS_acquireForm_3100(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100, ""); + } +} + +void FormAbilityA::FMS_acquireForm_3300(std::string data) +{ +} +void FormAbilityA::FMS_acquireForm_3400(std::string data) +{ +} +void FormAbilityA::FMS_acquireForm_3500(std::string data) +{ +} + +void FormAbilityA::FMS_acquireForm_tempForm(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); + + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, ""); + } +} +void FormAbilityA::FMS_acquireFormBatch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "false"); + } +} + +void FormAbilityA::FMS_acquireFormBatchB(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME2); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME2); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME2, FORM_PROVIDER_ABILITY_NAME2); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH_B, EVENT_CODE_BATCH_B, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH_B, EVENT_CODE_BATCH_B, "false"); + } +} +void FormAbilityA::FMS_acquireFormTempBatch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add temp form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "true"); + } else { + APP_LOGE("Batch add temp form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "false"); + } +} +void FormAbilityA::FMS_deleteFormBatch(std::string strFormId) +{ + APP_LOGI("%{public}s called", __func__); + int result = STtools::SystemTestFormUtil::ClearFormRecords(); + if (result == ERR_OK) { + APP_LOGI("Clear form records end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "true"); + } else { + APP_LOGE("Clear form records error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "false"); + } +} +FormAbilityA::~FormAbilityA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} +void FormAbilityA::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityA::onStart"); + Ability::OnStart(want); +} +void FormAbilityA::OnActive() +{ + APP_LOGI("FormAbilityA::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityA::OnStop() +{ + APP_LOGI("FormAbilityA::OnStop"); + + Ability::OnStop(); +} +void FormAbilityA::OnInactive() +{ + APP_LOGI("FormAbilityA::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityA::OnBackground() +{ + APP_LOGI("FormAbilityA::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityA::SubscribeEvent() +{ + APP_LOGI("FormAbilityA::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityA::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityA::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_0300] = &FormAbilityA::FMS_acquireForm_0300; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_0400] = &FormAbilityA::FMS_acquireForm_0400; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_0500] = &FormAbilityA::FMS_acquireForm_0500; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_0600] = &FormAbilityA::FMS_acquireForm_0600; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_0700] = &FormAbilityA::FMS_acquireForm_0700; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1000] = &FormAbilityA::FMS_acquireForm_1000; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1100] = &FormAbilityA::FMS_acquireForm_1100; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1200] = &FormAbilityA::FMS_acquireForm_1200; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1500_1] = &FormAbilityA::FMS_acquireForm_1500_1; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1600] = &FormAbilityA::FMS_acquireForm_1600; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1600_1] = &FormAbilityA::FMS_acquireForm_1600_1; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1800] = &FormAbilityA::FMS_acquireForm_1800; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1800_1] = &FormAbilityA::FMS_acquireForm_1800_1; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1900] = &FormAbilityA::FMS_acquireForm_1900; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2100] = &FormAbilityA::FMS_acquireForm_2100; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2200] = &FormAbilityA::FMS_acquireForm_2200; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2300] = &FormAbilityA::FMS_acquireForm_2300; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2400] = &FormAbilityA::FMS_acquireForm_2400; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2500] = &FormAbilityA::FMS_acquireForm_2500; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2600] = &FormAbilityA::FMS_acquireForm_2600; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2600_1] = &FormAbilityA::FMS_acquireForm_2600_1; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2700] = &FormAbilityA::FMS_acquireForm_2700; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2800] = &FormAbilityA::FMS_acquireForm_2800; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2900] = &FormAbilityA::FMS_acquireForm_2900; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2900_1] = &FormAbilityA::FMS_acquireForm_2900_1; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_3000] = &FormAbilityA::FMS_acquireForm_3000; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_3100] = &FormAbilityA::FMS_acquireForm_3100; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_COMMON] = &FormAbilityA::FMS_deleteFormCommon; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_TEMP] = &FormAbilityA::FMS_acquireForm_tempForm; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_BATCH] = &FormAbilityA::FMS_acquireFormBatch; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_BATCH_B] = &FormAbilityA::FMS_acquireFormBatchB; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH] = &FormAbilityA::FMS_acquireFormTempBatch; + memberFuncMap_[FORM_EVENT_REQ_CLEAR_FORM_BATCH] = &FormAbilityA::FMS_deleteFormBatch; + SubscribeEvent(); +} + +void FormAbilityA::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + if (calledFuncMap_.find(action) != calledFuncMap_.end()) { + return; + } + calledFuncMap_.emplace(action, 0); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilityA::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FormEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityA) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_deleteform.cpp b/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_deleteform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f50e5b4f7beab31ec5ff6fd7a7954f74d15af978 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_deleteform.cpp @@ -0,0 +1,905 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_deleteform.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "system_test_form_util.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +void FormAbilityDeleteForm::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s receive formId:%{public}s", __func__, std::to_string(formJsInfo.formId).c_str()); + if (this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_0600) { + ability_->FMS_deleteForm_common(formJsInfo.formId, this->caseName_); + } +} +void FormAbilityDeleteForm::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s receive formData:%{public}s", __func__, formJsInfo.formData.c_str()); + if (this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_0300 || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_0400 + || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_0700 || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_0800 + || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_0900 || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1000 + || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1100 || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1200 + || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1400 || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1500 + || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1501 || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1600 + || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1601 || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1700 + || this->caseName_ == FORM_EVENT_RECV_DELETE_FORM_1701) { + ability_->FMS_deleteForm_common(formJsInfo.formId, this->caseName_); + } +} + +void FormAbilityDeleteForm::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +void FormAbilityDeleteForm::FMS_deleteForm_common(int64_t formId, std::string caseName) +{ + APP_LOGI("%{public}s called, formId: %{public}s, caseName:%{public}s", + __func__, std::to_string(formId).c_str(), caseName.c_str()); + if (caseName == FORM_EVENT_RECV_DELETE_FORM_0300) { + DeleteForm_0300(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_0400) { + DeleteForm_0400(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_0600) { + DeleteForm_0600(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_0700) { + DeleteForm_0700(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_0800) { + DeleteForm_0800(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_0900) { + DeleteForm_0900(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1000) { + DeleteForm_1000(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1100) { + DeleteForm_1100(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1200) { + DeleteForm_1200(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1400) { + DeleteForm_1400(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1500) { + DeleteForm_1500(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1501) { + DeleteForm_1501(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1600) { + DeleteForm_1600(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1601) { + DeleteForm_1601(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1700) { + DeleteForm_1700(formId); + } else if (caseName == FORM_EVENT_RECV_DELETE_FORM_1701) { + DeleteForm_1701(formId); + } else { + return; + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_0300(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_0300); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0300, EVENT_CODE_300, ""); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_0400(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_0400); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0400, EVENT_CODE_400, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_0500(std::string data) +{ + APP_LOGI("%{public}s start[%{public}s]", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0500, EVENT_CODE_500, "true"); + } else { + APP_LOGE("%{public}s error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0500, EVENT_CODE_500, "false"); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_0600(std::string data) +{ + APP_LOGI("%{public}s start[%{public}s]", __func__, data.c_str()); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_0600); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(atoll(data.c_str()), want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0600, EVENT_CODE_600, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_0700(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_0700); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0700, EVENT_CODE_700, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_0800(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_0800); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0800, EVENT_CODE_800, ""); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_0900(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_0900); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0900, EVENT_CODE_900, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1000(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1000); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1000, EVENT_CODE_1000, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1100(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1100, EVENT_CODE_1100, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1200(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1200); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + if (data == "true") { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + } else { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + } + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1200, EVENT_CODE_1200, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1201(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1201, EVENT_CODE_1201, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1201, EVENT_CODE_1201, "false"); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1400(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1400); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + if (data == "true") { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + } else { + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + } + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1400, EVENT_CODE_1400, ""); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_1401(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1401, EVENT_CODE_1401, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1401, EVENT_CODE_1401, "false"); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1500(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1500); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1500, EVENT_CODE_1500, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1501(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1501); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1501, EVENT_CODE_1510, "acquireError"); + } + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1501, EVENT_CODE_1510, "deleteError"); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_1502(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1502, EVENT_CODE_1511, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1502, EVENT_CODE_1511, "false"); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_1600(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1600); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1600, EVENT_CODE_1600, ""); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_1601(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1601); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1601, EVENT_CODE_1610, "acquireError"); + } + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1601, EVENT_CODE_1610, "deleteError"); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_1602(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1602, EVENT_CODE_1611, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1602, EVENT_CODE_1611, "false"); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1700(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1700); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1700, EVENT_CODE_1700, ""); + } +} + +void FormAbilityDeleteForm::FMS_deleteForm_1701(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_DELETE_FORM_1701); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1701, EVENT_CODE_1701, "acquireError"); + } + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1701, EVENT_CODE_1701, "deleteError"); + } +} +void FormAbilityDeleteForm::FMS_deleteForm_1702(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1702, EVENT_CODE_1702, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1702, EVENT_CODE_1702, "false"); + } +} +void FormAbilityDeleteForm::FMS_acquire_tempForm_batch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "false"); + } +} +void FormAbilityDeleteForm::FMS_acquireForm_batch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "false"); + } +} +void FormAbilityDeleteForm::FMS_deleteFormBatch(std::string strFormId) +{ + APP_LOGI("%{public}s called", __func__); + int result = STtools::SystemTestFormUtil::ClearFormRecords(); + if (result == ERR_OK) { + APP_LOGI("Clear form records end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "true"); + } else { + APP_LOGE("Clear form records error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH, "false"); + } +} + +void FormAbilityDeleteForm::DeleteForm_0300(int64_t form_id) +{ + bool bResult = DeleteForm(-1); + Clear("FMS_deleteForm_0300", form_id); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0300, EVENT_CODE_300, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0300, EVENT_CODE_300, "false"); + } +} + +void FormAbilityDeleteForm::DeleteForm_0400(int64_t form_id) +{ + bool bResult = DeleteForm(0); + Clear("FMS_deleteForm_0400", form_id); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0400, EVENT_CODE_400, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0400, EVENT_CODE_400, "false"); + } +} + +void FormAbilityDeleteForm::DeleteForm_0500(int64_t form_id) +{} + +void FormAbilityDeleteForm::DeleteForm_0600(int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0600, EVENT_CODE_600, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0600, EVENT_CODE_600, "false"); + } +} + +void FormAbilityDeleteForm::DeleteForm_0700(int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0700, EVENT_CODE_700, std::to_string(form_id)); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0700, EVENT_CODE_700, "false"); + } +} + +void FormAbilityDeleteForm::DeleteForm_0800(int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0800, EVENT_CODE_800, std::to_string(form_id)); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0800, EVENT_CODE_800, "false"); + } +} + +void FormAbilityDeleteForm::DeleteForm_0900(int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + APP_LOGI("%{public}s DeleteForm1 end", __func__); + bool realResult = DeleteForm(form_id); + if (realResult) { + APP_LOGI("%{public}s DeleteForm2 end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0900, EVENT_CODE_900, "true"); + } else { + APP_LOGE("%{public}s DeleteForm2 error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0900, EVENT_CODE_900, "false"); + } + } else { + APP_LOGE("%{public}s DeleteForm1 error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0900, EVENT_CODE_900, ""); + } +} + +void FormAbilityDeleteForm::DeleteForm_1000(int64_t form_id) +{ + bool bResult = ReleaseForm(form_id); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + bool realResult = DeleteForm(form_id); + if (realResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1000, EVENT_CODE_1000, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1000, EVENT_CODE_1000, "false"); + } + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1000, EVENT_CODE_1000, ""); + } +} +void FormAbilityDeleteForm::DeleteForm_1100(int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1100, EVENT_CODE_1100, std::to_string(form_id)); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1100, EVENT_CODE_1100, "false"); + } +} +void FormAbilityDeleteForm::DeleteForm_1200(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1200, EVENT_CODE_1200, std::to_string(form_id)); +} +void FormAbilityDeleteForm::DeleteForm_1400(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1400, EVENT_CODE_1400, std::to_string(form_id)); +} +void FormAbilityDeleteForm::DeleteForm_1500(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1500, EVENT_CODE_1500, std::to_string(form_id)); +} +void FormAbilityDeleteForm::DeleteForm_1501(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1501, EVENT_CODE_1510, std::to_string(form_id)); +} +void FormAbilityDeleteForm::DeleteForm_1600(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1600, EVENT_CODE_1600, std::to_string(form_id)); +} +void FormAbilityDeleteForm::DeleteForm_1601(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1601, EVENT_CODE_1610, std::to_string(form_id)); +} +void FormAbilityDeleteForm::DeleteForm_1700(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1700, EVENT_CODE_1700, std::to_string(form_id)); +} +void FormAbilityDeleteForm::DeleteForm_1701(int64_t form_id) +{ + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_1701, EVENT_CODE_1701, std::to_string(form_id)); +} +void FormAbilityDeleteForm::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityDeleteForm::onStart"); + Ability::OnStart(want); + + std::vector eventList = { + FORM_EVENT_REQ_DELETE_FORM_0300, + FORM_EVENT_REQ_DELETE_FORM_0400, + FORM_EVENT_REQ_DELETE_FORM_0500, + FORM_EVENT_REQ_DELETE_FORM_0600, + FORM_EVENT_REQ_DELETE_FORM_0700, + FORM_EVENT_REQ_DELETE_FORM_0800, + FORM_EVENT_REQ_DELETE_FORM_0900, + FORM_EVENT_REQ_DELETE_FORM_1000, + FORM_EVENT_REQ_DELETE_FORM_1100, + FORM_EVENT_REQ_DELETE_FORM_1200, + FORM_EVENT_REQ_DELETE_FORM_1201, + FORM_EVENT_REQ_DELETE_FORM_1400, + FORM_EVENT_REQ_DELETE_FORM_1401, + FORM_EVENT_REQ_DELETE_FORM_1500, + FORM_EVENT_REQ_DELETE_FORM_1501, + FORM_EVENT_REQ_DELETE_FORM_1502, + FORM_EVENT_REQ_DELETE_FORM_1600, + FORM_EVENT_REQ_DELETE_FORM_1601, + FORM_EVENT_REQ_DELETE_FORM_1602, + FORM_EVENT_REQ_DELETE_FORM_1700, + FORM_EVENT_REQ_DELETE_FORM_1701, + FORM_EVENT_REQ_DELETE_FORM_1702, + FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, + FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH, + FORM_EVENT_REQ_CLEAR_FORM_BATCH + }; + SubscribeEvent(eventList); +} +void FormAbilityDeleteForm::OnActive() +{ + APP_LOGI("FormAbilityDeleteForm::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityDeleteForm::OnStop() +{ + APP_LOGI("FormAbilityDeleteForm::OnStop"); + + Ability::OnStop(); +} +void FormAbilityDeleteForm::OnInactive() +{ + APP_LOGI("FormAbilityDeleteForm::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityDeleteForm::OnBackground() +{ + APP_LOGI("FormAbilityDeleteForm::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityDeleteForm::SubscribeEvent(const std::vector &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityDeleteForm::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityDeleteForm::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0300] = &FormAbilityDeleteForm::FMS_deleteForm_0300; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0400] = &FormAbilityDeleteForm::FMS_deleteForm_0400; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0500] = &FormAbilityDeleteForm::FMS_deleteForm_0500; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0600] = &FormAbilityDeleteForm::FMS_deleteForm_0600; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0700] = &FormAbilityDeleteForm::FMS_deleteForm_0700; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0800] = &FormAbilityDeleteForm::FMS_deleteForm_0800; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0900] = &FormAbilityDeleteForm::FMS_deleteForm_0900; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1000] = &FormAbilityDeleteForm::FMS_deleteForm_1000; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1100] = &FormAbilityDeleteForm::FMS_deleteForm_1100; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1200] = &FormAbilityDeleteForm::FMS_deleteForm_1200; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1201] = &FormAbilityDeleteForm::FMS_deleteForm_1201; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1400] = &FormAbilityDeleteForm::FMS_deleteForm_1400; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1401] = &FormAbilityDeleteForm::FMS_deleteForm_1401; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1500] = &FormAbilityDeleteForm::FMS_deleteForm_1500; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1501] = &FormAbilityDeleteForm::FMS_deleteForm_1501; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1502] = &FormAbilityDeleteForm::FMS_deleteForm_1502; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1600] = &FormAbilityDeleteForm::FMS_deleteForm_1600; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1601] = &FormAbilityDeleteForm::FMS_deleteForm_1601; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1602] = &FormAbilityDeleteForm::FMS_deleteForm_1602; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1700] = &FormAbilityDeleteForm::FMS_deleteForm_1700; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1701] = &FormAbilityDeleteForm::FMS_deleteForm_1701; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_1702] = &FormAbilityDeleteForm::FMS_deleteForm_1702; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_BATCH] = &FormAbilityDeleteForm::FMS_acquireForm_batch; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH] = &FormAbilityDeleteForm::FMS_acquire_tempForm_batch; + memberFuncMap_[FORM_EVENT_REQ_CLEAR_FORM_BATCH] = &FormAbilityDeleteForm::FMS_deleteFormBatch; +} + +void FormAbilityDeleteForm::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilityDeleteForm::Clear(std::string case_id, int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + APP_LOGI("[%{public}s] clear ok", case_id.c_str()); + } else { + APP_LOGE("[%{public}s] clear error", case_id.c_str()); + } +} + +void FormEventSubscriberForDeleteForm::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriberForDeleteForm::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FormEventSubscriberForDeleteForm::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriberForDeleteForm::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityDeleteForm) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_releaseform.cpp b/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_releaseform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d2cdb7044b5a946cb38ef19363954b39ac0dd6e --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/src/form_ability_releaseform.cpp @@ -0,0 +1,636 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_releaseform.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +void FormAbilityReleaseForm::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s receive formId:%{public}s", __func__, std::to_string(formJsInfo.formId).c_str()); + if (this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_0700 || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_1000) { + ability_->FMS_releaseForm_common(formJsInfo.formId, this->caseName_, this->lastformId_); + } +} +void FormAbilityReleaseForm::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s receive formData:%{public}s", __func__, formJsInfo.formData.c_str()); + if (this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_0300 || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_0400 + || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_0600 || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_0800 + || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_0900 || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_1100 + || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_1200 || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_1300 + || this->caseName_ == FORM_EVENT_RECV_RELEASE_FORM_1400) { + ability_->FMS_releaseForm_common(formJsInfo.formId, this->caseName_, this->lastformId_); + } +} + +void FormAbilityReleaseForm::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +void FormAbilityReleaseForm::FMS_releaseForm_common(int64_t formId, std::string caseName, std::string lastFormId) +{ + APP_LOGI("%{public}s called, formId: %{public}s, caseName:%{public}s, lastFormId:%{public}s", + __func__, std::to_string(formId).c_str(), caseName.c_str(), lastFormId.c_str()); + if (caseName == FORM_EVENT_RECV_RELEASE_FORM_0300) { + ReleaseForm_0300(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_0400) { + ReleaseForm_0400(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_0600) { + ReleaseForm_0600(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_0700) { + ReleaseForm_0700(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_0800) { + ReleaseForm_0800(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_0900) { + ReleaseForm_0900(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_1000) { + ReleaseForm_1000(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_1100) { + ReleaseForm_1100(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_1200) { + ReleaseForm_1200(formId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_1300) { + ReleaseForm_1300(formId, lastFormId); + } else if (caseName == FORM_EVENT_RECV_RELEASE_FORM_1400) { + ReleaseForm_1400(formId); + } else { + return; + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_0300(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_0300, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0300, EVENT_CODE_300, ""); + } +} +void FormAbilityReleaseForm::FMS_releaseForm_0400(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_0400, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0400, EVENT_CODE_400, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_0500(std::string data) +{ + APP_LOGI("%{public}s start[%{public}s]", __func__, data.c_str()); + bool bResult = ReleaseForm(atoll(data.c_str()), true); + if (bResult) { + APP_LOGI("%{public}s end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0500, EVENT_CODE_500, "true"); + } else { + APP_LOGE("%{public}s error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0500, EVENT_CODE_500, "false"); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_0600(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_0600, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0600, EVENT_CODE_600, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_0700(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_0700, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(atoll(data.c_str()), want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0700, EVENT_CODE_700, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_0800(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_0800, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0800, EVENT_CODE_800, ""); + } +} +void FormAbilityReleaseForm::FMS_releaseForm_0900(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_0900, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0900, EVENT_CODE_900, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_1000(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_1000, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(atoll(data.c_str()), want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1000, EVENT_CODE_1000, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_1100(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_1100, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1100, EVENT_CODE_1100, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_1200(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_1200, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1200, EVENT_CODE_1200, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_1300(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_1300, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300, ""); + } +} + +void FormAbilityReleaseForm::FMS_releaseForm_1400(std::string data) +{ + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_RELEASE_FORM_1400, data); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("%{public}s AcquireForm ok.", __func__); + } else { + APP_LOGE("%{public}s AcquireForm error.", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1400, EVENT_CODE_1400, ""); + } +} +void FormAbilityReleaseForm::FMS_releaseForm_common_del(std::string data) +{ + APP_LOGI("%{public}s formId: %{public}s", __func__, data.c_str()); + bool bResult = DeleteForm(atoll(data.c_str())); + if (bResult) { + APP_LOGI("%{public}s DeleteForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, "true"); + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, "false"); + } +} + +void FormAbilityReleaseForm::ReleaseForm_0300(int64_t form_id) +{ + int64_t formId = -1; + bool isReleaseCache = true; + bool bResult = ReleaseForm(formId, isReleaseCache); + Clear("FMS_releaseForm_0300", form_id); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0300, EVENT_CODE_300, "true"); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0300, EVENT_CODE_300, "false"); + } +} + +void FormAbilityReleaseForm::ReleaseForm_0400(int64_t form_id) +{ + int64_t formId = 0; + bool isReleaseCache = true; + bool bResult = ReleaseForm(formId, isReleaseCache); + Clear("FMS_releaseForm_0400", form_id); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0400, EVENT_CODE_400, "true"); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0400, EVENT_CODE_400, "false"); + } +} + +void FormAbilityReleaseForm::ReleaseForm_0500(int64_t form_id) +{} + +void FormAbilityReleaseForm::ReleaseForm_0600(int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + bool isReleaseCache = true; + bool realResult = ReleaseForm(form_id, isReleaseCache); + if (realResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0600, EVENT_CODE_600, "true"); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0600, EVENT_CODE_600, "false"); + } + } else { + APP_LOGE("%{public}s DeleteForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0600, EVENT_CODE_600, ""); + } +} + +void FormAbilityReleaseForm::ReleaseForm_0700(int64_t form_id) +{ + bool isReleaseCache = false; + bool bResult = ReleaseForm(form_id, isReleaseCache); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0700, EVENT_CODE_700, "true"); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0700, EVENT_CODE_700, "false"); + } +} +void FormAbilityReleaseForm::ReleaseForm_0800(int64_t form_id) +{ + bool isReleaseCache = false; + bool bResult = ReleaseForm(form_id, isReleaseCache); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0800, EVENT_CODE_800, std::to_string(form_id)); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0800, EVENT_CODE_800, "false"); + } +} +void FormAbilityReleaseForm::ReleaseForm_0900(int64_t form_id) +{ + bool isReleaseCache = false; + bool bResult = ReleaseForm(form_id, isReleaseCache); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0900, EVENT_CODE_900, std::to_string(form_id)); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0900, EVENT_CODE_900, "false"); + } +} +void FormAbilityReleaseForm::ReleaseForm_1000(int64_t form_id) +{ + bool isReleaseCache = true; + bool bResult = ReleaseForm(form_id, isReleaseCache); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1000, EVENT_CODE_1000, "true"); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1000, EVENT_CODE_1000, "false"); + } +} +void FormAbilityReleaseForm::ReleaseForm_1100(int64_t form_id) +{ + bool isReleaseCache = true; + bool bResult = ReleaseForm(form_id, isReleaseCache); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1100, EVENT_CODE_1100, std::to_string(form_id)); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1100, EVENT_CODE_1100, "false"); + } +} +void FormAbilityReleaseForm::ReleaseForm_1200(int64_t form_id) +{ + bool isReleaseCache = true; + bool bResult = ReleaseForm(form_id, isReleaseCache); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1200, EVENT_CODE_1200, std::to_string(form_id)); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1200, EVENT_CODE_1200, "false"); + } +} +void FormAbilityReleaseForm::ReleaseForm_1300(int64_t form_id, std::string lastFormId) +{ + if (lastFormId == "") { + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300, std::to_string(form_id)); + } else { + bool isReleaseCache = true; + bool bResult1 = ReleaseForm(form_id, isReleaseCache); + bool bResult2 = ReleaseForm(atoll(lastFormId.c_str()), isReleaseCache); + Clear("FMS_releaseForm_1300", form_id); + Clear("FMS_releaseForm_1300", atoll(lastFormId.c_str())); + if (bResult1 && bResult2) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300, "true"); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300, "false"); + } + } +} +void FormAbilityReleaseForm::ReleaseForm_1400(int64_t form_id) +{ + bool isReleaseCache = true; + bool bResult = ReleaseForm(form_id, isReleaseCache); + Clear("FMS_releaseForm_1400", form_id); + if (bResult) { + APP_LOGI("%{public}s ReleaseForm end", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1400, EVENT_CODE_1400, "true"); + } else { + APP_LOGE("%{public}s ReleaseForm error", __func__); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_1400, EVENT_CODE_1400, "false"); + } +} + +void FormAbilityReleaseForm::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityReleaseForm::onStart"); + Ability::OnStart(want); + + std::vector eventList = { + FORM_EVENT_REQ_RELEASE_FORM_0300, + FORM_EVENT_REQ_RELEASE_FORM_0400, + FORM_EVENT_REQ_RELEASE_FORM_0500, + FORM_EVENT_REQ_RELEASE_FORM_0600, + FORM_EVENT_REQ_RELEASE_FORM_0700, + FORM_EVENT_REQ_RELEASE_FORM_0800, + FORM_EVENT_REQ_RELEASE_FORM_0900, + FORM_EVENT_REQ_RELEASE_FORM_1000, + FORM_EVENT_REQ_RELEASE_FORM_1100, + FORM_EVENT_REQ_RELEASE_FORM_1200, + FORM_EVENT_REQ_RELEASE_FORM_1300, + FORM_EVENT_REQ_RELEASE_FORM_1400, + FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL + }; + SubscribeEvent(eventList); +} +void FormAbilityReleaseForm::OnActive() +{ + APP_LOGI("FormAbilityReleaseForm::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityReleaseForm::OnStop() +{ + APP_LOGI("FormAbilityReleaseForm::OnStop"); + + Ability::OnStop(); +} +void FormAbilityReleaseForm::OnInactive() +{ + APP_LOGI("FormAbilityReleaseForm::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityReleaseForm::OnBackground() +{ + APP_LOGI("FormAbilityReleaseForm::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityReleaseForm::SubscribeEvent(const std::vector &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityReleaseForm::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityReleaseForm::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0300] = &FormAbilityReleaseForm::FMS_releaseForm_0300; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0400] = &FormAbilityReleaseForm::FMS_releaseForm_0400; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0500] = &FormAbilityReleaseForm::FMS_releaseForm_0500; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0600] = &FormAbilityReleaseForm::FMS_releaseForm_0600; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0700] = &FormAbilityReleaseForm::FMS_releaseForm_0700; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0800] = &FormAbilityReleaseForm::FMS_releaseForm_0800; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0900] = &FormAbilityReleaseForm::FMS_releaseForm_0900; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_1000] = &FormAbilityReleaseForm::FMS_releaseForm_1000; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_1100] = &FormAbilityReleaseForm::FMS_releaseForm_1100; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_1200] = &FormAbilityReleaseForm::FMS_releaseForm_1200; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_1300] = &FormAbilityReleaseForm::FMS_releaseForm_1300; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_1400] = &FormAbilityReleaseForm::FMS_releaseForm_1400; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL] = &FormAbilityReleaseForm::FMS_releaseForm_common_del; +} + +void FormAbilityReleaseForm::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilityReleaseForm::Clear(std::string case_id, int64_t form_id) +{ + bool bResult = DeleteForm(form_id); + if (bResult) { + APP_LOGI("[%{public}s] clear ok", case_id.c_str()); + } else { + APP_LOGE("[%{public}s] clear error", case_id.c_str()); + } +} + +void FormEventSubscriberForReleaseForm::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriberForReleaseForm::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FormEventSubscriberForReleaseForm::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + if ((data.GetCode() == EVENT_CODE_1300 && data.GetData() == "") || + eventName == FORM_EVENT_REQ_RELEASE_FORM_0700 || eventName == FORM_EVENT_REQ_RELEASE_FORM_0800 || + eventName == FORM_EVENT_REQ_RELEASE_FORM_0900 || eventName == FORM_EVENT_REQ_RELEASE_FORM_1000 || + eventName == FORM_EVENT_REQ_RELEASE_FORM_1100 || eventName == FORM_EVENT_REQ_RELEASE_FORM_1200) { + return; + } else { + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); + } +} + +void FormEventSubscriberForReleaseForm::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityReleaseForm) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..91ecd814dfaf231fca5344d269aa68e33fd8496a --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemTestHostNormalBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemTestHostNormalB") { + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "../tool/src/form_test_utils.cpp", + "src/form_ability_b.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ + ":fmsSystemTestHostNormalBConfig", + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/config.json b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5102f274b673e399a14ce84448f37fbf0c07b28d --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.normalb", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.normalb.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbilityB", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityB", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability B", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/include/form_ability_b.h b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/include/form_ability_b.h new file mode 100644 index 0000000000000000000000000000000000000000..5edd87f78d22e8700afb23c0cdffe76913013b33 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/include/form_ability_b.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_B_H_ +#define _FORM_ABILITY_B_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriber; +class FormAbilityB : public Ability { +public: + ~FormAbilityB(); + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + + void FMS_deleteFormCommon(std::string strFormId); + + void FMS_acquireForm_1400(std::string data); + void FMS_acquireForm_1500(std::string data); + void FMS_acquireForm_1800_2(std::string data); + void FMS_acquireForm_1800_3(std::string data); + void FMS_acquireForm_2400_1(std::string data); + void FMS_acquireForm_3100(std::string data); + void FMS_acquireForm_tempForm(std::string data); + void FMS_acquireFormBatch(std::string data); + void FMS_acquireFormTempBatch(std::string data); + + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback(std::string name, int code):caseName_(name), code_(code) + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_ = ""; + int code_ = 0; + FormAbilityB *ability_ = nullptr; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + + using FormFunc = void (FormAbilityB::*)(std::string data); + std::map memberFuncMap_; + std::map calledFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityB *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_B_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/src/form_ability_b.cpp b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/src/form_ability_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..437923559ae01683daf2901af227fc309b4ef3f1 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/src/form_ability_b.cpp @@ -0,0 +1,392 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_b.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "system_test_form_util.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +std::vector eventList = { + FORM_EVENT_REQ_DELETE_FORM_COMMON, FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, FORM_EVENT_REQ_ACQUIRE_FORM_1400, + FORM_EVENT_REQ_ACQUIRE_FORM_1500, FORM_EVENT_REQ_ACQUIRE_FORM_1800_2, FORM_EVENT_REQ_ACQUIRE_FORM_1800_3, + FORM_EVENT_REQ_ACQUIRE_FORM_2400_1, FORM_EVENT_REQ_ACQUIRE_FORM_3100, FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, + FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH, +}; +void FormAbilityB::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(this->caseName_, this->code_, std::to_string(formJsInfo.formId)); + if (this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1500) { + std::string strFormId = std::to_string(formJsInfo.formId); + APP_LOGI("%{public}s, delete form, formId: %{public}s", __func__, strFormId.c_str()); + ability_->FMS_deleteFormCommon(strFormId); + } +} +void FormAbilityB::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(this->caseName_, this->code_ + 1, formJsInfo.formData); + if (this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1800_2 || + this->caseName_ == FORM_EVENT_RECV_ACQUIRE_FORM_1800_3) { + std::string strFormId = std::to_string(formJsInfo.formId); + APP_LOGI("%{public}s, delete form, formId: %{public}s", __func__, strFormId.c_str()); + ability_->FMS_deleteFormCommon(strFormId); + } +} + +void FormAbilityB::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityB::FMS_deleteFormCommon(std::string strFormId) +{ + APP_LOGI("%{public}s called, formId: %{public}s", __func__, strFormId.c_str()); + if (strFormId.empty()) { + APP_LOGE("DeleteForm error, formId is 0"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "false"); + return; + } + int64_t formId = std::stoll(strFormId); + sleep(1); + bool bResult = DeleteForm(formId); + sleep(1); + if (bResult) { + APP_LOGI("DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "true"); + } else { + APP_LOGE("DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "false"); + } +} + +void FormAbilityB::FMS_acquireForm_1400(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1400, EVENT_CODE_1400); + // Set Want info begin + std::string formName = "formName999"; + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + int64_t formId = std::stoll(data); + bool bResult = AcquireForm(formId, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1400, EVENT_CODE_1400, "false"); + } +} +void FormAbilityB::FMS_acquireForm_1500(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1500, EVENT_CODE_1500); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + int64_t formId = std::stoll(data); + bool bResult = AcquireForm(formId, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1500, EVENT_CODE_1500, ""); + } +} + +void FormAbilityB::FMS_acquireForm_1800_2(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1800_2, EVENT_CODE_1820); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1800_2, EVENT_CODE_1820, ""); + } +} +void FormAbilityB::FMS_acquireForm_1800_3(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_1800_3, EVENT_CODE_1830); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_1800_3, EVENT_CODE_1830, ""); + } +} + +void FormAbilityB::FMS_acquireForm_2400_1(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_2400_1, EVENT_CODE_2410); + callback->ability_ = this; + // Set Want info end + int64_t formId = std::stoll(data); + bool bResult = CastTempForm(formId); + if (bResult) { + APP_LOGI("CastTempForm end"); + } else { + APP_LOGE("CastTempForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_2400_1, EVENT_CODE_2410, "false"); + } +} +void FormAbilityB::FMS_acquireForm_3100(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100, ""); + } +} +void FormAbilityB::FMS_acquireForm_tempForm(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); + + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, ""); + } +} + +void FormAbilityB::FMS_acquireFormBatch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "false"); + } +} + +void FormAbilityB::FMS_acquireFormTempBatch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add temp form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "true"); + } else { + APP_LOGE("Batch add temp form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "false"); + } +} +FormAbilityB::~FormAbilityB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} +void FormAbilityB::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityB::onStart"); + Ability::OnStart(want); +} +void FormAbilityB::OnActive() +{ + APP_LOGI("FormAbilityB::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityB::OnStop() +{ + APP_LOGI("FormAbilityB::OnStop"); + + Ability::OnStop(); +} +void FormAbilityB::OnInactive() +{ + APP_LOGI("FormAbilityB::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityB::OnBackground() +{ + APP_LOGI("FormAbilityB::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityB::SubscribeEvent() +{ + APP_LOGI("FormAbilityB::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityB::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityB::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_COMMON] = &FormAbilityB::FMS_deleteFormCommon; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_TEMP] = &FormAbilityB::FMS_acquireForm_tempForm; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_BATCH] = &FormAbilityB::FMS_acquireFormBatch; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH] = &FormAbilityB::FMS_acquireFormTempBatch; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1400] = &FormAbilityB::FMS_acquireForm_1400; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1500] = &FormAbilityB::FMS_acquireForm_1500; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1800_2] = &FormAbilityB::FMS_acquireForm_1800_2; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_1800_3] = &FormAbilityB::FMS_acquireForm_1800_3; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_2400_1] = &FormAbilityB::FMS_acquireForm_2400_1; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_3100] = &FormAbilityB::FMS_acquireForm_3100; + SubscribeEvent(); +} + +void FormAbilityB::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + if (calledFuncMap_.find(action) != calledFuncMap_.end()) { + return; + } + calledFuncMap_.emplace(action, 0); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilityB::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FormEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityB) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..c19ced112dc1f02bccb7e7a354b770294b846bfa --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemTestHostNormalCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemTestHostNormalC") { + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "../tool/src/form_test_utils.cpp", + "src/form_ability_c.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ + ":fmsSystemTestHostNormalCConfig", + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/config.json b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d86af9a1859066b14d2118d6cfbc9044939e1c6a --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.normalc", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.normalc.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbilityC", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityC", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability B", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/include/form_ability_c.h b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/include/form_ability_c.h new file mode 100644 index 0000000000000000000000000000000000000000..8fb20dcef4cc5b495dd3167581ff935a8425b59c --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/include/form_ability_c.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_C_H_ +#define _FORM_ABILITY_C_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriber; +class FormAbilityC : public Ability { +public: + ~FormAbilityC(); + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + + void FMS_deleteFormCommon(std::string strFormId); + + void FMS_acquireForm_3100(std::string data); + void FMS_acquireForm_3200(std::string data); + + void FMS_acquireFormBatch(std::string data); + void FMS_acquireFormTempBatch(std::string data); + + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback(std::string name, int code):caseName_(name), code_(code) + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_ = ""; + int code_ = 0; + FormAbilityC *ability_ = nullptr; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + + using FormFunc = void (FormAbilityC::*)(std::string data); + std::map memberFuncMap_; + std::map calledFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityC *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_C_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/src/form_ability_c.cpp b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/src/form_ability_c.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dad17b4b4b0facf359e444f27dd8498b1b4d3003 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/src/form_ability_c.cpp @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_c.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" +#include "system_test_form_util.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +std::vector eventList = { + FORM_EVENT_REQ_DELETE_FORM_COMMON, FORM_EVENT_REQ_ACQUIRE_FORM_3100, FORM_EVENT_REQ_ACQUIRE_FORM_3200, + FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH, +}; +void FormAbilityC::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(this->caseName_, this->code_, std::to_string(formJsInfo.formId)); +} +void FormAbilityC::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + FormTestUtils::PublishEvent(this->caseName_, this->code_ + 1, formJsInfo.formData); +} + +void FormAbilityC::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityC::FMS_deleteFormCommon(std::string strFormId) +{ + APP_LOGI("%{public}s called, formId: %{public}s", __func__, strFormId.c_str()); + if (strFormId.empty()) { + APP_LOGE("DeleteForm error, formId is 0"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "false"); + return; + } + int64_t formId = std::stoll(strFormId); + sleep(1); + bool bResult = DeleteForm(formId); + sleep(1); + if (bResult) { + APP_LOGI("DeleteForm end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "true"); + } else { + APP_LOGE("DeleteForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999, "false"); + } +} + +void FormAbilityC::FMS_acquireForm_3100(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100, ""); + } +} + +void FormAbilityC::FMS_acquireForm_3200(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200); + callback->ability_ = this; + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200, "false"); + } +} +void FormAbilityC::FMS_acquireFormBatch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "true"); + } else { + APP_LOGE("Batch add form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, "false"); + } +} + +void FormAbilityC::FMS_acquireFormTempBatch(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + + int formCount = std::stoi(data); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, formCount); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, formCount); + // Set Want info end + int result = STtools::SystemTestFormUtil::BatchAddFormRecords(want); + if (result == ERR_OK) { + APP_LOGI("Batch add temp form end"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "true"); + } else { + APP_LOGE("Batch add temp form error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, "false"); + } +} +FormAbilityC::~FormAbilityC() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} +void FormAbilityC::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityC::onStart"); + Ability::OnStart(want); +} +void FormAbilityC::OnActive() +{ + APP_LOGI("FormAbilityC::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityC::OnStop() +{ + APP_LOGI("FormAbilityC::OnStop"); + + Ability::OnStop(); +} +void FormAbilityC::OnInactive() +{ + APP_LOGI("FormAbilityC::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityC::OnBackground() +{ + APP_LOGI("FormAbilityC::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityC::SubscribeEvent() +{ + APP_LOGI("FormAbilityC::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityC::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityC::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_COMMON] = &FormAbilityC::FMS_deleteFormCommon; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_BATCH] = &FormAbilityC::FMS_acquireFormBatch; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH] = &FormAbilityC::FMS_acquireFormTempBatch; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_3100] = &FormAbilityC::FMS_acquireForm_3100; + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_3200] = &FormAbilityC::FMS_acquireForm_3200; + + SubscribeEvent(); +} + +void FormAbilityC::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + if (calledFuncMap_.find(action) != calledFuncMap_.end()) { + return; + } + calledFuncMap_.emplace(action, 0); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilityC::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FormEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityC) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNotSys/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..9e6ddf55f67ba482cfa6f2a9dc3632f8e535a6ab --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("fmsSystemTestHostNotSysConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("fmsSystemTestHostNotSys") { + sources = [ + "../tool/src/form_test_utils.cpp", + "src/form_ability_not_sys.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":fmsSystemTestHostNotSysConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNotSys/config.json b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8adf4d53ac924686e83606c3a07d9a09a61ec289 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.notsystemapp", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.notsystemapp.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilityNotSys", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNotSys/include/form_ability_not_sys.h b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/include/form_ability_not_sys.h new file mode 100644 index 0000000000000000000000000000000000000000..8e5eb6467e0b8af8f9e857d083b91a35409810e5 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/include/form_ability_not_sys.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_NOT_SYS_H_ +#define _FORM_ABILITY_NOT_SYS_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriber; +class FormAbilityNotSys : public Ability { +public: + void SubscribeEvent(const std::vector &eventList); + void handleEvent(std::string action); + + void FMS_acquireForm_0100(); + void FMS_deleteForm_0100(); + void FMS_releaseForm_0100(); + + std::shared_ptr subscriber_; + + class AcquireFormCallback : public FormCallback { + public: + AcquireFormCallback(std::string name):caseName_(name) + { + } + virtual ~AcquireFormCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + + using FormFunc = void (FormAbilityNotSys::*)(); + std::map memberFuncMap_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilityNotSys *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_NOT_SYS_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNotSys/src/form_ability_not_sys.cpp b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/src/form_ability_not_sys.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef06ae7609054797765bc020b5a48d460a2bdea4 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/src/form_ability_not_sys.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_not_sys.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +void FormAbilityNotSys::AcquireFormCallback::OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityNotSys::AcquireFormCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityNotSys::AcquireFormCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilityNotSys::FMS_acquireForm_0100() +{ + std::shared_ptr callback = std::make_shared("FMS_acquireForm_0100"); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_ACQUIRE_FORM_0100, EVENT_CODE_100, "false"); + } +} + +void FormAbilityNotSys::FMS_deleteForm_0100() +{ + int64_t formId = 1; + bool bResult = DeleteForm(formId); + if (bResult) { + APP_LOGI("[FMS_deleteForm_0100] end"); + } else { + APP_LOGE("[FMS_deleteForm_0100] error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_DELETE_FORM_0100, EVENT_CODE_100, "false"); + } +} + +void FormAbilityNotSys::FMS_releaseForm_0100() +{ + int64_t formId = 1; + bool isReleaseCache = true; + bool bResult = ReleaseForm(formId, isReleaseCache); + if (bResult) { + APP_LOGI("[FMS_releaseForm_0100] end"); + } else { + APP_LOGE("[FMS_releaseForm_0100] error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_RELEASE_FORM_0100, EVENT_CODE_100, "false"); + } +} + +void FormAbilityNotSys::OnStart(const Want &want) +{ + APP_LOGI("FormAbilityNotSys::onStart"); + Ability::OnStart(want); + + std::vector eventList = { + FORM_EVENT_REQ_ACQUIRE_FORM_0100, + FORM_EVENT_REQ_DELETE_FORM_0100, + FORM_EVENT_REQ_RELEASE_FORM_0100, + }; + SubscribeEvent(eventList); +} +void FormAbilityNotSys::OnActive() +{ + APP_LOGI("FormAbilityNotSys::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilityNotSys::OnStop() +{ + APP_LOGI("FormAbilityNotSys::OnStop"); + + Ability::OnStop(); +} +void FormAbilityNotSys::OnInactive() +{ + APP_LOGI("FormAbilityNotSys::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilityNotSys::OnBackground() +{ + APP_LOGI("FormAbilityNotSys::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilityNotSys::SubscribeEvent(const std::vector &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilityNotSys::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilityNotSys::Init"); + Ability::Init(abilityInfo, application, handler, token); + + memberFuncMap_[FORM_EVENT_REQ_ACQUIRE_FORM_0100] = &FormAbilityNotSys::FMS_acquireForm_0100; + memberFuncMap_[FORM_EVENT_REQ_DELETE_FORM_0100] = &FormAbilityNotSys::FMS_deleteForm_0100; + memberFuncMap_[FORM_EVENT_REQ_RELEASE_FORM_0100] = &FormAbilityNotSys::FMS_releaseForm_0100; +} + +void FormAbilityNotSys::handleEvent(std::string action) +{ + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(); + } + } +} + +void FormAbilityNotSys::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FormEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilityNotSys) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..d7ce1f7245081f4664810075f95db015107e1a60 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("selfStartingTestHostAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("selfStartingTestHostA") { + sources = [ + "../../tool/src/form_test_utils.cpp", + "src/form_ability_self_starting_a.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":selfStartingTestHostAConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/config.json b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9021cdb56ceb2ae3afb86c605fcb1308ac32920e --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.selfStartingA", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.selfStartingA.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilitySelfStartingA", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability Self Starting A", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/include/form_ability_self_starting_a.h b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/include/form_ability_self_starting_a.h new file mode 100644 index 0000000000000000000000000000000000000000..765a1dd9f1a078808bc47c3e8ffa77882ce9e34d --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/include/form_ability_self_starting_a.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_SELF_STARTING_A_H_ +#define _FORM_ABILITY_SELF_STARTING_A_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriber; +class FormAbilitySelfStartingA : public Ability { +public: + ~FormAbilitySelfStartingA(); + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + + void FMS_Start_0300_01(std::string data); + + std::shared_ptr subscriber_; + + class SelfStartingCallback : public FormCallback { + public: + SelfStartingCallback(std::string name, int code):caseName_(name), code_(code) {} + virtual ~SelfStartingCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_ = ""; + int code_ = 0; + FormAbilitySelfStartingA *ability_ = nullptr; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + + using FormFunc = void (FormAbilitySelfStartingA::*)(std::string data); + std::map memberFuncMap_; + std::map calledFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilitySelfStartingA *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_SELF_STARTING_A_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/src/form_ability_self_starting_a.cpp b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/src/form_ability_self_starting_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1496c8ed547151af27c0cbc869508b6bf4954a60 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/src/form_ability_self_starting_a.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_self_starting_a.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +std::vector eventList = { + FORM_EVENT_REQ_SELF_STARTING_TEST_0100, +}; +void FormAbilitySelfStartingA::SelfStartingCallback::OnAcquired(const int32_t result, + const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilitySelfStartingA::SelfStartingCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s called, caseName_: %{public}s, code_: %{public}d", __func__, this->caseName_.c_str(), + this->code_); + FormTestUtils::PublishEvent(this->caseName_, this->code_, "true"); +} + +void FormAbilitySelfStartingA::SelfStartingCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +void FormAbilitySelfStartingA::FMS_Start_0300_01(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_SELF_STARTING_TEST_0100, EVENT_CODE_100); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_SELF_STARTING_TEST_0100, EVENT_CODE_100, "false"); + } +} + +FormAbilitySelfStartingA::~FormAbilitySelfStartingA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void FormAbilitySelfStartingA::OnStart(const Want &want) +{ + APP_LOGI("FormAbilitySelfStartingA::onStart"); + Ability::OnStart(want); +} +void FormAbilitySelfStartingA::OnActive() +{ + APP_LOGI("FormAbilitySelfStartingA::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilitySelfStartingA::OnStop() +{ + APP_LOGI("FormAbilitySelfStartingA::OnStop"); + + Ability::OnStop(); +} +void FormAbilitySelfStartingA::OnInactive() +{ + APP_LOGI("FormAbilitySelfStartingA::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilitySelfStartingA::OnBackground() +{ + APP_LOGI("FormAbilitySelfStartingA::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilitySelfStartingA::SubscribeEvent() +{ + APP_LOGI("FormAbilitySelfStartingA::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilitySelfStartingA::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilitySelfStartingA::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_SELF_STARTING_TEST_0100] = &FormAbilitySelfStartingA::FMS_Start_0300_01; + + SubscribeEvent(); +} + +void FormAbilitySelfStartingA::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + if (calledFuncMap_.find(action) != calledFuncMap_.end()) { + return; + } + calledFuncMap_.emplace(action, 0); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilitySelfStartingA::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FormEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilitySelfStartingA) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..9bab35736c834d519d8af0e76b8816f0a5fa6bd5 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("selfStartingTestHostBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "../../tool/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"formManagerSystemTest\"", + "LOG_DOMAIN = 0xD002666", + ] +} +ohos_shared_library("selfStartingTestHostB") { + sources = [ + "../../tool/src/form_test_utils.cpp", + "src/form_ability_self_starting_b.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":selfStartingTestHostBConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/config.json b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ce2020d1f1572527f668268ab986fdd1ca2ad9c7 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/config.json @@ -0,0 +1,80 @@ +{ + "app":{ + "bundleName": "com.ohos.form.manager.selfStartingB", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.form.manager.selfStartingA.FormAbility", + "name":"FormAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "FormAbility", + "moduleType": "entry" + }, + "abilities": [{ + "name": "FormAbilitySelfStartingB", + "icon": "$media:snowball", + "srcLanguage": "c++", + "label": "Form Ability Self Starting B", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }], + "defPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "grantMode": "system_grant", + "label": "$string:entry_MainAbility", + "description": "REQUIRE_FORM permission in detail" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.REQUIRE_FORM", + "reason": "fmsStressTest100", + "usedScene": { + "ability": [ + ".MainAbility" + ], + "when": "always" + } + } + ], + "js": [ + { + "name": "formDemo", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/include/form_ability_self_starting_b.h b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/include/form_ability_self_starting_b.h new file mode 100644 index 0000000000000000000000000000000000000000..fc3775131ff3cd6b8bf82a007c9c2b9369072d2f --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/include/form_ability_self_starting_b.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_ABILITY_SELF_STARTING_B_H_ +#define _FORM_ABILITY_SELF_STARTING_B_H_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class FormEventSubscriber; +class FormAbilitySelfStartingB : public Ability { +public: + ~FormAbilitySelfStartingB(); + void SubscribeEvent(); + void handleEvent(std::string action, std::string data); + + void FMS_Start_0300_02(std::string data); + void FMS_Start_0300_03(std::string data); + + std::shared_ptr subscriber_; + + class SelfStartingCallback : public FormCallback { + public: + SelfStartingCallback(std::string name, int code):caseName_(name), code_(code) {} + virtual ~SelfStartingCallback() = default; + void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; + void OnFormUninstall(const int64_t formId) const override; + + std::string caseName_ = ""; + int code_ = 0; + FormAbilitySelfStartingB *ability_ = nullptr; + }; +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +private: + void Clear(); + + using FormFunc = void (FormAbilitySelfStartingB::*)(std::string data); + std::map memberFuncMap_; + std::map calledFuncMap_; + std::shared_ptr callback_; +}; + +class FormEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + FormEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + ability_ = nullptr; + } + ~FormEventSubscriber() + { + ability_ = nullptr; + } + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void KitTerminateAbility(); + + FormAbilitySelfStartingB *ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_ABILITY_SELF_STARTING_B_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/src/form_ability_self_starting_b.cpp b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/src/form_ability_self_starting_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28f419e5dff723e6b22a19dc8982e60d70e75488 --- /dev/null +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/src/form_ability_self_starting_b.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_ability_self_starting_b.h" +#include "app_log_wrapper.h" +#include "form_st_common_info.h" +#include "form_test_utils.h" + +namespace { +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +} + +namespace OHOS { +namespace AppExecFwk { +std::vector eventList = { + FORM_EVENT_REQ_SELF_STARTING_TEST_0200, FORM_EVENT_REQ_SELF_STARTING_TEST_0300, +}; +void FormAbilitySelfStartingB::SelfStartingCallback::OnAcquired(const int32_t result, + const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); +} +void FormAbilitySelfStartingB::SelfStartingCallback::OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const +{ + APP_LOGI("%{public}s called", __func__); + APP_LOGI("%{public}s called, caseName_: %{public}s, code_: %{public}d", __func__, this->caseName_.c_str(), + this->code_); + FormTestUtils::PublishEvent(this->caseName_, this->code_, "true"); +} + +void FormAbilitySelfStartingB::SelfStartingCallback::OnFormUninstall(const int64_t formId) const +{ + APP_LOGI("%{public}s called", __func__); +} + +void FormAbilitySelfStartingB::FMS_Start_0300_02(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_SELF_STARTING_TEST_0200, EVENT_CODE_200); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_SELF_STARTING_TEST_0200, EVENT_CODE_200, "false"); + } +} + +void FormAbilitySelfStartingB::FMS_Start_0300_03(std::string data) +{ + APP_LOGI("%{public}s called", __func__); + std::shared_ptr callback = + std::make_shared(FORM_EVENT_RECV_SELF_STARTING_TEST_0300, EVENT_CODE_300); + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + // Set Want info end + bool bResult = AcquireForm(0, want, callback); + if (bResult) { + APP_LOGI("AcquireForm end"); + } else { + APP_LOGE("AcquireForm error"); + FormTestUtils::PublishEvent(FORM_EVENT_RECV_SELF_STARTING_TEST_0300, EVENT_CODE_300, "false"); + } +} + +FormAbilitySelfStartingB::~FormAbilitySelfStartingB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} +void FormAbilitySelfStartingB::OnStart(const Want &want) +{ + APP_LOGI("FormAbilitySelfStartingB::onStart"); + Ability::OnStart(want); +} +void FormAbilitySelfStartingB::OnActive() +{ + APP_LOGI("FormAbilitySelfStartingB::OnActive"); + Ability::OnActive(); + std::string eventData = GetAbilityName() + FORM_ABILITY_STATE_ONACTIVE; + FormTestUtils::PublishEvent(FORM_EVENT_ABILITY_ONACTIVED, 0, eventData); +} + +void FormAbilitySelfStartingB::OnStop() +{ + APP_LOGI("FormAbilitySelfStartingB::OnStop"); + + Ability::OnStop(); +} +void FormAbilitySelfStartingB::OnInactive() +{ + APP_LOGI("FormAbilitySelfStartingB::OnInactive"); + + Ability::OnInactive(); +} +void FormAbilitySelfStartingB::OnBackground() +{ + APP_LOGI("FormAbilitySelfStartingB::OnBackground"); + + Ability::OnBackground(); +} +void FormAbilitySelfStartingB::SubscribeEvent() +{ + APP_LOGI("FormAbilitySelfStartingB::SubscribeEvent"); + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->ability_ = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +// KitTest End +void FormAbilitySelfStartingB::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FormAbilitySelfStartingB::Init"); + Ability::Init(abilityInfo, application, handler, token); + memberFuncMap_[FORM_EVENT_REQ_SELF_STARTING_TEST_0200] = &FormAbilitySelfStartingB::FMS_Start_0300_02; + memberFuncMap_[FORM_EVENT_REQ_SELF_STARTING_TEST_0300] = &FormAbilitySelfStartingB::FMS_Start_0300_03; + + SubscribeEvent(); +} + +void FormAbilitySelfStartingB::handleEvent(std::string action, std::string data) +{ + APP_LOGI("%{public}s called", __func__); + if (calledFuncMap_.find(action) != calledFuncMap_.end()) { + return; + } + calledFuncMap_.emplace(action, 0); + auto itFunc = memberFuncMap_.find(action); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data); + } + } +} + +void FormAbilitySelfStartingB::Clear() +{ +} + +void FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FormEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FormEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + ability_->handleEvent(eventName, data.GetData()); + CommonEventManager::UnSubscribeCommonEvent(ability_->subscriber_); +} + +void FormEventSubscriber::KitTerminateAbility() +{ + if (ability_ != nullptr) { + ability_->TerminateAbility(); + } +} + +REGISTER_AA(FormAbilitySelfStartingB) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5eaf2f50bbd2a957b9c2f0d256098d54eb44cf9c --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +subdemosystem_path = "${appexecfwk_path}/test/resource/formsystemtestability/formSystemTestServiceA" +config("formSystemTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "${even_path}/cesfwk/innerkits/include", + "${even_path}/cesfwk/kits/native/include", + ] + defines = [ + "APP_LOG_TAG = \"formSystemTestServiceA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("formSystemTestServiceA") { + sources = [ "${subdemosystem_path}/src/form_st_service_ability_A.cpp" ] + configs = [ ":formSystemTestAConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/config.json b/test/resource/formsystemtestability/formSystemTestServiceA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..4fc5961629080910399cb804270eb1d900712dee --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/config.json @@ -0,0 +1,112 @@ +{ + "app": { + "bundleName": "com.form.formsystemtestservicea", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 5, + "target": 5, + "releaseType": "Beta1" + } + }, + "deviceConfig": {}, + "module": { + "package": "com.form.formsystemtestservicea", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "formmodule001", + "moduleType": "entry" + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "visible": true, + "name": "FormStServiceAbilityA", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "$string:entry_MainAbility", + "type": "service", + "launchType": "standard", + "formsEnabled": true, + "srcLanguage": "c++", + "forms": [ + { + "name": "Form_Js001", + "src": "pages/card/index", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + }, + { + "name": "Form_Js002", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "updateEnabled": true, + "updateDuration": 1, + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": true + } + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h new file mode 100755 index 0000000000000000000000000000000000000000..9d54dda7e96811cab208e70637a4a514987da769 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FORM_ST_SERVICE_ABILITY_A_ +#define FORM_ST_SERVICE_ABILITY_A_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_a"; +const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_a"; +const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; +const std::string COMMON_EVENT_ON_DELETE = "usual.event.ondelete"; +/** + * Form event trigger result + */ +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +class FormStServiceAbilityA : public Ability { +public: + ~FormStServiceAbilityA(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual FormProviderInfo OnCreate(const Want &want) override; + virtual void OnUpdate(const int64_t formId) override; + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + virtual void OnDelete(const int64_t formId) override; + virtual void OnCastTemptoNormal(const int64_t formId) override; + virtual void OnVisibilityChanged(const std::map &formEventsMap) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (FormStServiceAbilityA::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FormStServiceAbilityA *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_A_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp new file mode 100755 index 0000000000000000000000000000000000000000..8b6c9010b834eb03c026b02e044ed3c02788dae1 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_st_service_ability_A.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityA::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityA::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityA::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityA::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityA::StopSelfAbility}, +}; + +FormStServiceAbilityA::~FormStServiceAbilityA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityA::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityA::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void FormStServiceAbilityA::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityA::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void FormStServiceAbilityA::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityA::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityA::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("FormStServiceAbilityA::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityA::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityA::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityA::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityA::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityA::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityA::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityA::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityA::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityA::OnStop() +{ + APP_LOGI("FormStServiceAbilityA::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityA::OnActive() +{ + APP_LOGI("FormStServiceAbilityA::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityA::OnInactive() +{ + APP_LOGI("FormStServiceAbilityA::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityA::OnBackground() +{ + APP_LOGI("FormStServiceAbilityA::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityA::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityA::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityA::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr FormStServiceAbilityA::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityA::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityA::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityA::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityA::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityA::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} + +FormProviderInfo FormStServiceAbilityA::OnCreate(const Want &want) +{ + APP_LOGI("%{public}s start", __func__); + FormProviderInfo formProviderInfo; + if (!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formId not exist", __func__); + return formProviderInfo; + } + std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + std::string jsonData = std::string("{\"city\":\"beijingA\"}"); + FormProviderData formProviderData = FormProviderData(jsonData); + formProviderInfo.SetFormData(formProviderData); + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCreate"); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +void FormStServiceAbilityA::OnUpdate(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityA::OnTriggerEvent(const int64_t formId, const std::string &message) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); + APP_LOGI("%{public}s end, formId: %{public}s, message: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), message.c_str(), currentTime); +} + +void FormStServiceAbilityA::OnDelete(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_ON_DELETE, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + std::to_string(formId)); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityA::OnCastTemptoNormal(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCastTemptoNormal"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityA::OnVisibilityChanged(const std::map &formEventsMap) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnVisibilityChanged"); + APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); +} + +REGISTER_AA(FormStServiceAbilityA); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/formsystemtestability/formSystemTestServiceB/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceB/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d76aaf333b3b98d35c2a0645ebbafb4d8b65ee86 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceB/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +subdemosystem_path = "${appexecfwk_path}/test/resource/formsystemtestability/formSystemTestServiceB" +config("formSystemTestBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "${even_path}/cesfwk/innerkits/include", + "${even_path}/cesfwk/kits/native/include", + ] + defines = [ + "APP_LOG_TAG = \"formSystemTestServiceB\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("formSystemTestServiceB") { + sources = [ "${subdemosystem_path}/src/form_st_service_ability_B.cpp" ] + configs = [ ":formSystemTestBConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceB/config.json b/test/resource/formsystemtestability/formSystemTestServiceB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..baf8da59ed63e02ee4ec549e459d5efee9fb069f --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceB/config.json @@ -0,0 +1,107 @@ +{ + "app": { + "bundleName": "com.form.formsystemtestserviceb", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 5, + "target": 5, + "releaseType": "Beta1" + } + }, + "deviceConfig": {}, + "module": { + "package": "com.form.formsystemtestserviceb", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "formmodule001", + "moduleType": "entry" + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "visible": true, + "name": "FormStServiceAbilityB", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "$string:entry_MainAbility", + "type": "service", + "launchType": "standard", + "formsEnabled": true, + "srcLanguage": "c++", + "forms": [ + { + "name": "Form_Js001", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + }, + { + "name": "Form_Js002", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "updateEnabled": true, + "updateDuration": 1, + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": true + } + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/formSystemTestServiceB/include/form_st_service_ability_B.h b/test/resource/formsystemtestability/formSystemTestServiceB/include/form_st_service_ability_B.h new file mode 100644 index 0000000000000000000000000000000000000000..090627c0bd4a4444d91efea7bb185e081f98f08a --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceB/include/form_st_service_ability_B.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FORM_ST_SERVICE_ABILITY_B_ +#define FORM_ST_SERVICE_ABILITY_B_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_b"; +const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_b"; +const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; +/** + * Form event trigger result + */ +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +class FormStServiceAbilityB : public Ability { +public: + ~FormStServiceAbilityB(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual FormProviderInfo OnCreate(const Want &want) override; + virtual void OnUpdate(const int64_t formId) override; + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + virtual void OnDelete(const int64_t formId) override; + virtual void OnCastTemptoNormal(const int64_t formId) override; + virtual void OnVisibilityChanged(const std::map &formEventsMap) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (FormStServiceAbilityB::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FormStServiceAbilityB *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_B_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceB/src/form_st_service_ability_B.cpp b/test/resource/formsystemtestability/formSystemTestServiceB/src/form_st_service_ability_B.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc07a7a8d3bb75923553c79acb58150469831791 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceB/src/form_st_service_ability_B.cpp @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_st_service_ability_B.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityB::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityB::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityB::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityB::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityB::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityB::StopSelfAbility}, +}; + +FormStServiceAbilityB::~FormStServiceAbilityB() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityB::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityB::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void FormStServiceAbilityB::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityB::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityB::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void FormStServiceAbilityB::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityB::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityB::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("FormStServiceAbilityB::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityB::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityB::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityB::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityB::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityB::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityB::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityB::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityB::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityB::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityB::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityB::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityB::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityB::OnStop() +{ + APP_LOGI("FormStServiceAbilityB::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityB::OnActive() +{ + APP_LOGI("FormStServiceAbilityB::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityB::OnInactive() +{ + APP_LOGI("FormStServiceAbilityB::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityB::OnBackground() +{ + APP_LOGI("FormStServiceAbilityB::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityB::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityB::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + FormStServiceAbilityB::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityB::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr FormStServiceAbilityB::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityB::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityB::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityB::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityB::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityB::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityB::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityB::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} + +FormProviderInfo FormStServiceAbilityB::OnCreate(const Want &want) +{ + APP_LOGI("%{public}s start", __func__); + FormProviderInfo formProviderInfo; + if (!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formId not exist", __func__); + return formProviderInfo; + } + std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + std::string jsonData = std::string(""); + int count = 200; + for (int i = 0; i < count; i = i + 1) { + jsonData = jsonData + std::string("beijingB" + std::to_string(i)); + } + std::string formData = std::string("{\"city\":\"") + jsonData + std::string("\"}"); + FormProviderData formProviderData = FormProviderData(formData); + formProviderInfo.SetFormData(formProviderData); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +void FormStServiceAbilityB::OnUpdate(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityB::OnTriggerEvent(const int64_t formId, const std::string &message) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); + APP_LOGI("%{public}s end, formId: %{public}s, message: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), message.c_str(), currentTime); +} + +void FormStServiceAbilityB::OnDelete(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnDelete"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityB::OnCastTemptoNormal(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnCastTemptoNormal"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityB::OnVisibilityChanged(const std::map &formEventsMap) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnVisibilityChanged"); + APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); +} + +REGISTER_AA(FormStServiceAbilityB); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/formsystemtestability/formSystemTestServiceC/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceC/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..73413e024fd86e4ac9f253009830a235ec4ecd1b --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceC/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +subdemosystem_path = "${appexecfwk_path}/test/resource/formsystemtestability/formSystemTestServiceC" +config("formSystemTestCConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "${even_path}/cesfwk/innerkits/include", + "${even_path}/cesfwk/kits/native/include", + ] + defines = [ + "APP_LOG_TAG = \"formSystemTestServiceC\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("formSystemTestServiceC") { + sources = [ "${subdemosystem_path}/src/form_st_service_ability_C.cpp" ] + configs = [ ":formSystemTestCConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceC/config.json b/test/resource/formsystemtestability/formSystemTestServiceC/config.json new file mode 100644 index 0000000000000000000000000000000000000000..81c2839e9faad4ca4617a561ffd6b2cb123df40f --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceC/config.json @@ -0,0 +1,87 @@ +{ + "app": { + "bundleName": "com.form.formsystemtestservicec", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 5, + "target": 5, + "releaseType": "Beta1" + } + }, + "deviceConfig": {}, + "module": { + "package": "com.form.formsystemtestservicec", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "formmodule001", + "moduleType": "entry" + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "visible": true, + "name": "FormStServiceAbilityC", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "$string:entry_MainAbility", + "type": "service", + "launchType": "standard", + "formsEnabled": true, + "srcLanguage": "c++", + "forms": [ + { + "name": "Form_Js001", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "updateEnabled": false, + "scheduledUpdateTime": "10:30", + "updateDuration": 1, + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": true + } + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/formSystemTestServiceC/include/form_st_service_ability_C.h b/test/resource/formsystemtestability/formSystemTestServiceC/include/form_st_service_ability_C.h new file mode 100644 index 0000000000000000000000000000000000000000..2b0c9929994520eb203cb49aae9515916559a8e0 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceC/include/form_st_service_ability_C.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FORM_ST_SERVICE_ABILITY_C_ +#define FORM_ST_SERVICE_ABILITY_C_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_b"; +const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_b"; +const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; +/** + * Form event trigger result + */ +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +class FormStServiceAbilityC : public Ability { +public: + ~FormStServiceAbilityC(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual FormProviderInfo OnCreate(const Want &want) override; + virtual void OnUpdate(const int64_t formId) override; + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + virtual void OnDelete(const int64_t formId) override; + virtual void OnCastTemptoNormal(const int64_t formId) override; + virtual void OnVisibilityChanged(const std::map &formEventsMap) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (FormStServiceAbilityC::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FormStServiceAbilityC *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_C_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceC/src/form_st_service_ability_C.cpp b/test/resource/formsystemtestability/formSystemTestServiceC/src/form_st_service_ability_C.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24d64b59b69d8afb8c9394157d01a33c4b4743f5 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceC/src/form_st_service_ability_C.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_st_service_ability_C.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityC::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityC::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityC::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityC::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityC::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityC::StopSelfAbility}, +}; + +FormStServiceAbilityC::~FormStServiceAbilityC() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityC::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityC::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void FormStServiceAbilityC::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityC::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityC::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void FormStServiceAbilityC::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityC::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityC::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("FormStServiceAbilityC::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityC::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityC::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityC::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityC::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityC::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityC::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityC::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityC::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityC::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityC::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityC::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityC::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityC::OnStop() +{ + APP_LOGI("FormStServiceAbilityC::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityC::OnActive() +{ + APP_LOGI("FormStServiceAbilityC::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityC::OnInactive() +{ + APP_LOGI("FormStServiceAbilityC::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityC::OnBackground() +{ + APP_LOGI("FormStServiceAbilityC::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityC::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityC::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + FormStServiceAbilityC::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityC::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityC::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr FormStServiceAbilityC::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityC::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityC::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityC::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityC::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityC::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityC::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityC::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} + +FormProviderInfo FormStServiceAbilityC::OnCreate(const Want &want) +{ + APP_LOGI("%{public}s start", __func__); + FormProviderInfo formProviderInfo; + if (!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formId not exist", __func__); + return formProviderInfo; + } + std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + std::string jsonData = std::string("{\"city\":\"beijingC\"}"); + FormProviderData formProviderData = FormProviderData(jsonData); + formProviderInfo.SetFormData(formProviderData); + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCreate"); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +void FormStServiceAbilityC::OnUpdate(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityC::OnTriggerEvent(const int64_t formId, const std::string &message) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); + APP_LOGI("%{public}s end, formId: %{public}s, message: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), message.c_str(), currentTime); +} + +void FormStServiceAbilityC::OnDelete(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnDelete"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityC::OnCastTemptoNormal(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnCastTemptoNormal"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityC::OnVisibilityChanged(const std::map &formEventsMap) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnVisibilityChanged"); + APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); +} + +REGISTER_AA(FormStServiceAbilityC); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/formsystemtestability/formSystemTestServiceD/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceD/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..14703ff26acf0f3d77d3d5e7360ec74b1c426700 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceD/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +subdemosystem_path = "${appexecfwk_path}/test/resource/formsystemtestability/formSystemTestServiceD" +config("formSystemTestDConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "${even_path}/cesfwk/innerkits/include", + "${even_path}/cesfwk/kits/native/include", + ] + defines = [ + "APP_LOG_TAG = \"formSystemTestServiceD\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("formSystemTestServiceD") { + sources = [ "${subdemosystem_path}/src/form_st_service_ability_D.cpp" ] + configs = [ ":formSystemTestDConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceD/config.json b/test/resource/formsystemtestability/formSystemTestServiceD/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bda4f9975f4d45c22e027a8c7f17e81d6d327e7c --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceD/config.json @@ -0,0 +1,87 @@ +{ + "app": { + "bundleName": "com.form.formsystemtestserviced", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 5, + "target": 5, + "releaseType": "Beta1" + } + }, + "deviceConfig": {}, + "module": { + "package": "com.form.formsystemtestserviced", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "formmodule001", + "moduleType": "entry" + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "visible": true, + "name": "FormStServiceAbilityD", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "$string:entry_MainAbility", + "type": "service", + "launchType": "standard", + "formsEnabled": true, + "srcLanguage": "c++", + "forms": [ + { + "name": "Form_Js001", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 1, + "jsComponentName": "card", + "formVisibleNotify" : false, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": true + } + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/formSystemTestServiceD/include/form_st_service_ability_D.h b/test/resource/formsystemtestability/formSystemTestServiceD/include/form_st_service_ability_D.h new file mode 100644 index 0000000000000000000000000000000000000000..a0d8e46a9f110ffc466f7ad3b2a95b6b0110e345 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceD/include/form_st_service_ability_D.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FORM_ST_SERVICE_ABILITY_D_ +#define FORM_ST_SERVICE_ABILITY_D_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_b"; +const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_b"; +const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; +/** + * Form event trigger result + */ +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +class FormStServiceAbilityD : public Ability { +public: + ~FormStServiceAbilityD(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual FormProviderInfo OnCreate(const Want &want) override; + virtual void OnUpdate(const int64_t formId) override; + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + virtual void OnDelete(const int64_t formId) override; + virtual void OnCastTemptoNormal(const int64_t formId) override; + virtual void OnVisibilityChanged(const std::map &formEventsMap) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (FormStServiceAbilityD::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FormStServiceAbilityD *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_D_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceD/src/form_st_service_ability_D.cpp b/test/resource/formsystemtestability/formSystemTestServiceD/src/form_st_service_ability_D.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4988dacef547db10368bb4aae950879b8f42541 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceD/src/form_st_service_ability_D.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_st_service_ability_D.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityD::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityD::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityD::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityD::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityD::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityD::StopSelfAbility}, +}; + +FormStServiceAbilityD::~FormStServiceAbilityD() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityD::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityD::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void FormStServiceAbilityD::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityD::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityD::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void FormStServiceAbilityD::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityD::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityD::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("FormStServiceAbilityD::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityD::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityD::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityD::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityD::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityD::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityD::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityD::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityD::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityD::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityD::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityD::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityD::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityD::OnStop() +{ + APP_LOGI("FormStServiceAbilityD::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityD::OnActive() +{ + APP_LOGI("FormStServiceAbilityD::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityD::OnInactive() +{ + APP_LOGI("FormStServiceAbilityD::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityD::OnBackground() +{ + APP_LOGI("FormStServiceAbilityD::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityD::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityD::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + FormStServiceAbilityD::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityD::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityD::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr FormStServiceAbilityD::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityD::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityD::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityD::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityD::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityD::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityD::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityD::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} + +FormProviderInfo FormStServiceAbilityD::OnCreate(const Want &want) +{ + APP_LOGI("%{public}s start", __func__); + FormProviderInfo formProviderInfo; + if (!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formId not exist", __func__); + return formProviderInfo; + } + std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + std::string jsonData = std::string("{\"city\":\"beijingD\"}"); + FormProviderData formProviderData = FormProviderData(jsonData); + formProviderInfo.SetFormData(formProviderData); + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCreate"); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +void FormStServiceAbilityD::OnUpdate(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityD::OnTriggerEvent(const int64_t formId, const std::string &message) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); + APP_LOGI("%{public}s end, formId: %{public}s, message: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), message.c_str(), currentTime); +} + +void FormStServiceAbilityD::OnDelete(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnDelete"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityD::OnCastTemptoNormal(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnCastTemptoNormal"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityD::OnVisibilityChanged(const std::map &formEventsMap) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnVisibilityChanged"); + APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); +} + +REGISTER_AA(FormStServiceAbilityD); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/formsystemtestability/formSystemTestServiceE/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceE/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..11ad6a87d62ce665e15005f0f4f562580fd72775 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceE/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +subdemosystem_path = "${appexecfwk_path}/test/resource/formsystemtestability/formSystemTestServiceE" +config("formSystemTestEConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${aafwk_path}/frameworks/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "${even_path}/cesfwk/innerkits/include", + "${even_path}/cesfwk/kits/native/include", + ] + defines = [ + "APP_LOG_TAG = \"formSystemTestServiceE\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("formSystemTestServiceE") { + sources = [ "${subdemosystem_path}/src/form_st_service_ability_E.cpp" ] + configs = [ ":formSystemTestEConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/appkit:appkit_native", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceE/config.json b/test/resource/formsystemtestability/formSystemTestServiceE/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9bf48e647281548ed8d7250fa78ab0c17d689586 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceE/config.json @@ -0,0 +1,87 @@ +{ + "app": { + "bundleName": "com.form.formsystemtestservicee", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 5, + "target": 5, + "releaseType": "Beta1" + } + }, + "deviceConfig": {}, + "module": { + "package": "com.form.formsystemtestservicee", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "formmodule001", + "moduleType": "entry" + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "visible": true, + "name": "FormStServiceAbilityE", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "$string:entry_MainAbility", + "type": "service", + "launchType": "standard", + "formsEnabled": true, + "srcLanguage": "c++", + "forms": [ + { + "name": "Form_Js001", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "updateEnabled": true, + "scheduledUpdateTime": "0:0", + "updateDuration": 1, + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": true + } + } + ] + } +} \ No newline at end of file diff --git a/test/resource/formsystemtestability/formSystemTestServiceE/include/form_st_service_ability_E.h b/test/resource/formsystemtestability/formSystemTestServiceE/include/form_st_service_ability_E.h new file mode 100644 index 0000000000000000000000000000000000000000..a84bc3862a5e4581a1e4ce728eadc30c049da7b7 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceE/include/form_st_service_ability_E.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FORM_ST_SERVICE_ABILITY_E_ +#define FORM_ST_SERVICE_ABILITY_E_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_b"; +const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_b"; +const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; +/** + * Form event trigger result + */ +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +class FormStServiceAbilityE : public Ability { +public: + ~FormStServiceAbilityE(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual FormProviderInfo OnCreate(const Want &want) override; + virtual void OnUpdate(const int64_t formId) override; + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + virtual void OnDelete(const int64_t formId) override; + virtual void OnCastTemptoNormal(const int64_t formId) override; + virtual void OnVisibilityChanged(const std::map &formEventsMap) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (FormStServiceAbilityE::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FormStServiceAbilityE *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_E_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceE/src/form_st_service_ability_E.cpp b/test/resource/formsystemtestability/formSystemTestServiceE/src/form_st_service_ability_E.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfcc357b114a277596329404bc51860565aaec7e --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceE/src/form_st_service_ability_E.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_st_service_ability_E.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityE::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityE::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityE::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityE::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityE::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityE::StopSelfAbility}, +}; + +FormStServiceAbilityE::~FormStServiceAbilityE() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityE::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityE::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void FormStServiceAbilityE::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityE::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityE::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void FormStServiceAbilityE::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityE::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityE::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("FormStServiceAbilityE::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityE::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityE::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityE::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityE::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityE::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityE::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityE::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityE::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityE::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityE::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityE::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityE::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityE::OnStop() +{ + APP_LOGI("FormStServiceAbilityE::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityE::OnActive() +{ + APP_LOGI("FormStServiceAbilityE::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityE::OnInactive() +{ + APP_LOGI("FormStServiceAbilityE::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityE::OnBackground() +{ + APP_LOGI("FormStServiceAbilityE::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityE::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityE::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + FormStServiceAbilityE::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityE::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityE::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr FormStServiceAbilityE::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityE::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityE::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityE::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityE::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityE::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityE::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityE::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} + +FormProviderInfo FormStServiceAbilityE::OnCreate(const Want &want) +{ + APP_LOGI("%{public}s start", __func__); + FormProviderInfo formProviderInfo; + if (!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formId not exist", __func__); + return formProviderInfo; + } + std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + std::string jsonData = std::string("{\"city\":\"beijingE\"}"); + FormProviderData formProviderData = FormProviderData(jsonData); + formProviderInfo.SetFormData(formProviderData); + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCreate"); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +void FormStServiceAbilityE::OnUpdate(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityE::OnTriggerEvent(const int64_t formId, const std::string &message) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); + APP_LOGI("%{public}s end, formId: %{public}s, message: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), message.c_str(), currentTime); +} + +void FormStServiceAbilityE::OnDelete(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnDelete"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityE::OnCastTemptoNormal(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnCastTemptoNormal"); + APP_LOGI("%{public}s end, formId: %{public}s, current time: %{public}ld", __func__, + std::to_string(formId).c_str(), currentTime); +} + +void FormStServiceAbilityE::OnVisibilityChanged(const std::map &formEventsMap) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, + "OnVisibilityChanged"); + APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); +} + +REGISTER_AA(FormStServiceAbilityE); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/formsystemtestability/tool/include/form_test_utils.h b/test/resource/formsystemtestability/tool/include/form_test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..73daabb2d082cb47b2dd8e2781d59d0400df270c --- /dev/null +++ b/test/resource/formsystemtestability/tool/include/form_test_utils.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _FORM_TEST_UTILS_H_ +#define _FORM_TEST_UTILS_H_ +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class FormTestUtils { +public: + FormTestUtils() = default; + virtual ~FormTestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _FORM_TEST_UTILS_H_ \ No newline at end of file diff --git a/test/resource/formsystemtestability/tool/src/form_test_utils.cpp b/test/resource/formsystemtestability/tool/src/form_test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ba7d976ce7513f6a69c5a5c58ee2ad8cda606af --- /dev/null +++ b/test/resource/formsystemtestability/tool/src/form_test_utils.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_test_utils.h" +#include "common_event_data.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool FormTestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want FormTestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/tools/ohos_test.xml b/test/resource/tools/ohos_test.xml index d94a2929fc9a28d2730d52594ccb0acd12dd326e..cf80c8cf2983f96784a448c15bd63f79d3c9fd28 100644 --- a/test/resource/tools/ohos_test.xml +++ b/test/resource/tools/ohos_test.xml @@ -16,20 +16,20 @@ - - - - - - \ No newline at end of file diff --git a/test/systemtest/BUILD.gn b/test/systemtest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e6015affe0b793c4d78bf95fd5b061b5f085a005 --- /dev/null +++ b/test/systemtest/BUILD.gn @@ -0,0 +1,30 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//foundation/aafwk/standard/aafwk.gni") + +config("system_test_config") { + include_dirs = [] + + configs = [] +} + +group("systemtest") { + testonly = true + + deps = [ + "common/ams:systemtest", + "common/fms:systemtest", + "common/task_dispatcher:systemtest_task", + ] +} diff --git a/test/systemtest/common/ams/BUILD.gn b/test/systemtest/common/ams/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..950b5b9d13746853ae0cb0aa6180bdfaafd4b8b8 --- /dev/null +++ b/test/systemtest/common/ams/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("ams_system_test_config") { + defines = [ + # "APP_LOG_TAG = \"AmsSystemTest\"", + # "LOG_DOMAIN = 0xD00111F", + ] + + configs = [ + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base_sdk_config", + ] +} + +group("systemtest") { + testonly = true + + deps = [ + "ams_aa_command_test:systemtest", + "ams_ability_append_test:systemtest", + "ams_ability_state_age_manual_test:systemtest", + "ams_ability_state_test:systemtest", + "ams_ability_visible_test:systemtest", + "ams_app_process_manage_test:systemtest", + "ams_check_service:systemtest", + "ams_configuration_updated_test:systemtest", + "ams_data_ability_test:systemtest", + "ams_dfx_test:systemtest", + "ams_kit_test:systemtest", + "ams_missionstack_test:systemtest", + "ams_page_ability_test:systemtest", + "ams_power_test:systemtest", + "ams_service_ability_test:systemtest", + "tool:system_test_ability_util", + ] +} diff --git a/test/systemtest/common/ams/ams_aa_command_test/BUILD.gn b/test/systemtest/common/ams/ams_aa_command_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..c869fc0aa2f2230a43f97f735c96aa9b12837681 --- /dev/null +++ b/test/systemtest/common/ams/ams_aa_command_test/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_aa_command_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/aafwk/standard/tools/aa/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_aa_command_test.cpp", + ] + + configs = [ + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_aa_command_test" ] +} diff --git a/test/systemtest/common/ams/ams_aa_command_test/ams_aa_command_test.cpp b/test/systemtest/common/ams/ams_aa_command_test/ams_aa_command_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..808ae1f2acd895958aac9a950dd8638da601f293 --- /dev/null +++ b/test/systemtest/common/ams/ams_aa_command_test/ams_aa_command_test.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "ability_command.h" +#include "shell_command.h" +#include "hilog_wrapper.h" +#include "module_test_dump_util.h" +#include "st_ability_util.h" +#include + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using std::string; + +namespace { +static const std::string bundleName = "com.ohos.amsst.appA"; +static const std::string abilityName = "AmsStAbilityA1"; +constexpr int WAIT_LAUNCHER_OK = 5 * 1000; +static std::string launcherBundleName = "com.ohos.launcher"; +std::string systemUiBundle = "com.ohos.systemui"; +std::string terminatePageAbility = "requ_page_ability_terminate"; +static const string mexpectResult = "User ID #0\n MissionStack ID #0\n MissionRecord ID #0 bottom app " + "[com.ohos.launcher.MainAbility] winMode #0\n AbilityRecord"; +} // namespace + +class AmsAACommandTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + void ExecuteSystemForResult(const string &cmd, string &result); + void ReadForResult(const string &cmd, string &result); + void Clear(); +}; + +void AmsAACommandTest::SetUpTestCase(void) +{ + STAbilityUtil::Install("amsSystemTestA"); +} + +void AmsAACommandTest::TearDownTestCase(void) +{ + STAbilityUtil::Uninstall("com.ohos.amsst.appA"); +} + +void AmsAACommandTest::SetUp(void) +{} + +void AmsAACommandTest::TearDown(void) +{} + +void AmsAACommandTest::ExecuteSystemForResult(const string &cmd, string &result) +{ + result.clear(); + int MAX_SIZE = 1024; + char buf_ps[MAX_SIZE]; + FILE *ptr; + string command = "aa " + cmd; + if (!command.empty() && (ptr = popen(command.c_str(), "r")) != nullptr) { + while (fgets(buf_ps, MAX_SIZE, ptr) != nullptr) { + result.append(buf_ps); + } + pclose(ptr); + ptr = nullptr; + } +} + +void AmsAACommandTest::Clear() +{ + STAbilityUtil::KillService("appspawn"); + STAbilityUtil::KillService("installs"); + STAbilityUtil::KillService(launcherBundleName); + STAbilityUtil::KillService(systemUiBundle); + STAbilityUtil::KillService("foundation"); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LAUNCHER_OK)); +} + +/** + * @tc.number : ams_aa_command_test_0100 + * @tc.name : aa -h + * @tc.desc : commands help when aa -h command. + */ +HWTEST_F(AmsAACommandTest, ams_aa_command_test_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0100 start"; + + string result; + const string cmd{"start -h"}; + const string &expectResult = HELP_MSG_START; + ExecuteSystemForResult(cmd, result); + + EXPECT_EQ(result, expectResult); + + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0100 end"; +} + +/** + * @tc.number : ams_aa_command_test_0200 + * @tc.name : aa dump -h + * @tc.desc : commands help when aa dump -h command. + */ +HWTEST_F(AmsAACommandTest, ams_aa_command_test_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0200 start"; + + string result; + const string cmd{"dump -h"}; + const string &expectResult = HELP_MSG_DUMP; + ExecuteSystemForResult(cmd, result); + + EXPECT_EQ(result, expectResult); + + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0200 end"; +} + +/** + * @tc.number : ams_aa_command_test_0300 + * @tc.name : aa dump -a + * @tc.desc : all page abilities when aa -a command. + */ +HWTEST_F(AmsAACommandTest, ams_aa_command_test_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0300 start"; + + string dumpInfo, result; + const string cmd{"dump -a"}; + const string &expectResult = mexpectResult; + ExecuteSystemForResult(cmd, result); + EXPECT_EQ(result.substr(0, expectResult.size()), expectResult); + + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0300 end"; +} + +/** + * @tc.number : ams_aa_command_test_0400 + * @tc.name : aa dump -s + * @tc.desc : commands the ability info of a specificed stack when aa -s command. + */ +HWTEST_F(AmsAACommandTest, ams_aa_command_test_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0400 start"; + + string result; + const string cmd{"dump -s 0"}; + const string &expectResult = mexpectResult; + ExecuteSystemForResult(cmd, result); + EXPECT_EQ(result.substr(0, expectResult.size()), expectResult); + + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0400 end"; +} + +/** + * @tc.number : ams_aa_command_test_0500 + * @tc.name : aa dump -m + * @tc.desc : dump the ability info of a specificed mission when aa -m command. + */ +HWTEST_F(AmsAACommandTest, ams_aa_command_test_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0500 start"; + + string result; + const string cmd{"dump -m 0"}; + const string &expectResult = "User ID #0\n MissionRecord ID #0 bottom app " + "[com.ohos.launcher.MainAbility] winMode #0\n AbilityRecord ID #0\n app "; + ExecuteSystemForResult(cmd, result); + EXPECT_EQ(result.substr(0, expectResult.size()), expectResult); + + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0500 end"; +} + +/** + * @tc.number : ams_aa_command_test_0600 + * @tc.name : aa dump -l + * @tc.desc : dump the mission list of every stack when aa -l command. + */ +HWTEST_F(AmsAACommandTest, ams_aa_command_test_0600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0600 start"; + string result; + const string cmd{"dump -l"}; + const string &expectResult = "User ID #0\n MissionStack ID #0 [ #0 ]\n MissionStack ID #1 [ ]\n"; + ExecuteSystemForResult(cmd, result); + EXPECT_EQ(result, expectResult); + + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0600 end"; +} + +/** + * @tc.number : ams_aa_command_test_0700 + * @tc.name : aa -d -a -b + * @tc.desc : start/stop page ability when aa -d -a -b command. + */ +HWTEST_F(AmsAACommandTest, ams_aa_command_test_0700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0700 start"; + + string result; + const string cmd{"start -d deviceId -a " + abilityName + " -b " + bundleName}; + const string expectResult{"start ability successfully.\n"}; + ExecuteSystemForResult(cmd, result); + EXPECT_EQ(result, expectResult); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LAUNCHER_OK)); + STAbilityUtil::PublishEvent(terminatePageAbility, 0, abilityName); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LAUNCHER_OK)); + + GTEST_LOG_(INFO) << "AmsAACommandTest ams_aa_command_test_0700 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_ability_append_test/BUILD.gn b/test/systemtest/common/ams/ams_ability_append_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..ba3a315435500068ce6ce8ff4b04b4085ce7ff9f --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_append_test/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_ability_append_test") { + module_out_path = module_output_path + + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_ability_append_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_ability_append_test" ] +} diff --git a/test/systemtest/common/ams/ams_ability_append_test/ams_ability_append_test.cpp b/test/systemtest/common/ams/ams_ability_append_test/ams_ability_append_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f425ac2ed4fbc9bad270a0154d9e0463e5ffc015 --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_append_test/ams_ability_append_test.cpp @@ -0,0 +1,446 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ability_append_test_info.h" +#include "ability_lifecycle.h" +#include "ability_lifecycle_executor.h" +#include "ability_manager_errors.h" +#include "ability_manager_service.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "event.h" +#include "hilog_wrapper.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "stoperator.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "uri.h" +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; + +using MAP_STR_STR = std::map; +namespace { +static const string KIT_BUNDLE_NAME = "com.ohos.amsst.AppAppend"; +static const string KIT_HAP_NAME = "amsAbilityAppendTest"; +static const string FIRST_ABILITY_NAME = "MainAbility"; +static const string SECOND_ABILITY_NAME = "SecondAbility"; +static const string THIRD_ABILITY_NAME = "MainAbility"; +static constexpr int WAIT_TIME = 1; +constexpr int START_DELAY = 1000; +static string g_eventMessage = ""; +} +class AmsAbilityAppendTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static void Reinstall(const std::string &hapName, const std::string &bundleName); + void ResetSystem() const; + static bool SubscribeEvent(); + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber(){}; + }; + + static sptr abilityMgrService; + static Event event; +}; + +Event AmsAbilityAppendTest::event = Event(); +sptr AmsAbilityAppendTest::abilityMgrService = nullptr; + +void AmsAbilityAppendTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + if (data.GetWant().GetAction() == g_EVENT_RESP_FIRST_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_FIRSTB_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_LIFECYCLE) { + TestCompleted(event, data.GetData(), data.GetCode()); + } else if (data.GetWant().GetAction() == g_EVENT_RESP_FIRST || data.GetWant().GetAction() == g_EVENT_RESP_FIRSTB || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND) { + g_eventMessage = data.GetData(); + TestCompleted(event, data.GetWant().GetAction(), data.GetCode()); + GTEST_LOG_(INFO) << "OnReceiveEvent: g_eventMessage=" << data.GetData(); + } +} + +int AmsAbilityAppendTest::TestWaitCompleted( + Event &event, const std::string &eventName, const int code, const int timeout) +{ + GTEST_LOG_(INFO) << "TestWaitCompleted : " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} + +void AmsAbilityAppendTest::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + GTEST_LOG_(INFO) << "TestCompleted : " << eventName << " " << code; + return STAbilityUtil::Completed(event, eventName, code); +} + +void AmsAbilityAppendTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void AmsAbilityAppendTest::TearDownTestCase(void) +{} + +static int CODE_ = 0; +void AmsAbilityAppendTest::SetUp(void) +{ + ResetSystem(); + STAbilityUtil::Install(KIT_HAP_NAME + "A"); + STAbilityUtil::Install(KIT_HAP_NAME + "B"); + STAbilityUtil::CleanMsg(event); + + CODE_++; +} + +void AmsAbilityAppendTest::TearDown(void) +{ + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME + "A"); + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); +} + +bool AmsAbilityAppendTest::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_RESP_FIRST_LIFECYCLE, + g_EVENT_RESP_SECOND_LIFECYCLE, + g_EVENT_RESP_FIRSTB_LIFECYCLE, + g_EVENT_RESP_FIRST, + g_EVENT_RESP_SECOND, + g_EVENT_RESP_FIRSTB + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsAbilityAppendTest::Reinstall(const std::string &hapName, const std::string &bundleName) +{ + STAbilityUtil::Uninstall(bundleName); + STAbilityUtil::Install(hapName); +} + +void AmsAbilityAppendTest::ResetSystem() const +{ + GTEST_LOG_(INFO) << "ResetSystem"; +} + +/** + * @tc.number : AMS_Ability_Append_00100 + * @tc.name : test OnSetCaller in ability.h + * @tc.desc : Verify that the result of OnSetCaller function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE, START_DELAY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE, START_DELAY), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::OnSetCaller) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_, START_DELAY), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00100 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00200 + * @tc.name : test TerminateAndRemoveMisson in ability.h + * @tc.desc : Verify that the result of TerminateAndRemoveMisson function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00200 start"; + MAP_STR_STR params; + Want wantFirst = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(wantFirst, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE, START_DELAY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE, START_DELAY), 0); + + auto abilityMs = STAbilityUtil::GetAbilityManagerService(); + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + sleep(5); + Want wantSecond = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + // start first ability + eCode = STAbilityUtil::StartAbility(wantSecond, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE, START_DELAY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE, START_DELAY), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_A_CODE, START_DELAY), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::TerminateAndRemoveMisson) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_, START_DELAY), 0); + string appInfo = g_eventMessage; + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00200 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00300 + * @tc.name : test TerminateAbilityResult in ability.h + * @tc.desc : Verify that the result of TerminateAbilityResult function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE, START_DELAY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE, START_DELAY), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AppendApi::TerminateAbilityResult) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_, START_DELAY), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + EXPECT_EQ(TestWaitCompleted(event, "OnStop", SECOND_ABILITY_A_CODE, START_DELAY), 0); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00300 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00400 + * @tc.name : test GetDispalyOrientation in ability.h + * @tc.desc : Verify that the result of GetDispalyOrientation function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::GetDispalyOrientation) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00400 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00500 + * @tc.name : test GetPreferencesDir in ability.h + * @tc.desc : Verify that the result of GetPreferencesDir function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE, START_DELAY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE, START_DELAY), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::GetPreferencesDir) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_, START_DELAY), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "0"); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00500 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00600 + * @tc.name : test StartAbilities in ability.h + * @tc.desc : Verify that the result of StartAbilities function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::StartAbilities) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo = g_eventMessage; + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00600 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00700 + * @tc.name : test GetColorMode in ability.h + * @tc.desc : Verify that the result of GetColorMode function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::GetColorMode) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00700 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00800 + * @tc.name : test SetColorMode in ability.h + * @tc.desc : Verify that the result of SetColorMode function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::SetColorMode) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00800 end"; +} + +/** + * @tc.number : AMS_Ability_Append_00900 + * @tc.name : test IsFirstInMission in ability.h + * @tc.desc : Verify that the result of IsFirstInMission function is correct. + */ +HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::IsFirstInMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, "1"); + GTEST_LOG_(INFO) << "AmsAbilityAppendTest AMS_Ability_Append_00900 end"; +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_ability_state_age_manual_test/BUILD.gn b/test/systemtest/common/ams/ams_ability_state_age_manual_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..434f05196d0256d8ae1dfb60a5f6cdd1fed891e0 --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_state_age_manual_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams/" + +config("system_test_ams_ability_state_age_manual_test_config") { + include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_systemtest("ams_ability_state_age_manual_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_ability_state_age_manual_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_config", + + ":system_test_ams_ability_state_age_manual_test_config", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/:system_test_ability_util_config", + "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_ability_state_age_manual_test" ] +} diff --git a/test/systemtest/common/ams/ams_ability_state_age_manual_test/ams_ability_state_age_manual_test.cpp b/test/systemtest/common/ams/ams_ability_state_age_manual_test/ams_ability_state_age_manual_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..e804bc9ca796a038b54c6a6fdcf5e74ee0592851 --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_state_age_manual_test/ams_ability_state_age_manual_test.cpp @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_lifecycle_executor.h" +#include "module_test_dump_util.h" +#include "common_event_manager.h" +#include "st_ability_util.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +using namespace testing::ext; +using namespace STABUtil; +using namespace OHOS::MTUtil; +namespace { +const std::string bundleName = "com.ohos.amsst.fwkAbilityState"; +const std::string firstAbilityName = "FwkAbilityStateMain"; +const std::string secondAbilityname = "FwkAbilityStateSecond"; +static const std::string DUMP_ALL = "-a"; +std::string FwkAbilityState_Event_Resp_A = "resp_com_ohos_amsst_FwkAbilityStateA"; +std::string FwkAbilityState_Event_Requ_A = "requ_com_ohos_amsst_FwkAbilityStateA"; +std::string FwkAbilityState_Event_Resp_B = "resp_com_ohos_amsst_FwkAbilityStateB"; +std::string FwkAbilityState_Event_Requ_B = "requ_com_ohos_amsst_FwkAbilityStateB"; +constexpr int onActive = 1; +constexpr int onBackground = 2; +constexpr int WAIT_TIME = 500; +constexpr int DELAY = 10; +} // namespace +class AmsAbilityStateAgeManualTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + class AppEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { + public: + explicit AppEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; + ~AppEventSubscriber() = default; + }; + + void StartAbility(const std::string &abilityName, const std::string &bundleName); + static OHOS::sptr abilityMs; + static OHOS::STtools::Event event; + static OHOS::StressTestLevel stLevel_; + static std::shared_ptr subscriber_; +}; + +Event AmsAbilityStateAgeManualTest::event = OHOS::STtools::Event(); +sptr AmsAbilityStateAgeManualTest::abilityMs = nullptr; +StressTestLevel AmsAbilityStateAgeManualTest::stLevel_ {}; +std::shared_ptr AmsAbilityStateAgeManualTest::subscriber_ = nullptr; + +void AmsAbilityStateAgeManualTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + stLevel_.AMSLevel = 1; +} +void AmsAbilityStateAgeManualTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsAbilityStateAgeManualTest::SetUp() +{ + std::vector hapNameList = {"fwkAbilityState"}; + STAbilityUtil::InstallHaps(hapNameList); +} + +void AmsAbilityStateAgeManualTest::TearDown() +{ + std::vector bundleNameList = { + bundleName, + }; + + sleep(1); + STAbilityUtil::UninstallBundle(bundleNameList); + STAbilityUtil::CleanMsg(event); +} + +void AmsAbilityStateAgeManualTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + STAbilityUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +bool AmsAbilityStateAgeManualTest::SubscribeEvent() +{ + std::vector eventList = { + FwkAbilityState_Event_Resp_A, + FwkAbilityState_Event_Resp_B, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsAbilityStateAgeManualTest::StartAbility(const std::string &abilityName, const std::string &bundleName) +{ + std::map params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + ErrCode result = STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "AmsAbilityStateAgeManualTest::StartAbility : " << result; + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_A, onActive, DELAY)); +} + +/** + * @tc.number : FWK_RestoreAbilityStateAged_0100 + * @tc.name : RestoreAbilityState aged + * @tc.desc : RestoreAbilityState not called when aging time expired + */ +HWTEST_F(AmsAbilityStateAgeManualTest, FWK_RestoreAbilityStateAged_0100, Function | MediumTest | Level1) +{ + std::string data; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + std::string crashEvent = "DoCrash"; + bool result = false; + + for (int i = 0; i < stLevel_.AMSLevel; i++) { + StartAbility(firstAbilityName, bundleName); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_A, onBackground, DELAY)); + data = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_A, onBackground); + result = data.compare("OnInactiveOnSaveAbilityStateOnBackground") == 0; + EXPECT_TRUE(result); + sleep(1); + EXPECT_EQ(true, STAbilityUtil::PublishEvent(FwkAbilityState_Event_Requ_A, onActive, crashEvent)); + GTEST_LOG_(INFO) << "FWK_RestoreAbilityStateAged_0100 DOCRASH NOTIFY"; + sleep(10); + StartAbility(firstAbilityName, bundleName); + data = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_A, onActive); + GTEST_LOG_(INFO) << "FWK_RestoreAbilityStateAged_0100 data= : " << data; + result = data.compare("OnStartOnNewWantOnActive") == 0; + EXPECT_TRUE(result); + + if (!result && i > 0) { + GTEST_LOG_(INFO) << "FWK_RestoreAbilityStateAged_0100 : " << i; + break; + } + } +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_ability_state_test/BUILD.gn b/test/systemtest/common/ams/ams_ability_state_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..6b7fbaf3abe1d82668ca97f3c088436acaeddce9 --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_state_test/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams/" + +config("system_test_ams_ability_state_test_config") { + include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_systemtest("ams_ability_state_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_ability_state_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_config", + + ":system_test_ams_ability_state_test_config", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/:system_test_ability_util_config", + "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_ability_state_test" ] +} diff --git a/test/systemtest/common/ams/ams_ability_state_test/ams_ability_state_test.cpp b/test/systemtest/common/ams/ams_ability_state_test/ams_ability_state_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..f09b3a74a9ed5846accdf95fa14f6c4f6085719f --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_state_test/ams_ability_state_test.cpp @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_lifecycle_executor.h" +#include "module_test_dump_util.h" +#include "common_event_manager.h" +#include "st_ability_util.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +using namespace testing::ext; +using namespace STABUtil; +using namespace OHOS::MTUtil; +namespace { +const std::string bundleName = "com.ohos.amsst.fwkAbilityState"; +const std::string firstAbilityName = "FwkAbilityStateMain"; +const std::string secondAbilityname = "FwkAbilityStateSecond"; +static const std::string DUMP_ALL = "-a"; +std::string FwkAbilityState_Event_Resp_A = "resp_com_ohos_amsst_FwkAbilityStateA"; +std::string FwkAbilityState_Event_Requ_A = "requ_com_ohos_amsst_FwkAbilityStateA"; +std::string FwkAbilityState_Event_Resp_B = "resp_com_ohos_amsst_FwkAbilityStateB"; +std::string FwkAbilityState_Event_Requ_B = "requ_com_ohos_amsst_FwkAbilityStateB"; +constexpr int onActive = 1; +constexpr int onBackground = 2; +constexpr int WAIT_TIME = 500; +constexpr int DELAY = 10; +} // namespace +class AmsAbilityStateTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + class AppEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { + public: + explicit AppEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; + ~AppEventSubscriber() = default; + }; + + void StartAbility(const std::string &abilityName, const std::string &bundleName); + void CheckBackGroundState(const std::string &abilityName, bool bIsBackGround); + static OHOS::sptr abilityMs; + static OHOS::STtools::Event event; + static OHOS::StressTestLevel stLevel_; + static std::shared_ptr subscriber_; +}; + +Event AmsAbilityStateTest::event = OHOS::STtools::Event(); +sptr AmsAbilityStateTest::abilityMs = nullptr; +StressTestLevel AmsAbilityStateTest::stLevel_ {}; +std::shared_ptr AmsAbilityStateTest::subscriber_ = nullptr; + +void AmsAbilityStateTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + stLevel_.AMSLevel = 1; +} +void AmsAbilityStateTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsAbilityStateTest::SetUp() +{ + std::vector hapNameList = {"fwkAbilityState"}; + STAbilityUtil::InstallHaps(hapNameList); +} + +void AmsAbilityStateTest::TearDown() +{ + std::vector bundleNameList = { + bundleName, + }; + + sleep(1); + STAbilityUtil::UninstallBundle(bundleNameList); + STAbilityUtil::CleanMsg(event); +} + +void AmsAbilityStateTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + STAbilityUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +bool AmsAbilityStateTest::SubscribeEvent() +{ + std::vector eventList = { + FwkAbilityState_Event_Resp_A, + FwkAbilityState_Event_Resp_B, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsAbilityStateTest::StartAbility(const std::string &abilityName, const std::string &bundleName) +{ + std::map params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + ErrCode result = STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "AmsAbilityStateTest::StartAbility : " << result; + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_A, onActive, DELAY)); +} + +void AmsAbilityStateTest::CheckBackGroundState(const std::string &abilityName, bool bIsBackGround) +{ + std::vector dumpInfo; + std::vector result; + + abilityMs->DumpState(DUMP_ALL, dumpInfo); + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + EXPECT_NE(pos, result.end()); + MTDumpUtil::GetInstance()->GetAll("State", dumpInfo, result); + EXPECT_TRUE(pos < result.end()); + if (bIsBackGround) { + EXPECT_EQ(*pos, "BACKGROUND"); + } else { + EXPECT_NE(*pos, "BACKGROUND"); + } +} + +/** + * @tc.number : FWK_SaveAbilityState_0100 + * @tc.name : onSaveAbilityState called when home event + * @tc.desc : onSaveAbilityState called when home event + */ +HWTEST_F(AmsAbilityStateTest, FWK_SaveAbilityState_0100, Function | MediumTest | Level1) +{ + std::string data; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + bool result = false; + + for (int i = 0; i < stLevel_.AMSLevel; i++) { + StartAbility(firstAbilityName, bundleName); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_A, onBackground, DELAY)); + data = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_A, onBackground); + result = data.compare("OnInactiveOnSaveAbilityStateOnBackground") == 0; + EXPECT_TRUE(result); + + if (!result && i > 0) { + GTEST_LOG_(INFO) << "FWK_SaveAbilityState_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : FWK_SaveAbilityState_0200 + * @tc.name : onSaveAbilityState called when start another ability + * @tc.desc : onSaveAbilityState called when start another ability + */ +HWTEST_F(AmsAbilityStateTest, FWK_SaveAbilityState_0200, Function | MediumTest | Level1) +{ + std::string eventData = "StartNextAbility"; + std::string resultData; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + StartAbility(firstAbilityName, bundleName); + STAbilityUtil::PublishEvent(FwkAbilityState_Event_Requ_A, onActive, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_B, onActive, DELAY)); + resultData = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_B, onActive); + result = resultData.compare("OnStartOnActive") == 0; + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_A, onBackground, DELAY)); + resultData = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_A, onBackground); + result = resultData.compare("OnInactiveOnSaveAbilityStateOnBackground") == 0; + EXPECT_TRUE(result); + sleep(2); + + if (!result && i > 0) { + GTEST_LOG_(INFO) << "FWK_SaveAbilityState_0200 : " << i; + break; + } + } +} + +/** + * @tc.number : FWK_RestoreAbilityState_0100 + * @tc.name : onRestoreAbilityState called when restart after app crash + * @tc.desc : onRestoreAbilityState called when restart after app crash + */ +HWTEST_F(AmsAbilityStateTest, FWK_RestoreAbilityState_0100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleName); + std::string data; + std::vector bundleNameList = { + bundleName, + }; + std::string crashEvent = "DoCrash"; + bool result = false; + + for (int i = 0; i < stLevel_.AMSLevel; i++) { + EXPECT_EQ(true, STAbilityUtil::PublishEvent(FwkAbilityState_Event_Requ_A, onActive, crashEvent)); + GTEST_LOG_(INFO) << "FWK_RestoreAbilityState_0100 DOCRASH NOTIFY"; + sleep(1); + + StartAbility(firstAbilityName, bundleName); + data = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_A, onActive); + GTEST_LOG_(INFO) << "FWK_RestoreAbilityState_0100 data= : " << data; + result = data.compare("OnStartOnRestoreAbilityStateOnNewWantOnActive") == 0; + + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "FWK_RestoreAbilityState_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : FWK_SaveAbilityStateTimeout_0100 + * @tc.name : onSaveAbilityState timeout + * @tc.desc : onSaveAbilityState timeout when moving ability background, check ability state + */ +HWTEST_F(AmsAbilityStateTest, FWK_SaveAbilityStateTimeout_0100, Function | MediumTest | Level1) +{ + std::string eventData = "BlockAndStart"; + std::string resultData; + bool result = false; + + for (int i = 0; i < stLevel_.AMSLevel; i++) { + StartAbility(firstAbilityName, bundleName); + STAbilityUtil::PublishEvent(FwkAbilityState_Event_Requ_A, onActive, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_B, onActive, DELAY)); + resultData = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_B, onActive); + result = resultData.compare("OnStartOnActive") == 0; + sleep(2); + CheckBackGroundState(firstAbilityName, false); + sleep(8); + CheckBackGroundState(firstAbilityName, true); + (void)STAbilityUtil::WaitCompleted(event, FwkAbilityState_Event_Resp_A, onBackground, DELAY); + resultData = STAbilityUtil::GetData(event, FwkAbilityState_Event_Resp_A, onBackground); + result = resultData.compare("OnInactiveOnSaveAbilityStateOnBackground") == 0; + EXPECT_TRUE(result); + + if (!result && i > 0) { + GTEST_LOG_(INFO) << "FWK_SaveAbilityStateTimeout_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : FWK_RestoreAbilityStateTimeout_0100 + * @tc.name : onRestoreAbilityState timeout + * @tc.desc : onRestoreAbilityState timeout when restarting from crash, check final status ACTIVATING + */ +HWTEST_F(AmsAbilityStateTest, FWK_RestoreAbilityStateTimeout_0100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleName); + std::string data; + std::vector bundleNameList = { + bundleName, + }; + std::string crashEvent = "DoCrash"; + std::map params; + Want want; + ErrCode ret; + std::vector dumpInfo; + std::vector vstrResult; + bool result = false; + + for (int i = 0; i < stLevel_.AMSLevel; i++) { + EXPECT_EQ(true, STAbilityUtil::PublishEvent(FwkAbilityState_Event_Requ_A, onActive, crashEvent)); + GTEST_LOG_(INFO) << "FWK_RestoreAbilityStateTimeout_0100 DOCRASH NOTIFY"; + sleep(1); + + params["StartType1"] = "BlockRestore"; + want = STAbilityUtil::MakeWant("device", firstAbilityName, bundleName, params); + ret = STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "AmsAbilityStateTest::StartAbility : " << ret; + + sleep(6); + abilityMs->DumpState(DUMP_ALL, dumpInfo); + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, vstrResult); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(firstAbilityName, vstrResult, vstrResult.begin()); + EXPECT_NE(pos, vstrResult.end()); + MTDumpUtil::GetInstance()->GetAll("State", dumpInfo, vstrResult); + EXPECT_TRUE(pos < vstrResult.end()); + GTEST_LOG_(INFO) << "FWK_RestoreAbilityStateTimeout_0100::POS2 : " << *pos; + result = (*pos).compare("ACTIVATING") == 0; + EXPECT_TRUE(result); + + if (!result && i > 0) { + GTEST_LOG_(INFO) << "FWK_RestoreAbilityStateTimeout_0100 : " << i; + break; + } + } +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_ability_visible_test/BUILD.gn b/test/systemtest/common/ams/ams_ability_visible_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..e4dcf1334411702df42bdca4a8779ee0faefb1bb --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_visible_test/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_ability_visible_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_ability_visible_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_ability_visible_test" ] +} diff --git a/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0568a45989f836c8581b5a059de001174865cd98 --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp @@ -0,0 +1,1261 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "module_test_dump_util.h" +#include "st_ability_util.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "common_event.h" +#include "common_event_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using namespace OHOS::EventFwk; + +namespace { +using MAP_STR_STR = std::map; +std::vector bundleNameSuffix = {"PageA", "ServiceB"}; +static const std::string bundleNameBase = "com.ohos.amsst.appAbilityVisible"; +static const std::string hapNameBase = "amsAbilityVisibleTest"; +static const std::string abilityNameBase = "AmsAbilityVisibleTest"; +static const std::string launcherBundle = "com.ohos.launcher"; +static const std::string launcherAbility = "com.ohos.launcher.MainAbility"; +static const std::string systemUiBundle = "com.ohos.systemui"; +static const std::string terminateAbility = "requ_page_ability_terminate"; +static const std::string terminateAbilityCaller = "requ_page_ability_terminate_caller"; +static const std::string disconnectService = "requ_disconnect_service"; +static const std::string terminateAbilityResult = "requ_page_ability_terminate_result"; + +static const std::string DUMP_STACK_LIST = "--stack-list"; +static const std::string DUMP_SERVICE = "--serv"; +static const std::string DUMP_DATA = "--data"; +static const std::string DUMP_STACK = "--stack"; +static const std::string DUMP_MISSION = "--mission"; +static const std::string DUMP_TOP = "--top"; +static const std::string DUMP_ALL = "-a"; +static const std::string abilityStateInit = ":Init"; +static const std::string abilityStateOnStart = ":OnStart"; +static const std::string abilityStateOnStop = ":OnStop"; +static const std::string abilityStateOnActive = ":OnActive"; +static const std::string abilityStateOnInactive = ":OnInactive"; +static const std::string abilityStateOnBackground = ":OnBackground"; +static const std::string abilityStateOnForeground = ":OnForeground"; +static const std::string abilityStateOnNewWant = ":OnNewWant"; +static const std::string abilityStateOnCommand = ":OnCommand"; +static const std::string abilityStateOnConnect = ":OnConnect"; +static const std::string abilityStateOnDisconnect = ":OnDisconnect"; +static const std::string abilityStateInsert = ":Insert"; +static const std::string abilityStateDelete = ":Delete"; +static const std::string abilityStateUpdate = ":Update"; +static const std::string abilityStateQuery = ":Query"; +static const std::string abilityStateGetFileTypes = ":GetFileTypes"; +static const std::string abilityStateOpenFile = ":OpenFile"; +static const std::string getWantAgentState = ":GetWantAgentFail"; +static const std::string triggerWantAgentState = ":TriggerWantAgentSuccess"; +static const int abilityStateCountOne = 1; +static const int abilityStateCountTwo = 2; +enum AbilityState_Test { + INITIAL = 0, + INACTIVE, + ACTIVE, + BACKGROUND, + SUSPENDED, + INACTIVATING, + ACTIVATING, + MOVING_BACKGROUND, + TERMINATING, + ALLSUM, +}; +static const std::vector abilityStateVec = { + "INITIAL", + "INACTIVE", + "ACTIVE", + "BACKGROUND", + "SUSPENDED", + "INACTIVATING", + "ACTIVATING", + "MOVING_BACKGROUND", + "TERMINATING", +}; +} // namespace +class AppEventSubscriber; + +class AmsAbilityVisibleTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static std::vector GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs); + static bool SubscribeEvent(); + void ShowDump(); + static void CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState); + void ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, + const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = (DUMP_STACK + " 1")); + void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum, const std::string &type = "-a"); + void ExpectServiceAbilityNumInStack(const std::string &abilityName, int abilityNum); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + {} + virtual ~AppEventSubscriber() + {} + virtual void OnReceiveEvent(const CommonEventData &data) override; + }; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityConnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + resultConnectCode = resultCode; + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + resultConnectCode = resultCode; + } + + static size_t onAbilityConnectDoneCount; + static int resultConnectCode; + }; + static sptr appMs_; + static sptr abilityMs_; + static STtools::Event event_; + static std::shared_ptr subscriber_; +}; + +sptr AmsAbilityVisibleTest::appMs_ = nullptr; +sptr AmsAbilityVisibleTest::abilityMs_ = nullptr; +STtools::Event AmsAbilityVisibleTest::event_ = STtools::Event(); +std::shared_ptr AmsAbilityVisibleTest::subscriber_ = nullptr; +size_t AmsAbilityVisibleTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +int AmsAbilityVisibleTest::AbilityConnectCallback::resultConnectCode = 0; + +void AmsAbilityVisibleTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::SetUpTestCase(void)"; + + SubscribeEvent(); + appMs_ = STAbilityUtil::GetAppMgrService(); + abilityMs_ = STAbilityUtil::GetAbilityManagerService(); + if (appMs_) { + int freeTime = 60; + appMs_->SetAppFreezingTime(freeTime); + int time = 0; + appMs_->GetAppFreezingTime(time); + std::cout << "appMs_->GetAppFreezingTime();" << time << std::endl; + } +} + +void AmsAbilityVisibleTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::TearDownTestCase(void)"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsAbilityVisibleTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::SetUp(void)"; + std::vector hapNames = GetBundleNames(hapNameBase, bundleNameSuffix); + STAbilityUtil::InstallHaps(hapNames); +} + +void AmsAbilityVisibleTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::TearDown(void)"; + std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); + STAbilityUtil::UninstallBundle(bundleNames); + + STAbilityUtil::CleanMsg(event_); +} + +std::vector AmsAbilityVisibleTest::GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs) +{ + std::vector bundleNames; + for (auto strSuffix : strSuffixs) { + bundleNames.push_back(strBase + strSuffix); + } + return bundleNames; +} + +bool AmsAbilityVisibleTest::SubscribeEvent() +{ + std::vector eventList = {"resp_st_page_ability_callback"}; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsAbilityVisibleTest::ShowDump() +{ + if (abilityMs_) { + std::vector dumpInfo; + abilityMs_->DumpState("-a", dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + dumpInfo.clear(); + abilityMs_->DumpState(DUMP_SERVICE, dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + dumpInfo.clear(); + abilityMs_->DumpState(DUMP_DATA, dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + } +} + +void AmsAbilityVisibleTest::CheckAbilityStateByName(const std::string &abilityName, + const std::vector &info, const std::string &state, const std::string &midState) +{ + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", info, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + // ability exist + EXPECT_NE(pos, result.end()); + MTDumpUtil::GetInstance()->GetAll("State", info, result); + EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } + // ability state + if (midState != "") { + bool compareResult = ((*pos == state) || (*pos == midState)); + EXPECT_EQ(1, compareResult); + } else { + EXPECT_EQ(*pos, state); + } +} + +void AmsAbilityVisibleTest::ExpectAbilityCurrentState(const std::string &abilityName, + const AbilityState_Test ¤tState, const AbilityState_Test &midState, const std::string &args) +{ + std::string strCurrentState = abilityStateVec.at(currentState); + std::string strMidState = ""; + if (midState != AbilityState_Test::ALLSUM) { + strMidState = abilityStateVec.at(midState); + } + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(args, dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, strCurrentState, strMidState); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsAbilityVisibleTest::ExpectAbilityNumInStack( + const std::string &abilityName, int abilityNum, const std::string &type) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(type, dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsAbilityVisibleTest::ExpectServiceAbilityNumInStack(const std::string &abilityName, int abilityNum) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(DUMP_SERVICE, dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsAbilityVisibleTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + std::string eventName = data.GetWant().GetAction(); + if (eventName == "resp_st_page_ability_callback") { + std::string target = data.GetData(); + STAbilityUtil::Completed(event_, target, data.GetCode()); + } +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0100 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : The test process starts an ability whose visible attribute is false + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0100 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + ErrCode result = STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(result, ABILITY_VISIBLE_FALSE_DENY_REQUEST); + + ExpectAbilityNumInStack(abilityName, 0); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0100 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0200 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : The test process starts an ability, + * and the visible attribute of the ability is the default value. + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0200, TestSize.Level2) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0200 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA4"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + ErrCode result = STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(result, ABILITY_VISIBLE_FALSE_DENY_REQUEST); + + ExpectAbilityNumInStack(abilityName, 0); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0200 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0300 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : The test process starts an ability whose visible attribute is true + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0300 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0300 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0400 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA1) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA1 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0400 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0400 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0500 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA3,type:singleton) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA3 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0500 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0500 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0600 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageB1) whose visible attribute is false + * 3.PageA2 has the different bundleName as PageB1 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0600 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0600 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0700 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageB2) whose visible attribute is true + * 3.PageA2 has the different bundleName as PageB2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0700 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0700 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0800 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts a Service ability(Service) whose visible attribute is false + * 3.PageA2 has the different bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0800, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0800 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0800 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0900 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) starts a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0900 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0900 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1000 + * @tc.name : Visible attribute impact on ConnectAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageA2 has the different bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1000 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Service"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1000 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1100 + * @tc.name : Visible attribute impact on ConnectAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1100 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Service"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnConnect, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1100 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1200 + * @tc.name : Visible attribute impact on start dataAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) start a Data ability(Data) whose visible attribute is false + * 3.PageA2 has the different bundleName as Data + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1200 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Data"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Data"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_DATA); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1200 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1300 + * @tc.name : Visible attribute impact on start dataAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a Data ability(Data) whose visible attribute is false + * 3.PageB2 has the same bundleName as Data + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1300 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Data"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Data"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateInsert, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_DATA); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1300 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1400 + * @tc.name : Visible attribute impact on terminateAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA3,type:singleton) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA3 + * 4.terminate PageA3 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1400 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1400 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1500 + * @tc.name : Visible attribute impact on terminateAbilityCaller + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA3,type:singleton) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA3 + * 4.terminateCaller PageA2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1500 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbilityCaller, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1500 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1600 + * @tc.name : Visible attribute impact on terminateAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.terminate Service and PageB2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1600 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName, 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1600 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1700 + * @tc.name : Visible attribute impact on terminateAbilityCaller + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.The ability(Service) start a Service ability(ServiceA1) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service and ServiceA1 + * 4.terminateCaller Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1700 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + std::string abilityName3 = abilityNameBase + "ServiceA1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2 + "," + bundleName2; + params["targetAbility"] = abilityName2 + "," + abilityName3; + params["type"] = "Service,Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnConnect, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityNumInStack(abilityName3, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbilityCaller, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1700 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1800 + * @tc.name : Visible attribute impact on terminateAbilityResult + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.terminateAbilityResult Service and terminateAbility PageB2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1800, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1800 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = 1; + STAbilityUtil::PublishEvent(terminateAbilityResult, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName, 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1800 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1900 + * @tc.name : Visible attribute impact on disconnectService + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.disconnectService Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1900 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Service"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnConnect, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = 0; + STAbilityUtil::PublishEvent(disconnectService, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnDisconnect, abilityStateCountOne), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1900 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2000 + * @tc.name : Visible attribute impact on data Release + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a data ability(Data) whose visible attribute is false + * 3.PageB2 has the same bundleName as Data + * 4.Release Data + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2000 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Data"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "DataRelease"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateInsert, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_DATA); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2000 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2100 + * @tc.name : Visible attribute impact on terminateAbilityCaller + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.terminateCaller Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2100 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbilityCaller, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2100 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2200 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability(PageA1) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA1 + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2200 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentPageAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2200 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2300 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability(PageB1) whose visible attribute is false + * 3.PageA2 has the different bundleName as PageB1 + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2300 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentPageAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2300 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2400 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability(PageB2) whose visible attribute is true + * 3.PageA2 has the different bundleName as PageB2 + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2400 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentPageAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ShowDump(); + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2400 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2500 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability whose visible attribute is false + * 3.PageA2 has the different bundleName as Service + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2500 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentServiceAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2500 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2600 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) get the wantagent to starts an ability whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2600 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentServiceAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2600 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn b/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..57f0d3ac76adfc789f13a282b61fccb55f8d7c13 --- /dev/null +++ b/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_app_process_manage_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_app_process_manage_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + resource_config_file = "//foundation/appexecfwk/standard/test/resource/mstbundlemgrservice/ohos_test.xml" +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_app_process_manage_test" ] +} diff --git a/test/systemtest/common/ams/ams_app_process_manage_test/ams_app_process_manage_test.cpp b/test/systemtest/common/ams/ams_app_process_manage_test/ams_app_process_manage_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1b1e6c18155eaf1b74b52b067f288136a5aa447 --- /dev/null +++ b/test/systemtest/common/ams/ams_app_process_manage_test/ams_app_process_manage_test.cpp @@ -0,0 +1,1031 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "module_test_dump_util.h" +#include "st_ability_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "common_event.h" +#include "common_event_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using namespace OHOS::EventFwk; + +namespace { +using MAP_STR_STR = std::map; +std::vector bundleNameSuffix = {"A", "B", "C"}; +std::string bundleNameBase = "com.ohos.amsst.app"; +std::string hapNameBase = "amsSystemTest"; +std::string abilityNameBase = "AmsStAbility"; +std::string launcherBundle = "com.ohos.launcher"; +std::string systemUiBundle = "com.ohos.systemui"; +static const std::string DUMP_STACK_LIST = "--stack-list"; +static const std::string DUMP_STACK = "--stack"; +static const std::string DUMP_MISSION = "--mission"; +static const std::string DUMP_TOP = "--top"; +constexpr int WAIT_TIME = 3 * 1000; +constexpr int WAIT_LAUNCHER_OK = 5 * 1000; +static const std::string abilityStateOnStart = ":OnStart"; +static const std::string abilityStateOnStop = ":OnStop"; +static const std::string abilityStateOnActive = ":OnActive"; +static const std::string abilityStateOnInactive = ":OnInactive"; +static const std::string abilityStateOnBackground = ":OnBackground"; +static const std::string abilityStateOnForeground = ":OnForeground"; +static const std::string abilityStateOnNewWant = ":OnNewWant"; +static const int abilityStateCountOne = 1; +static const int abilityStateCountTwo = 2; +constexpr int appFreezingTime = 60; +} // namespace +class AppEventSubscriber; + +class AmsAppProcessManageTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static std::vector GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs); + static bool SubscribeEvent(); + void ClearSystem(); + void ShowDump(); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + {} + virtual ~AppEventSubscriber() + {} + virtual void OnReceiveEvent(const CommonEventData &data) override; + }; + static sptr appMs_; + static sptr abilityMs_; + static STtools::Event event_; + static std::shared_ptr subscriber_; +}; + +sptr AmsAppProcessManageTest::appMs_ = nullptr; +sptr AmsAppProcessManageTest::abilityMs_ = nullptr; +STtools::Event AmsAppProcessManageTest::event_ = STtools::Event(); +std::shared_ptr AmsAppProcessManageTest::subscriber_ = nullptr; + +void AmsAppProcessManageTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsAppProcessManageTest::SetUpTestCase(void)"; + std::vector hapNames = GetBundleNames(hapNameBase, bundleNameSuffix); + STAbilityUtil::InstallHaps(hapNames); + SubscribeEvent(); + appMs_ = STAbilityUtil::GetAppMgrService(); + abilityMs_ = STAbilityUtil::GetAbilityManagerService(); + if (appMs_) { + appMs_->SetAppFreezingTime(appFreezingTime); + int time = 0; + appMs_->GetAppFreezingTime(time); + std::cout << "appMs_->GetAppFreezingTime();" << time << std::endl; + } +} + +void AmsAppProcessManageTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsAppProcessManageTest::TearDownTestCase(void)"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); + STAbilityUtil::UninstallBundle(bundleNames); +} + +void AmsAppProcessManageTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "void AmsAppProcessManageTest::SetUp(void)"; +} + +void AmsAppProcessManageTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "void AmsAppProcessManageTest::TearDown(void)"; + STAbilityUtil::RemoveStack(1, abilityMs_, WAIT_TIME, WAIT_LAUNCHER_OK); + std::vector vecBundleName; + for (const auto &suffix : bundleNameSuffix) { + vecBundleName.push_back(bundleNameBase + suffix); + } + STAbilityUtil::KillBundleProcess(vecBundleName); + + STAbilityUtil::CleanMsg(event_); +} + +std::vector AmsAppProcessManageTest::GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs) +{ + std::vector bundleNames; + for (auto strSuffix : strSuffixs) { + bundleNames.push_back(strBase + strSuffix); + } + return bundleNames; +} + +bool AmsAppProcessManageTest::SubscribeEvent() +{ + std::vector eventList = {"resp_st_page_ability_callback"}; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsAppProcessManageTest::ClearSystem() +{ + STAbilityUtil::KillService("appspawn"); + STAbilityUtil::KillService("installs"); + STAbilityUtil::KillService(launcherBundle); + STAbilityUtil::KillService(systemUiBundle); + STAbilityUtil::KillService("foundation"); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LAUNCHER_OK)); +} + +void AmsAppProcessManageTest::ShowDump() +{ + std::vector dumpInfo; + abilityMs_->DumpState("-a", dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } +} + +void AmsAppProcessManageTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + std::string eventName = data.GetWant().GetAction(); + if (eventName == "resp_st_page_ability_callback") { + std::string target = data.GetData(); + STAbilityUtil::Completed(event_, target, data.GetCode()); + } +} + +/* + * @tc.number : AMS_App_Process_0100 + * @tc.name : create app process successfully by starting ability,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.determine process Info + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0100 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string hapName = hapNameBase + "A"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_); + EXPECT_TRUE(pInfo.pid_ > 0); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0100 end"; +} + +/* + * @tc.number : AMS_App_Process_0200 + * @tc.name : create multiple app process successfully by starting ability,launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start page ability B1 by A1 onActive function + * 3.start ENTITY_HOME + * 4.wait for the event sent by the page ability + * 5.determine process status + * 6.start page ability A1 + * 7.wait for the event sent by the page ability + * 8.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0200 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + MAP_STR_STR params; + params["targetBundle"] = bundleNameBase + "B"; + params["targetAbility"] = abilityNameBase + "B1"; + + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + MAP_STR_STR params1; + Want want2 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params1); + + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + RunningProcessInfo pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo1.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo1.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo2.state_); + ShowDump(); + + STAbilityUtil::StartAbility(want2, abilityMs_); + ShowDump(); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo1.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo1.state_); + pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo2.state_); + EXPECT_TRUE(pInfo2.pid_ != pInfo1.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0200 end"; +} + +/* + * @tc.number : AMS_App_Process_0300 + * @tc.name : not create new app process when app process started,launchtype[A1,A2:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.determine process Info + * 4.start a page ability A2 + * 5.wait for the event sent by the page ability + * 6.determine process Info + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0300 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string abilityName2 = abilityNameBase + "A2"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_); + EXPECT_TRUE(pInfo.pid_ > 0); + + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + // start the same abilty again + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_); + EXPECT_EQ(pInfo.pid_, pInfo2.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0300 end"; +} + +/* + * @tc.number : AMS_App_Process_0400 + * @tc.name : kill app process that is running,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.determine process Info + * 4.kill current Application + * 5.determine process Info and dump stack info + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0400 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_); + EXPECT_TRUE(pInfo.pid_ > 0); + + STAbilityUtil::KillApplication(bundleName, appMs_, WAIT_TIME); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_); + EXPECT_EQ(0, pInfo2.pid_); + + std::vector dumpInfo; + abilityMs_->DumpState(DUMP_STACK + " 1", dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + EXPECT_NE(pos, result.end()); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0400 end"; +} + +/* + * @tc.number : AMS_App_Process_0500 + * @tc.name : kill app process that do not exist,launchtype[A1:singletop] + * @tc.desc : 1.determine process Info + * 2.kill current Application + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0500 start"; + + std::string bundleName = bundleNameBase + "A"; + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_); + EXPECT_TRUE(pInfo.pid_ == 0); + + STAbilityUtil::KillApplication(bundleName, appMs_, WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0500 end"; +} + +/* + * @tc.number : AMS_App_Process_0600 + * @tc.name : create multiple app process successfully by starting ability,launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.determine process Info + * 4.start a page ability B1 + * 5.wait for the event sent by the page ability + * 6.determine process Info + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0600 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo.pid_ > 0); + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_TRUE(pInfo2.pid_ != pInfo.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0600 end"; +} + +/* + * @tc.number : AMS_App_Process_0700 + * @tc.name : kill app process when all abilities of this app is terminated,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.A1 terminated by A1 OnActive + * 3.wait for the event sent by the page ability + * 4.determine process Info + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0700 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + params["shouldReturn"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(pInfo.pid_, 0); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0700 end"; +} + +/* + * @tc.number : AMS_App_Process_0800 + * @tc.name : app process state transition to background when HOME key pressed,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.start ENTITY_HOME + * 4.wait for the event sent by the page ability + * 5.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0800, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0800 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0800 end"; +} + +/* + * @tc.number : AMS_App_Process_0900 + * @tc.name : app process state transition to background when another app started, + * launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.start a page ability B1 + * 4.wait for the event sent by the page ability + * 5.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_0900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0900 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_0900 end"; +} + +/* + * @tc.number : AMS_App_Process_1000 + * @tc.name : app process state transition to background when it starts another app, + * launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start a page ability B1 by A1 OnActive + * 3.wait for the event sent by the page ability + * 4.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1000 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1000 end"; +} + +/* + * @tc.number : AMS_App_Process_1100 + * @tc.name : app process state transition to foreground when restarted,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.determine process status + * 4.start ENTITY_HOME + * 5.wait for the event sent by the page ability + * 6.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1100 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(launcherBundle, appMs_); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + pInfo = STAbilityUtil::GetAppProcessInfoByName(launcherBundle, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + // restart + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1100 end"; +} + +/* + * @tc.number : AMS_App_Process_1200 + * @tc.name : restart app after kill app process,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.determine process status + * 4.kill current Application + * 5.start a page ability A1 + * 6.wait for the event sent by the page ability + * 7.determine process status and determine process info + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1200 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + STAbilityUtil::KillApplication(bundleName, appMs_, WAIT_TIME); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo2.state_); + // new process + EXPECT_NE(pInfo.pid_, pInfo2.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1200 end"; +} + +/* + * @tc.number : AMS_App_Process_1300 + * @tc.name : kill background app process,launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.determine process status + * 4.kill current Application + * 5.start a page ability A1 + * 6.wait for the event sent by the page ability + * 7.determine process status and determine process info + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1300 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + + STAbilityUtil::KillApplication(bundleName, appMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(0, pInfo2.pid_); + RunningProcessInfo pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(0, pInfo1.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1300 end"; +} + +/* + * @tc.number : AMS_App_Process_1400 + * @tc.name : verify process management when start abnormal app(onStart exception),launchtype[K1:singletop] + * @tc.desc : 1.start a page ability K1 + * 2.determine process info + * 3.get AbilityRecordId + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1400 start"; + + std::string bundleName = bundleNameBase + "K"; + std::string abilityName = "AmsStAbilityErrorK1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_, WAIT_TIME); + // when app collapse in OnStart, app process should be terminated? + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(0, pInfo.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1400 end"; +} + +/* + * @tc.number : AMS_App_Process_1500 + * @tc.name : create multiple app process successfully by starting ability,launchtype[A1,B1:singletop] + * @tc.desc : 1.start page ability A1,B1,A1,B1,A1 in turn + * 2.wait for the event sent by the page ability + * 3.determine process status + * 4.start a page ability B1 + * 5.wait for the event sent by the page ability + * 6.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1500 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + MAP_STR_STR params; + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + RunningProcessInfo pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo1.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo1.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo2.state_); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo1.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo1.state_); + pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo2.state_); + + EXPECT_TRUE(pInfo2.pid_ != pInfo1.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1500 end"; +} + +/* + * @tc.number : AMS_App_Process_1600 + * @tc.name : create multiple app process successfully by starting ability,launchtype[A1,B1:singletop] + * @tc.desc : 1.start page ability A1 + * 2.start page ability B1 by A1 OnActive + * 3.wait for the event sent by the page ability + * 4.determine process status + * 4.start a page ability A1 + * 5.wait for the event sent by the page ability + * 6.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1600 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + MAP_STR_STR params; + params["targetBundle"] = bundleNameBase + "B"; + params["targetAbility"] = abilityNameBase + "B1"; + + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + params.clear(); + Want want2 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::CleanMsg(event_); + RunningProcessInfo pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo1.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo1.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo2.state_); + + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo1.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo1.state_); + pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo2.state_); + + EXPECT_TRUE(pInfo2.pid_ != pInfo1.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1600 end"; +} + +/* + * @tc.number : AMS_App_Process_1700 + * @tc.name : verify process status,switch the ability status of different bundlename, + * launchtype[A1,B1:singletop] + * @tc.desc : 1.start page ability A1,B1,ENTITY_HOME,A1 in turn + * 2.wait for the event sent by the page ability + * 3.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1700 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + MAP_STR_STR params; + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo2.state_); + // new process + EXPECT_NE(pInfo.pid_, pInfo2.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1700 end"; +} + +/* + * @tc.number : AMS_App_Process_1800 + * @tc.name : verify process status,switch the ability status of different bundlename, + * launchtype[A1,B1:singletop] + * @tc.desc : 1.start page ability A1,ENTITY_HOME,B1,ENTITY_HOME,B1 in turn + * 2.wait for the event sent by the page ability + * 3.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1800, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1800 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + MAP_STR_STR params; + + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo2.state_); + // new process + EXPECT_NE(pInfo.pid_, pInfo2.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1800 end"; +} + +/* + * @tc.number : AMS_App_Process_1900 + * @tc.name : verify process status,switch the ability status of different bundlename, + * launchtype[A1,B1,A2:singletop] + * @tc.desc : 1.start page ability A1,B1,ENTITY_HOME,A2 in turn + * 2.wait for the event sent by the page ability + * 3.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_1900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1900 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + std::string abilityName3 = abilityNameBase + "A2"; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + MAP_STR_STR params; + + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName, params); + + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want3, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo2.state_); + // new process + EXPECT_NE(pInfo.pid_, pInfo2.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_1900 end"; +} + +/* + * @tc.number : AMS_App_Process_2000 + * @tc.name : verify process status,switch the ability status of different bundlename, + * launchtype[A1,B1,A2:singletop] + * @tc.desc : 1.start page ability B1,A1,ENTITY_HOME,A2 in turn + * 2.wait for the event sent by the page ability + * 3.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_2000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_2000 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + std::string abilityName3 = abilityNameBase + "A2"; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + MAP_STR_STR params; + + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName, params); + + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want3, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo2.state_); + // new process + EXPECT_NE(pInfo.pid_, pInfo2.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_2000 end"; +} + +/* + * @tc.number : AMS_App_Process_2100 + * @tc.name : verify process status,switch the ability status of different bundlename, + * launchtype[A1,B1:singletop] + * @tc.desc : 1.start page ability A1,B1,ENTITY_HOME,A1 in turn + * 2.wait for the event sent by the page ability + * 3.determine process status + */ +HWTEST_F(AmsAppProcessManageTest, AMS_App_Process_2100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_2100 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + MAP_STR_STR params; + Want want1 = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want1, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo2.state_); + // new process + EXPECT_NE(pInfo.pid_, pInfo2.pid_); + + GTEST_LOG_(INFO) << "AmsAppProcessManageTest AMS_App_Process_2100 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_check_service/BUILD.gn b/test/systemtest/common/ams/ams_check_service/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..5fe6972849d6ad45acd73729b93ad59f1ff148b7 --- /dev/null +++ b/test/systemtest/common/ams/ams_check_service/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams/" + +config("ams_check_service_config") { + include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_systemtest("ams_check_service") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "access_control_check.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_config", + ":ams_check_service_config", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/:system_test_ability_util_config", + "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + deps = [ ":ams_check_service" ] +} diff --git a/test/systemtest/common/ams/ams_check_service/access_control_check.cpp b/test/systemtest/common/ams/ams_check_service/access_control_check.cpp new file mode 100755 index 0000000000000000000000000000000000000000..7e88c5bbc06ee6ae11b8414418a47a218a6e72b8 --- /dev/null +++ b/test/systemtest/common/ams/ams_check_service/access_control_check.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_manager_service.h" +#include "app_mgr_service.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using namespace testing::ext; +class AccessControlCheck : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static sptr abilityMs_; + static sptr appMs_; +}; + +sptr AccessControlCheck::abilityMs_ = nullptr; +sptr AccessControlCheck::appMs_ = nullptr; + +void AccessControlCheck::SetUpTestCase(void) {} +void AccessControlCheck::TearDownTestCase(void) {} +void AccessControlCheck::SetUp() {} +void AccessControlCheck::TearDown() {} + +/** + * @tc.number : Access_Control_Check_0100 + * @tc.name : check whether abilityManagerService is running + * @tc.desc : check whether abilityManagerService is running + */ +HWTEST_F(AccessControlCheck, Access_Control_Check_0100, Function | MediumTest | Level0) +{ + sptr abilityMgrRemoteObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + EXPECT_TRUE(abilityMgrRemoteObj != nullptr); + if (abilityMgrRemoteObj == nullptr) { + GTEST_LOG_(INFO) << "SaMgrClient::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID) failed."; + return; + } + sptr abilityManager = iface_cast(abilityMgrRemoteObj); + EXPECT_TRUE(abilityManager != nullptr); + if (abilityManager == nullptr) { + GTEST_LOG_(INFO) << "iface_cast(abilityMgrRemoteObj) failed."; + return; + } + StackInfo stackInfo; + EXPECT_TRUE(abilityManager->GetAllStackInfo(stackInfo) == ERR_OK); + EXPECT_TRUE(stackInfo.missionStackInfos.size() > 0); +} + +/** + * @tc.number : Access_Control_Check_0200 + * @tc.name : check whether appManagerService is running + * @tc.desc : check whether appManagerService is running + */ +HWTEST_F(AccessControlCheck, Access_Control_Check_0200, Function | MediumTest | Level0) +{ + sptr appMgrRemoteObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); + EXPECT_TRUE(appMgrRemoteObj != nullptr); + if (appMgrRemoteObj == nullptr) { + GTEST_LOG_(INFO) << "SaMgrClient::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID) failed."; + return; + } + sptr appManager = iface_cast(appMgrRemoteObj); + EXPECT_TRUE(appManager != nullptr); + if (appManager == nullptr) { + GTEST_LOG_(INFO) << "iface_cast(appMgrRemoteObj) failed."; + return; + } + std::vector info; + EXPECT_TRUE(appManager->GetAllRunningProcesses(info) == ERR_OK); + EXPECT_TRUE(info.size() > 0); + std::string launcherBundle = "com.ohos.launcher"; + bool isLauncherExist = false; + for (auto process : info) { + if (process.processName_ == launcherBundle) { + isLauncherExist = true; + break; + } + } + EXPECT_TRUE(isLauncherExist); +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_configuration_updated_test/BUILD.gn b/test/systemtest/common/ams/ams_configuration_updated_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..0b0b0fbc54a5fe6a14aa9f1b1cee5a1a971dcdb4 --- /dev/null +++ b/test/systemtest/common/ams/ams_configuration_updated_test/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_configuration_updated_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_configuration_updated_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_configuration_updated_test" ] +} diff --git a/test/systemtest/common/ams/ams_configuration_updated_test/ams_configuration_updated_test.cpp b/test/systemtest/common/ams/ams_configuration_updated_test/ams_configuration_updated_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..451b7f235a9e6fa072000d0fb4b88f60db8b9f2a --- /dev/null +++ b/test/systemtest/common/ams/ams_configuration_updated_test/ams_configuration_updated_test.cpp @@ -0,0 +1,561 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "ability_append_test_info.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "configuration.h" +#include "hilog_wrapper.h" +#include "stoperator.h" +#include "st_ability_util.h" +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; + +using MAP_STR_STR = std::map; +namespace { +static const string KIT_BUNDLE_NAME = "com.ohos.amsst.ConfigurationUpdated"; +static const string KIT_SECOND_BUNDLE_NAME = "com.ohos.amsst.ConfigurationUpdatedSingleton"; +static const string KIT_HAP_NAME = "amsConfigurationUpdatedTest"; +static const string KIT_SECOND_HAP_NAME = "amsConfigurationUpdatedSingletonTest"; +static const string MAIN_ABILITY = "MainAbility"; +static const string SECOND_ABILITY = "SecondAbility"; +static constexpr int WAIT_TIME = 1; +static constexpr int WAIT_LAUNCHER_TIME = 5; +static constexpr int WAIT_SETUP_TIME = 1; +static constexpr int WAIT_TEARDOWN_TIME = 1; +static constexpr int WAIT_ONACTIVE_TIME = 1; +static constexpr int WAIT_BLOCKUPDATE_TIME = 7; +static constexpr int TEST_TIMES = 10; +static string g_eventMessage = ""; +static string g_tempDataStr = ""; +static int g_mainAbilityUpdateTimes = 0; +static int g_secondAbilityUpdateTimes = 0; +static int g_thirdAbilityUpdateTimes = 0; +std::string ConfigurationUpdate_Event_Resp_A = "resp_com_ohos_amsst_ConfigurationUpdateB"; +} // namespace + +std::vector eventList = { + g_EVENT_RESP_MAIN_LIFECYCLE, +}; + +class AmsConfigurationUpdatedTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + void SetDefaultConfig(); + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber(){}; + }; + + static sptr abilityMgrService; + static Event event; + static std::shared_ptr subscriber_; +}; + +Event AmsConfigurationUpdatedTest::event = Event(); +sptr AmsConfigurationUpdatedTest::abilityMgrService = nullptr; +std::shared_ptr AmsConfigurationUpdatedTest::subscriber_ = nullptr; + +void AmsConfigurationUpdatedTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "\nOnReceiveEvent: event====>" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "\nOnReceiveEvent: data=====>" << data.GetData(); + GTEST_LOG_(INFO) << "\nOnReceiveEvent: code=====>" << data.GetCode(); + if (data.GetData() == "Updated") { + switch (data.GetCode()) { + case MAIN_ABILITY_CODE: + g_mainAbilityUpdateTimes++; + break; + case SECOND_ABILITY_CODE: + g_secondAbilityUpdateTimes++; + break; + case THIRD_ABILITY_CODE: + g_thirdAbilityUpdateTimes++; + break; + default: + break; + } + } + if (find(eventList.begin(), eventList.end(), data.GetWant().GetAction()) != eventList.end()) { + TestCompleted(event, data.GetData(), data.GetCode()); + } +} + +int AmsConfigurationUpdatedTest::TestWaitCompleted( + Event &event, const std::string &eventName, const int code, const int timeout) +{ + GTEST_LOG_(INFO) << "---------->\n\nTestWaitCompleted ====>: " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} + +void AmsConfigurationUpdatedTest::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + GTEST_LOG_(INFO) << "----------<\nTestCompleted ====>: " << eventName << " " << code << "\n"; + return STAbilityUtil::Completed(event, eventName, code); +} + +void AmsConfigurationUpdatedTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "\nSubscribeEvent error====<"; + } +} + +void AmsConfigurationUpdatedTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsConfigurationUpdatedTest::SetUp(void) +{ + STAbilityUtil::Install(KIT_HAP_NAME); + sleep(WAIT_SETUP_TIME); + STAbilityUtil::Install(KIT_SECOND_HAP_NAME); + sleep(WAIT_SETUP_TIME); + STAbilityUtil::CleanMsg(event); +} + +void AmsConfigurationUpdatedTest::TearDown(void) +{ + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME); + sleep(WAIT_TEARDOWN_TIME); + STAbilityUtil::Uninstall(KIT_SECOND_BUNDLE_NAME); + sleep(WAIT_TEARDOWN_TIME); + STAbilityUtil::CleanMsg(event); +} + +bool AmsConfigurationUpdatedTest::SubscribeEvent() +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsConfigurationUpdatedTest::SetDefaultConfig() +{ + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "ZH-HANS"); + abilityMgrService->UpdateConfiguration(configuration); + (void)TestWaitCompleted(event, "Updated", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME); + + AppExecFwk::Configuration configuration2; + configuration2.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "vertical"); + abilityMgrService->UpdateConfiguration(configuration2); + (void)TestWaitCompleted(event, "Updated", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME); + STAbilityUtil::CleanMsg(event); +} + +/** + * @tc.number : 0100 + * @tc.name : AMS_UpdateConfiguration_0100 + * @tc.desc : Verify whether the results of the orientation function of the system configuration concerned by + * capability are correct. + */ +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0100 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + SetDefaultConfig(); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "fr_FR"); + abilityMgrService->UpdateConfiguration(configuration); + g_tempDataStr = "Updated"; + EXPECT_EQ(TestWaitCompleted(event, "fr_FR", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0100 end=========<"; +} + +/** + * @tc.number : 0200 + * @tc.name : AMS_UpdateConfiguration_0200 + * @tc.desc : Verify whether the results of the orientation, locale function of the system configuration concerned + * by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0200 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + SetDefaultConfig(); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "ZH-HANS"); + abilityMgrService->UpdateConfiguration(configuration); + EXPECT_NE(TestWaitCompleted(event, "Updated", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0200 end=========<"; +} + +/** + * @tc.number : 0300 + * @tc.name : AMS_UpdateConfiguration_0300 + * @tc.desc : Verify whether the results of the orientation, locale, layout function of the system configuration + * concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0300 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + SetDefaultConfig(); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "horizontal"); + abilityMgrService->UpdateConfiguration(configuration); + EXPECT_EQ(TestWaitCompleted(event, "horizontal", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0300 end=========<"; +} + +/** + * @tc.number : 0400 + * @tc.name : AMS_UpdateConfiguration_0400 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system + * configuration concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0400 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + SetDefaultConfig(); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "vertical"); + abilityMgrService->UpdateConfiguration(configuration); + + g_tempDataStr = "Updated"; + EXPECT_NE(TestWaitCompleted(event, "Updated", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0400 end=========<"; +} + +/** + * @tc.number : 0500 + * @tc.name : AMS_UpdateConfiguration_0500 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system + * configuration concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0500 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + SetDefaultConfig(); + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN, MAIN_ABILITY_CODE, "StartNextAbility"); + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + Want want2 = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_SECOND_BUNDLE_NAME, params); + eCode = STAbilityUtil::StartAbility(want2, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartSecondApp,ThirdAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "fr_FR"); + abilityMgrService->UpdateConfiguration(configuration); + EXPECT_EQ(TestWaitCompleted(event, "fr_FR", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "fr_FR", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "fr_FR", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0500 end=========<"; +} + +/** + * @tc.number : 0600 + * @tc.name : AMS_UpdateConfiguration_0600 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system + * configuration concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0600 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + SetDefaultConfig(); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN, MAIN_ABILITY_CODE, "StartNextAbility"); + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + Want want2 = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_SECOND_BUNDLE_NAME, params); + eCode = STAbilityUtil::StartAbility(want2, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartSecondAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "horizontal"); + abilityMgrService->UpdateConfiguration(configuration); + EXPECT_EQ(TestWaitCompleted(event, "horizontal", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "horizontal", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "horizontal", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0600 end=========<"; +} + +/** + * @tc.number : 0700 + * @tc.name : AMS_UpdateConfiguration_0700 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system + * configuration concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0700 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + SetDefaultConfig(); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN, MAIN_ABILITY_CODE, "StartNextAbilityWithBlockFlag"); + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + Want want2 = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_SECOND_BUNDLE_NAME, params); + eCode = STAbilityUtil::StartAbility(want2, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartSecondApp,ThirdAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "fr_FR"); + GTEST_LOG_(INFO) << "\nUpdateConfiguration First Time ====>> "; + abilityMgrService->UpdateConfiguration(configuration); + AppExecFwk::Configuration configuration2; + configuration2.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "en_US"); + GTEST_LOG_(INFO) << "\nUpdateConfiguration Second Time ====>> "; + abilityMgrService->UpdateConfiguration(configuration2); + + EXPECT_EQ(TestWaitCompleted(event, "fr_FR", THIRD_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "fr_FR", SECOND_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "fr_FR", MAIN_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + + EXPECT_EQ(TestWaitCompleted(event, "en_US", THIRD_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "en_US", SECOND_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "en_US", MAIN_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0700 end=========<"; +} + +/** + * @tc.number : 0800 + * @tc.name : AMS_UpdateConfiguration_0800 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system + * configuration concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0800 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + SetDefaultConfig(); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN, MAIN_ABILITY_CODE, "StartNextAbilityWithBlockFlag"); + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + Want want2 = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_SECOND_BUNDLE_NAME, params); + eCode = STAbilityUtil::StartAbility(want2, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartSecondApp,ThirdAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "horizontal"); + GTEST_LOG_(INFO) << "\nUpdateConfiguration First Time ====>> "; + abilityMgrService->UpdateConfiguration(configuration); + AppExecFwk::Configuration configuration2; + configuration2.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "vertical"); + GTEST_LOG_(INFO) << "\nUpdateConfiguration Second Time ====>> "; + abilityMgrService->UpdateConfiguration(configuration2); + + EXPECT_EQ(TestWaitCompleted(event, "horizontal", THIRD_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "horizontal", SECOND_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "horizontal", MAIN_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + + EXPECT_EQ(TestWaitCompleted(event, "vertical", THIRD_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "vertical", SECOND_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "vertical", MAIN_ABILITY_CODE, WAIT_BLOCKUPDATE_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0800 end=========<"; +} + +/** + * @tc.number : 0900 + * @tc.name : AMS_UpdateConfiguration_0900 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system + * configuration concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0900 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + SetDefaultConfig(); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN, MAIN_ABILITY_CODE, "StartNextAbility"); + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + Want want2 = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_SECOND_BUNDLE_NAME, params); + eCode = STAbilityUtil::StartAbility(want2, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartSecondApp,ThirdAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + + g_mainAbilityUpdateTimes = 0; + g_secondAbilityUpdateTimes = 0; + g_thirdAbilityUpdateTimes = 0; + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "fr_FR"); + AppExecFwk::Configuration configuration2; + configuration2.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, "en_US"); + for (int iLoop = 0; iLoop < TEST_TIMES / 2; iLoop++) { + abilityMgrService->UpdateConfiguration(configuration); + abilityMgrService->UpdateConfiguration(configuration2); + } + sleep(WAIT_LAUNCHER_TIME); + + EXPECT_EQ(g_mainAbilityUpdateTimes, TEST_TIMES); + EXPECT_EQ(g_secondAbilityUpdateTimes, TEST_TIMES); + EXPECT_EQ(g_thirdAbilityUpdateTimes, TEST_TIMES); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0900 end=========<"; +} + +/** + * @tc.number : 1000 + * @tc.name : AMS_UpdateConfiguration_1000 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system + * configuration concerned by capability are correct. + */ + +HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_1000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1000 start"; + MAP_STR_STR params; + + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + SetDefaultConfig(); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN, MAIN_ABILITY_CODE, "StartNextAbility"); + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + Want want2 = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_SECOND_BUNDLE_NAME, params); + eCode = STAbilityUtil::StartAbility(want2, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartSecondApp,ThirdAbility ====>> " << eCode; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", THIRD_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + sleep(WAIT_ONACTIVE_TIME); + + g_mainAbilityUpdateTimes = 0; + g_secondAbilityUpdateTimes = 0; + g_thirdAbilityUpdateTimes = 0; + AppExecFwk::Configuration configuration; + configuration.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "horizontal"); + AppExecFwk::Configuration configuration2; + configuration2.AddItem(GlobalConfigurationKey::SYSTEM_ORIENTATION, "vertical"); + for (int iLoop = 0; iLoop < TEST_TIMES / 2; iLoop++) { + abilityMgrService->UpdateConfiguration(configuration); + abilityMgrService->UpdateConfiguration(configuration2); + } + sleep(WAIT_LAUNCHER_TIME); + + EXPECT_EQ(g_mainAbilityUpdateTimes, TEST_TIMES); + EXPECT_EQ(g_secondAbilityUpdateTimes, TEST_TIMES); + EXPECT_EQ(g_thirdAbilityUpdateTimes, TEST_TIMES); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1000 end=========<"; +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_data_ability_test/BUILD.gn b/test/systemtest/common/ams/ams_data_ability_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..9c11fe5a08a9003c5152003e3f32441fd29ce7be --- /dev/null +++ b/test/systemtest/common/ams/ams_data_ability_test/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_data_ability_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_data_ability_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_data_ability_test" ] +} diff --git a/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test.cpp b/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca601b40de760d7f17279c499d0ca89ce41c362a --- /dev/null +++ b/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test.cpp @@ -0,0 +1,933 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "ability_lifecycle_executor.h" +#include "ability_manager_errors.h" +#include "ability_manager_service.h" +#include "ams_data_ability_test_def.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "event.h" +#include "hilog_wrapper.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "semaphore_ex.h" +#include "stoperator.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "uri.h" + +namespace { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::EventFwk; +using Uri = OHOS::Uri; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; + +using MAP_STR_STR = std::map; +using VECTOR_STR = std::vector; +namespace { +static const std::string BUNDLE_NAME_BASE = "com.ohos.amsst.AppData"; +static const std::string ABILITY_NAME_BASE = "AmsStDataAbility"; +static const std::string HAP_NAME_BASE = "amsDataSystemTest"; +static const int ABILITY_CODE_BASE = 100; +} + +bool PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +class AmsDataAbilityTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + void ResetSystem() const; + static bool SubscribeEvent(); + void ReInstallBundle() const; + void UnInstallBundle() const; + static sptr appMgrService; + static sptr abilityMgrService; + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + + static STtools::Event event; + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + PageAbilityState_ = { + {"onStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + }; + DataAbilityState_ = { + {"OnStart"}, + {"Insert"}, + {"Delete"}, + {"Update"}, + {"Query"}, + {"GetFileTypes"}, + {"OpenFile"}, + {"Default"}, + }; + AbilityOperator_ = { + {"Insert"}, + {"Delete"}, + {"Update"}, + {"Query"}, + {"GetFileTypes"}, + {"OpenFile"}, + }; + }; + ~AppEventSubscriber() + { + PageAbilityState_ = {}; + DataAbilityState_ = {}; + }; + virtual void OnReceiveEvent(const CommonEventData &data) override; + std::unordered_map PageAbilityState_; + std::set DataAbilityState_; + std::set AbilityOperator_; + }; +}; + +STtools::Event AmsDataAbilityTest::event = STtools::Event(); + +void AmsDataAbilityTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + std::string eventName = data.GetWant().GetAction(); + if (eventName.compare(ABILITY_EVENT_NAME) == 0) { + std::string target = data.GetData(); + if (target.find(" ") != target.npos) { + AmsDataAbilityTest::TestCompleted(event, target, data.GetCode()); + return; + } + + if (PAGE_ABILITY_CODE == data.GetCode() / ABILITY_CODE_BASE) { // page ability + EXPECT_TRUE(PageAbilityState_.find(target) != PageAbilityState_.end()); + AmsDataAbilityTest::TestCompleted(event, target, data.GetCode()); + return; + } else if (DATA_ABILITY_CODE == data.GetCode() / ABILITY_CODE_BASE) { // data ability + std::string target = data.GetData(); + EXPECT_TRUE(DataAbilityState_.find(target) != DataAbilityState_.end()); + AmsDataAbilityTest::TestCompleted(event, target, data.GetCode()); + return; + } + } +} + +void AmsDataAbilityTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void AmsDataAbilityTest::TearDownTestCase(void) +{} + +void AmsDataAbilityTest::SetUp(void) +{ + ReInstallBundle(); + STAbilityUtil::CleanMsg(event); + ResetSystem(); + + abilityMgrService = STAbilityUtil::GetAbilityManagerService(); + appMgrService = STAbilityUtil::GetAppMgrService(); +} + +void AmsDataAbilityTest::TearDown(void) +{ + UnInstallBundle(); + STAbilityUtil::CleanMsg(event); +} + +bool AmsDataAbilityTest::SubscribeEvent() +{ + std::vector eventList = {"event_data_ability_callback"}; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsDataAbilityTest::ReInstallBundle() const +{ + std::vector bundleNameSuffix = {"A", "B", "C"}; + for (std::string suffix : bundleNameSuffix) { + STAbilityUtil::Install(HAP_NAME_BASE + suffix); + } +} + +void AmsDataAbilityTest::UnInstallBundle() const +{ + std::vector bundleNameSuffix = {"A", "B", "C"}; + for (std::string suffix : bundleNameSuffix) { + STAbilityUtil::Uninstall(BUNDLE_NAME_BASE + suffix); + } +} + +sptr AmsDataAbilityTest::appMgrService = nullptr; +sptr AmsDataAbilityTest::abilityMgrService = nullptr; + +void AmsDataAbilityTest::ResetSystem() const +{ + GTEST_LOG_(INFO) << "ResetSystem"; +} + +int AmsDataAbilityTest::TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) +{ + GTEST_LOG_(INFO) << "TestWaitCompleted : " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} + +void AmsDataAbilityTest::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + GTEST_LOG_(INFO) << "TestCompleted : " << eventName << " " << code; + return STAbilityUtil::Completed(event, eventName, code); +} + +/** + * @tc.number : AMS_Data_Ability_00100 + * @tc.name : data ability ST 001 + * @tc.desc : start InsertOperator of data ability by page ability in the same app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00200 + * @tc.name : data ability ST 002 + * @tc.desc : start DeleteOperator of data ability by page ability in the same app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00300 + * @tc.name : data ability ST 003 + * @tc.desc : start UpdateOperator of data ability by page ability in the same app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00400 + * @tc.name : data ability ST 004 + * @tc.desc : start OpenFileOperator of data ability by page ability in the same app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_OPENFILE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00500 + * @tc.name : data ability ST 005 + * @tc.desc : start GetFileTypesOperator of data ability by page ability in the same app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00600 + * @tc.name : data ability ST 006 + * @tc.desc : start QueryOperator of data ability by page ability in the same app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_A_CODE, OPERATOR_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00700 + * @tc.name : data ability ST 007 + * @tc.desc : start InsertOperator of data ability by page ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00800 + * @tc.name : data ability ST 008 + * @tc.desc : start DeleteOperator of data ability by page ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00900 + * @tc.name : data ability ST 009 + * @tc.desc : start UpdateOperator of data ability by page ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_00900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_00900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01000 + * @tc.name : data ability ST 010 + * @tc.desc : start OpenFileOperator of data ability by page ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_01000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_OPENFILE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01100 + * @tc.name : data ability ST 011 + * @tc.desc : start GetFileTypesOperator of data ability by page ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_01100, Function | MediumTest | Level1) +{ + using namespace STtools; + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = + std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName, OPERATOR_DEFAULT); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_DATA_C1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01200 + * @tc.name : data ability ST 012 + * @tc.desc : start QueryOperator of data ability by page ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_01200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_C1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_C1_CODE, OPERATOR_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + OPERATOR_QUERY, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01300 + * @tc.name : data ability ST 013 + * @tc.desc : start InsertOperator of data ability by data ability in the same app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_01300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = + std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName, OPERATOR_DEFAULT); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC2", OPERATOR_QUERY); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_C1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_C1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C2_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_C2_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_C2_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_DATA_C1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01400 + * @tc.name : data ability ST 014 + * @tc.desc : start InsertOperator of data ability by data ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_01400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = + std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName, OPERATOR_DEFAULT); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_A_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_DATA_A_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01500 + * @tc.name : data ability ST 015 + * @tc.desc : start InsertOperator of data ability by the same data ability. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_01500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = + std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName, OPERATOR_DEFAULT); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_C1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_C1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_DATA_C1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01600 + * @tc.name : data ability ST 016 + * @tc.desc : start InsertOperator of data ability by two page ability in different app. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_016, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = + std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName, OPERATOR_DEFAULT); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC2", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + GTEST_LOG_(INFO) << "StartAbility1 start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility1 done"; + + bundleName = BUNDLE_NAME_BASE + "B"; + abilityName = ABILITY_NAME_BASE + "PageB"; + first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName, OPERATOR_DEFAULT); + second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC2", OPERATOR_INSERT); + first->AddChildOperator(second); + vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + GTEST_LOG_(INFO) << "StartAbility2 start"; + eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility2 done"; + + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C2_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT, ABILITY_DATA_C2_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_PAGE_A_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT, ABILITY_DATA_C2_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_PAGE_B_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01700 + * @tc.name : data ability ST 017 + * @tc.desc : start some data ability by some page ability and data ability. + */ +HWTEST_F(AmsDataAbilityTest, AMS_Data_Ability_01700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + std::shared_ptr first = + std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName, OPERATOR_DEFAULT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_INSERT); + std::shared_ptr second2 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_QUERY); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_DELETE); + std::shared_ptr second3 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC2", OPERATOR_INSERT); + std::shared_ptr second4 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA", OPERATOR_QUERY); + std::shared_ptr third2 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC1", OPERATOR_QUERY); + std::shared_ptr four = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "C", ABILITY_NAME_BASE + "DataC2", OPERATOR_DELETE); + first->AddChildOperator(second1); + first->AddChildOperator(second2); + second2->AddChildOperator(third1); + first->AddChildOperator(second3); + first->AddChildOperator(second4); + second4->AddChildOperator(third2); + third2->AddChildOperator(four); + + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + // second1 + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_DATA_C1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_PAGE_A_CODE), 0); + + // second2 + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_B_CODE, DATA_STATE_QUERY); + // third1 + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_DATA_C1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_PAGE_A_CODE), 0); + + // second3 + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_C2_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_DATA_C2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_PAGE_A_CODE), 0); + + // second4 + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_A_CODE, DATA_STATE_QUERY); + // third2 + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_DATA_C1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_DATA_C1_CODE, DATA_STATE_QUERY); + // four + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_DATA_C2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_DATA_C1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_DATA_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_PAGE_A_CODE), 0); + + GTEST_LOG_(INFO) << "AmsDataAbilityTest AMS_Data_Ability_01700 end"; +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test_def.h b/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test_def.h new file mode 100644 index 0000000000000000000000000000000000000000..6c376a0b5800e2215e1f8536a8f6392520b53995 --- /dev/null +++ b/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test_def.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 _AMS_DATA_ABILITY_TEST_DEF_H_ +#define _AMS_DATA_ABILITY_TEST_DEF_H_ +#include + +namespace OHOS { +namespace AppExecFwk { +const int PAGE_ABILITY_CODE = 1; +const int DATA_ABILITY_CODE = 2; +const int SERVICE_ABILITY_CODE = 3; + +const int ABILITY_PAGE_A_CODE = 110; +const int ABILITY_DATA_A_CODE = 210; +const int ABILITY_PAGE_B_CODE = 120; +const int ABILITY_DATA_B_CODE = 220; +const int ABILITY_DATA_C1_CODE = 230; +const int ABILITY_DATA_C2_CODE = 240; + +const int ABILITY_KIT_PAGE_A_CODE = 130; +const int ABILITY_KIT_SERVICE_A_CODE = 310; +const int ABILITY_KIT_DATA_A1_CODE = 250; +const int LIFECYCLE_CALLBACKS_A1 = 251; +const int LIFECYCLE_OBSERVER_A1 = 252; +const int ABILITY_KIT_DATA_A2_CODE = 260; +const int LIFECYCLE_CALLBACKS_A2 = 261; +const int LIFECYCLE_OBSERVER_A2 = 262; +const int ABILITY_KIT_DATA_A3_CODE = 290; +const int LIFECYCLE_CALLBACKS_A3 = 291; +const int LIFECYCLE_OBSERVER_A3 = 292; + +const int ABILITY_KIT_PAGE_B_CODE = 140; +const int ABILITY_KIT_SERVICE_B_CODE = 320; +const int ABILITY_KIT_DATA_B_CODE = 270; +const int LIFECYCLE_CALLBACKS_B = 271; +const int LIFECYCLE_OBSERVER_B = 272; + +const std::string DEVICE_ID = "device"; + +const std::string ABILITY_TYPE_PAGE = "0"; +const std::string ABILITY_TYPE_SERVICE = "1"; +const std::string ABILITY_TYPE_DATA = "2"; + +const std::string ABILITY_EVENT_NAME = "event_data_ability_callback"; +const std::string TEST_EVENT_NAME = "event_data_test_action"; + +const std::string PAGE_STATE_ONSTART = "onStart"; +const std::string PAGE_STATE_ONSTOP = "OnStop"; +const std::string PAGE_STATE_ONACTIVE = "OnActive"; +const std::string PAGE_STATE_ONINACTIVE = "OnInactive"; +const std::string PAGE_STATE_ONFOREGROUND = "OnForeground"; +const std::string PAGE_STATE_ONBACKGROUND = "OnBackground"; + +const std::string DATA_STATE_ONSTART = "OnStart"; +const std::string DATA_STATE_ONSTOP = "OnStop"; +const std::string DATA_STATE_ONACTIVE = "OnActive"; +const std::string DATA_STATE_ONINACTIVE = "OnInactive"; +const std::string DATA_STATE_ONFOREGROUND = "OnForeground"; +const std::string DATA_STATE_ONBACKGROUND = "OnBackground"; +const std::string DATA_STATE_INSERT = "Insert"; +const std::string DATA_STATE_DELETE = "Delete"; +const std::string DATA_STATE_UPDATE = "Update"; +const std::string DATA_STATE_QUERY = "Query"; +const std::string DATA_STATE_GETFILETYPES = "GetFileTypes"; +const std::string DATA_STATE_OPENFILE = "OpenFile"; + +const std::string SERVICE_STATE_ONSTART = "onStart"; +const std::string SERVICE_STATE_ONSTOP = "OnStop"; +const std::string SERVICE_STATE_ONACTIVE = "OnActive"; +const std::string SERVICE_STATE_ONINACTIVE = "OnInactive"; +const std::string SERVICE_STATE_ONFOREGROUND = "OnForeground"; +const std::string SERVICE_STATE_ONBACKGROUND = "OnBackground"; +const std::string SERVICE_STATE_ONCOMMAND = "OnCommand"; + +const std::string DATA_STATE_CHANGE = "OnStateChanged"; +const std::string DATA_STATE_ONNEWWANT = "OnNewWant"; + +const std::string OPERATOR_INSERT = "Insert"; +const std::string OPERATOR_DELETE = "Delete"; +const std::string OPERATOR_UPDATE = "Update"; +const std::string OPERATOR_QUERY = "Query"; +const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +const std::string OPERATOR_OPENFILE = "OpenFile"; +const std::string OPERATOR_GETTYPE = "GetType"; +const std::string OPERATOR_TEST_LIFECYCLE = "TestLifeCycle"; +const std::string OPERATOR_GETLIFECYCLESTATE = "GetLifecycleState"; +const std::string OPERATOR_DEFAULT = "Default"; + +const std::string DEFAULT_INSERT_RESULT = "1111"; +const std::string DEFAULT_DELETE_RESULT = "2222"; +const std::string DEFAULT_UPDATE_RESULT = "3333"; +const std::string DEFAULT_OPENFILE_RESULT = "4444"; +const std::string DEFAULT_GETFILETYPE_RESULT = "filetypes"; +const std::string DEFAULT_QUERY_RESULT = "Query"; +const std::string DEFAULT_GETTYPE_RESULT = "GetType"; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_DATA_ABILITY_TEST_DEF_H_ \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_dfx_test/BUILD.gn b/test/systemtest/common/ams/ams_dfx_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..6926ed55aa05bc13210ecfc2333ba3040d348d51 --- /dev/null +++ b/test/systemtest/common/ams/ams_dfx_test/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_dfx_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_dfx_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_dfx_test" ] +} diff --git a/test/systemtest/common/ams/ams_dfx_test/ams_dfx_test.cpp b/test/systemtest/common/ams/ams_dfx_test/ams_dfx_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df6fd0e1ae1064934424b72c09a9d1fd2d80b3ea --- /dev/null +++ b/test/systemtest/common/ams/ams_dfx_test/ams_dfx_test.cpp @@ -0,0 +1,652 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "module_test_dump_util.h" +#include "st_ability_util.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "common_event.h" +#include "common_event_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using namespace OHOS::EventFwk; + +namespace { +using MAP_STR_STR = std::map; +std::vector bundleNameSuffix = {"Q", "R", "DFX"}; +std::string bundleNameBase = "com.ohos.amsst.app"; +std::string hapNameBase = "amsSystemTest"; +std::string abilityNameBase = "AmsStAbility"; +std::string launcherBundle = "com.ohos.launcher"; +std::string launcherAbility = "com.ohos.launcher.MainAbility"; +std::string systemUiBundle = "com.ohos.systemui"; +std::string terminatePageAbility = "requ_page_ability_terminate"; + +static const std::string DUMP_STACK_LIST = "--stack-list"; +const std::string DUMP_SERVICE = "--serv"; +static const std::string DUMP_STACK = "--stack"; +static const std::string DUMP_MISSION = "--mission"; +static const std::string DUMP_TOP = "--top"; +static const std::string DUMP_ALL = "-a"; +constexpr int WAIT_TIME = 7 * 1000; +constexpr int BACKGROUND_WAIT_TIME = 15 * 1000; +static const std::string abilityStateInit = ":Init"; +static const std::string abilityStateOnStart = ":OnStart"; +static const std::string abilityStateOnStop = ":OnStop"; +static const std::string abilityStateOnActive = ":OnActive"; +static const std::string abilityStateOnInactive = ":OnInactive"; +static const std::string abilityStateOnBackground = ":OnBackground"; +static const std::string abilityStateOnForeground = ":OnForeground"; +static const std::string abilityStateOnNewWant = ":OnNewWant"; +static const std::string abilityStateOnCommand = ":OnCommand"; +static const std::string abilityStateOnConnect = ":OnConnect"; +static const std::string abilityStateOnDisconnect = ":OnDisconnect"; +static const int abilityStateCountOne = 1; +static const int abilityStateCountTwo = 2; +enum AbilityState_Test { + INITIAL = 0, + INACTIVE, + ACTIVE, + BACKGROUND, + SUSPENDED, + INACTIVATING, + ACTIVATING, + MOVING_BACKGROUND, + TERMINATING, + ALLSUM, +}; +static const std::vector abilityStateVec = { + "INITIAL", + "INACTIVE", + "ACTIVE", + "BACKGROUND", + "SUSPENDED", + "INACTIVATING", + "ACTIVATING", + "MOVING_BACKGROUND", + "TERMINATING", +}; +} // namespace +class AppEventSubscriber; + +class AmsDFXTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static std::vector GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs); + static bool SubscribeEvent(); + void ShowDump(); + static void CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState); + void ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, + const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = (DUMP_STACK + " 1")); + void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum); + void ExpectServiceAbilityNumInStack(const std::string &abilityName, int abilityNum); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + {} + virtual ~AppEventSubscriber() + {} + virtual void OnReceiveEvent(const CommonEventData &data) override; + }; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityConnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + resultConnectCode = resultCode; + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + resultConnectCode = resultCode; + } + + static size_t onAbilityConnectDoneCount; + static int resultConnectCode; + }; + static sptr appMs_; + static sptr abilityMs_; + static STtools::Event event_; + static std::shared_ptr subscriber_; +}; + +sptr AmsDFXTest::appMs_ = nullptr; +sptr AmsDFXTest::abilityMs_ = nullptr; +STtools::Event AmsDFXTest::event_ = STtools::Event(); +std::shared_ptr AmsDFXTest::subscriber_ = nullptr; +size_t AmsDFXTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +int AmsDFXTest::AbilityConnectCallback::resultConnectCode = 0; + +void AmsDFXTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsDFXTest::SetUpTestCase(void)"; + + SubscribeEvent(); + appMs_ = STAbilityUtil::GetAppMgrService(); + abilityMs_ = STAbilityUtil::GetAbilityManagerService(); + if (appMs_) { + int freeTime = 60; + appMs_->SetAppFreezingTime(freeTime); + int time = 0; + appMs_->GetAppFreezingTime(time); + std::cout << "appMs_->GetAppFreezingTime();" << time << std::endl; + } +} + +void AmsDFXTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsDFXTest::TearDownTestCase(void)"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsDFXTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "void AmsDFXTest::SetUp(void)"; + std::vector hapNames = GetBundleNames(hapNameBase, bundleNameSuffix); + STAbilityUtil::InstallHaps(hapNames); +} + +void AmsDFXTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "void AmsDFXTest::TearDown(void)"; + + std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); + STAbilityUtil::UninstallBundle(bundleNames); + + STAbilityUtil::CleanMsg(event_); +} + +std::vector AmsDFXTest::GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs) +{ + std::vector bundleNames; + for (auto strSuffix : strSuffixs) { + bundleNames.push_back(strBase + strSuffix); + } + return bundleNames; +} + +bool AmsDFXTest::SubscribeEvent() +{ + std::vector eventList = {"resp_st_page_ability_callback"}; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsDFXTest::ShowDump() +{ + if (abilityMs_) { + std::vector dumpInfo; + abilityMs_->DumpState("-a", dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + } +} + +void AmsDFXTest::CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState) +{ + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", info, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + // ability exist + EXPECT_NE(pos, result.end()); + MTDumpUtil::GetInstance()->GetAll("State", info, result); + EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } + // ability state + if (midState != "") { + bool compareResult = ((*pos == state) || (*pos == midState)); + EXPECT_EQ(1, compareResult); + } else { + EXPECT_EQ(*pos, state); + } +} + +void AmsDFXTest::ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, + const AbilityState_Test &midState, const std::string &args) +{ + std::string strCurrentState = abilityStateVec.at(currentState); + std::string strMidState = ""; + if (midState != AbilityState_Test::ALLSUM) { + strMidState = abilityStateVec.at(midState); + } + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(args, dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, strCurrentState, strMidState); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsDFXTest::ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState("-a", dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsDFXTest::ExpectServiceAbilityNumInStack(const std::string &abilityName, int abilityNum) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(DUMP_SERVICE, dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsDFXTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + std::string eventName = data.GetWant().GetAction(); + if (eventName == "resp_st_page_ability_callback") { + std::string target = data.GetData(); + STAbilityUtil::Completed(event_, target, data.GetCode()); + } +} + +/* + * @tc.number : AMS_DFX_0100 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.LoadAbility timeout pageAbility + * 2.Restart the previous ability(different bundle) + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0100 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string bundleName2 = bundleNameBase + "R"; + std::string abilityName2 = abilityNameBase + "R1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityNumInStack(abilityName2, 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0100 end"; +} + +/* + * @tc.number : AMS_DFX_0200 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.LoadAbility timeout pageAbility + * 2.Restart the previous ability(same bundle) + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0200 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string abilityName2 = abilityNameBase + "Q2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityNumInStack(abilityName2, 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0200 end"; +} + +/* + * @tc.number : AMS_DFX_0300 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.LoadAbility timeout pageAbility + * 2.Restart the previous ability(back launch) + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0300, TestSize.Level1) +{ + std::this_thread::sleep_for(std::chrono::milliseconds(5000)); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0300 start"; + std::string bundleName = bundleNameBase + "R"; + std::string abilityName = abilityNameBase + "R1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + ExpectAbilityCurrentState(launcherAbility, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); + ExpectAbilityNumInStack(abilityName, 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0300 end"; +} + +/* + * @tc.number : AMS_DFX_0400 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.LoadAbility timeout pageAbility + * 2.Restart the previous ability + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0400 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string bundleName2 = bundleNameBase + "R"; + std::string abilityName2 = abilityNameBase + "R1"; + std::string abilityName3 = abilityNameBase + "Q3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName + "," + bundleName2; + params["targetAbility"] = abilityName3 + "," + abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityNumInStack(abilityName2, 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0400 end"; +} + +/* + * @tc.number : AMS_DFX_0500 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.background timeout pageAbility + * 2.Force call CompleteBackground function(same bundle) + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0500 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string abilityName2 = abilityNameBase + "Q4"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(BACKGROUND_WAIT_TIME)); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::BACKGROUND); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + ExpectAbilityNumInStack(abilityName2, 1); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0500 end"; +} + +/* + * @tc.number : AMS_DFX_0600 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.background timeout pageAbility + * 2.Force call CompleteBackground function(different bundle) + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0600 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string bundleName2 = bundleNameBase + "R"; + std::string abilityName2 = abilityNameBase + "R2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(BACKGROUND_WAIT_TIME)); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::BACKGROUND); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + std::cout << "pInfo.state_:" << static_cast(pInfo.state_) << std::endl; + std::cout << "pInfo.pid_:" << static_cast(pInfo.pid_) << std::endl; + ExpectAbilityNumInStack(abilityName2, 1); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0600 end"; +} + +/* + * @tc.number : AMS_DFX_0700 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.background timeout pageAbility + * 2.Force call CompleteBackground function(different bundle) + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0700 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string bundleName2 = bundleNameBase + "R"; + std::string abilityName2 = abilityNameBase + "R3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(BACKGROUND_WAIT_TIME)); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::BACKGROUND); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + std::cout << "pInfo.state_:" << static_cast(pInfo.state_) << std::endl; + std::cout << "pInfo.pid_:" << static_cast(pInfo.pid_) << std::endl; + ExpectAbilityNumInStack(abilityName2, 1); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0700 end"; +} + +/* + * @tc.number : AMS_DFX_0800 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.Terminate timeout pageAbility + * 2.Force call CompleteTerminate function + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0800, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0800 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string bundleName2 = bundleNameBase + "R"; + std::string abilityName2 = abilityNameBase + "R2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + std::this_thread::sleep_for(std::chrono::milliseconds(BACKGROUND_WAIT_TIME)); + ExpectAbilityNumInStack(abilityName2, 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0800 end"; +} + +/* + * @tc.number : AMS_DFX_0900 + * @tc.name : Lifecycle switch timeout. + * @tc.desc : 1.Terminate timeout pageAbility + * 2.Force call CompleteTerminate function + */ +HWTEST_F(AmsDFXTest, AMS_DFX_0900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0900 start"; + std::string bundleName = bundleNameBase + "Q"; + std::string abilityName = abilityNameBase + "Q1"; + std::string bundleName2 = bundleNameBase + "R"; + std::string abilityName2 = abilityNameBase + "R2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + std::this_thread::sleep_for(std::chrono::milliseconds(BACKGROUND_WAIT_TIME)); + ExpectAbilityNumInStack(abilityName2, 0); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + params.clear(); + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_0900 end"; +} + +/* + * @tc.number : AMS_DFX_1000 + * @tc.name : service ability connection,disconnection exception. + * @tc.desc : 1.connection service ability timeout + * 2.verification callBack resultCode + */ +HWTEST_F(AmsDFXTest, AMS_DFX_1000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_1000 start"; + std::string bundleName = bundleNameBase + "DFX"; + std::string abilityName = "AmsDfxStServiceAbilityA1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + // connect service ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + STAbilityUtil::ConnectAbility(want, stub, stub->AsObject()); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + EXPECT_EQ(AbilityConnectCallback::resultConnectCode, CONNECTION_TIMEOUT); + ExpectServiceAbilityNumInStack(abilityName, 1); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo.pid_ > 0); + + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo.pid_ == 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_1000 end"; +} + +/* + * @tc.number : AMS_DFX_1100 + * @tc.name : service ability connection,disconnection exception. + * @tc.desc : 1.disconnection service ability timeout + * 2.verification disconnection + */ +HWTEST_F(AmsDFXTest, AMS_DFX_1100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_1100 start"; + std::string bundleName = bundleNameBase + "DFX"; + std::string abilityName = "AmsDfxStServiceAbilityA2"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + // connect service ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + STAbilityUtil::ConnectAbility(want, stub, stub->AsObject()); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + EXPECT_EQ(AbilityConnectCallback::resultConnectCode, 0); + ExpectServiceAbilityNumInStack(abilityName, 1); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_TRUE(pInfo.pid_ > 0); + + STAbilityUtil::DisconnectAbility(stub); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + ExpectServiceAbilityNumInStack(abilityName, 0); + GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_1100 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_kit_test/BUILD.gn b/test/systemtest/common/ams/ams_kit_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..9491c311f228eecdaa2367a6b350051d0cec3b36 --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/BUILD.gn @@ -0,0 +1,392 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/ams" +ohos_systemtest("ams_kit_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_systemtest("ams_kit_service_ability_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_service_ability_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_systemtest("ams_kit_data_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_data_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_systemtest("ams_kit_a_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_a_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_systemtest("ams_kit_want_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_want_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_systemtest("ams_kit_skills_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_skills_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_systemtest("ams_kit_lifecycle_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_lifecycle_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_systemtest("ams_kit_processinfo_test") { + module_out_path = module_output_path + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "${appexecfwk_path}/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", + ] + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "acts_ams_kit_processinfo_test.cpp", + ] + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ + ":ams_kit_a_test", + ":ams_kit_data_test", + ":ams_kit_lifecycle_test", + ":ams_kit_processinfo_test", + ":ams_kit_service_ability_test", + ":ams_kit_skills_test", + ":ams_kit_test", + ":ams_kit_want_test", + ] +} diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_a_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_a_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39b6866c2bf0d8ca8bb771955e3ba19a593ed950 --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_a_test.cpp @@ -0,0 +1,2413 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ability_lifecycle.h" +#include "ability_lifecycle_executor.h" +#include "ability_manager_errors.h" +#include "ability_manager_service.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "event.h" +#include "hilog_wrapper.h" +#include "kit_test_common_info.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "stoperator.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "testConfigParser.h" +#include "uri.h" +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; + +using MAP_STR_STR = std::map; +static const string KIT_BUNDLE_NAME = "com.ohos.amsst.AppKit"; +static const string KIT_HAP_NAME = "amsKitSystemTest"; +static const string FIRST_ABILITY_NAME = "MainAbility"; +static const string SECOND_ABILITY_NAME = "SecondAbility"; +static const string THIRD_ABILITY_NAME = "MainAbility"; +static constexpr int WAIT_TIME = 5; +static const int MAIN_ABILITY_A_CODE = 100; +static const int SECOND_ABILITY_A_CODE = 200; +static const int MAIN_ABILITY_B_CODE = 300; +static string g_eventMessage = ""; +int g_StLevel = 1; +} +class ActsAmsKitATest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static void Reinstall(const std::string &hapName, const std::string &bundleName); + void ResetSystem() const; + static bool SubscribeEvent(); + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber(){}; + }; + + static sptr abilityMgrService; + static Event event; + static StressTestLevel stLevel_; +}; + +StressTestLevel ActsAmsKitATest::stLevel_ {}; +Event ActsAmsKitATest::event = Event(); +sptr ActsAmsKitATest::abilityMgrService = nullptr; + +void ActsAmsKitATest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + if (data.GetWant().GetAction() == g_EVENT_RESP_FIRST_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_FIRSTB_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_LIFECYCLE) { + TestCompleted(event, data.GetData(), data.GetCode()); + } else if (data.GetWant().GetAction() == g_EVENT_RESP_FIRST || data.GetWant().GetAction() == g_EVENT_RESP_FIRSTB || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND) { + g_eventMessage = data.GetData(); + TestCompleted(event, data.GetWant().GetAction(), data.GetCode()); + GTEST_LOG_(INFO) << "OnReceiveEvent: g_eventMessage=" << data.GetData(); + } +} + +int ActsAmsKitATest::TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) +{ + GTEST_LOG_(INFO) << "TestWaitCompleted : " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} + +void ActsAmsKitATest::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + GTEST_LOG_(INFO) << "TestCompleted : " << eventName << " " << code; + return STAbilityUtil::Completed(event, eventName, code); +} + +void ActsAmsKitATest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + g_StLevel = stLevel_.AMSLevel; +} + +void ActsAmsKitATest::TearDownTestCase(void) +{} + +static int CODE_ = 0; +void ActsAmsKitATest::SetUp(void) +{ + ResetSystem(); + STAbilityUtil::Install(KIT_HAP_NAME + "A"); + STAbilityUtil::Install(KIT_HAP_NAME + "B"); + STAbilityUtil::CleanMsg(event); + + CODE_++; +} + +void ActsAmsKitATest::TearDown(void) +{ + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME + "A"); + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); +} + +bool ActsAmsKitATest::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_RESP_FIRST_LIFECYCLE, + g_EVENT_RESP_SECOND_LIFECYCLE, + g_EVENT_RESP_FIRSTB_LIFECYCLE, + g_EVENT_RESP_FIRST, + g_EVENT_RESP_SECOND, + g_EVENT_RESP_FIRSTB + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void ActsAmsKitATest::Reinstall(const std::string &hapName, const std::string &bundleName) +{ + STAbilityUtil::Uninstall(bundleName); + STAbilityUtil::Install(hapName); +} + +void ActsAmsKitATest::ResetSystem() const +{ + GTEST_LOG_(INFO) << "ResetSystem"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00100 + * @tc.name : test getApplicationInfo in ability_context.h + * @tc.desc : Verify that the result of getApplicationInfo function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00100, Function | MediumTest | Level1) +{ + // ability_context.h ApplicationInfo* getApplicationInfo() 001 + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetApplicationInfo) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo; + EXPECT_EQ(appInfo, KIT_BUNDLE_NAME + "A"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00100 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00200 + * @tc.name : test getApplicationInfo in ability_context.h + * @tc.desc : Verify that the result of getApplicationInfo function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00200, Function | MediumTest | Level1) +{ + // ability_context.h ApplicationInfo* getApplicationInfo() 002 + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetApplicationInfo) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetApplicationInfo) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string appInfo2 = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo1; + GTEST_LOG_(INFO) << appInfo2; + + EXPECT_EQ(appInfo1, KIT_BUNDLE_NAME + "A"); + EXPECT_EQ(appInfo1, appInfo2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00200 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00300 + * @tc.name : test getApplicationInfo in ability_context.h + * @tc.desc : Verify that the result of getApplicationInfo function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00300, Function | MediumTest | Level1) +{ + // ability_context.h ApplicationInfo* getApplicationInfo() 003 + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetApplicationInfo) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appInfo1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetApplicationInfo) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string appInfo2 = g_eventMessage; + + GTEST_LOG_(INFO) << appInfo1; + GTEST_LOG_(INFO) << appInfo2; + + EXPECT_EQ(appInfo1, KIT_BUNDLE_NAME + "A"); + EXPECT_EQ(appInfo2, KIT_BUNDLE_NAME + "B"); + EXPECT_NE(appInfo1, appInfo2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00300 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00400 + * @tc.name : test GetCacheDir in ability_context.h + * @tc.desc : Verify that the result of GetCacheDir function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCacheDir) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string cacheDir = g_eventMessage; + + GTEST_LOG_(INFO) << cacheDir; + EXPECT_NE(cacheDir, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00400 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00500 + * @tc.name : test GetCacheDir in ability_context.h + * @tc.desc : Verify that the result of GetCacheDir function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCacheDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string cacheDir1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCacheDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string cacheDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << cacheDir1; + GTEST_LOG_(INFO) << cacheDir2; + EXPECT_NE(cacheDir1, ""); + EXPECT_EQ(cacheDir1, cacheDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00500 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00600 + * @tc.name : test GetCacheDir in ability_context.h + * @tc.desc : Verify that the result of GetCacheDir function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCacheDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string cacheDir1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCacheDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string cacheDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << cacheDir1; + GTEST_LOG_(INFO) << cacheDir2; + + EXPECT_NE(cacheDir1, ""); + EXPECT_NE(cacheDir2, ""); + EXPECT_NE(cacheDir1, cacheDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00600 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00700 + * @tc.name : test GetCodeCacheDir in ability_context.h + * @tc.desc : Verify that the result of GetCodeCacheDir function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCodeCacheDir) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string codeCacheDir = g_eventMessage; + + GTEST_LOG_(INFO) << codeCacheDir; + EXPECT_NE(codeCacheDir, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00700 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00800 + * @tc.name : test GetCodeCacheDir in ability_context.h + * @tc.desc : Verify that the result of GetCodeCacheDir function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCodeCacheDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string codeCacheDir1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCodeCacheDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string codeCacheDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << codeCacheDir1; + GTEST_LOG_(INFO) << codeCacheDir2; + EXPECT_NE(codeCacheDir1, ""); + EXPECT_EQ(codeCacheDir1, codeCacheDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00800 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_00900 + * @tc.name : test GetCodeCacheDir in ability_context.h + * @tc.desc : Verify that the result of GetCodeCacheDir function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_00900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCodeCacheDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string codeCacheDir1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCodeCacheDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string codeCacheDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << codeCacheDir1; + GTEST_LOG_(INFO) << codeCacheDir2; + + EXPECT_NE(codeCacheDir1, ""); + EXPECT_NE(codeCacheDir2, ""); + EXPECT_NE(codeCacheDir1, codeCacheDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_00900 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01000 + * @tc.name : test GetDatabaseDir in ability_context.h + * @tc.desc : Verify that the result of GetDatabaseDir function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDatabaseDir) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dataBaseDir = g_eventMessage; + + GTEST_LOG_(INFO) << dataBaseDir; + + EXPECT_NE(dataBaseDir, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01000 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01100 + * @tc.name : test GetDatabaseDir in ability_context.h + * @tc.desc : Verify that the result of GetDatabaseDir function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDatabaseDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dataBaseDir1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDatabaseDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string dataBaseDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << dataBaseDir1; + GTEST_LOG_(INFO) << dataBaseDir2; + + EXPECT_NE(dataBaseDir1, ""); + EXPECT_EQ(dataBaseDir1, dataBaseDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01100 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01200 + * @tc.name : test GetDatabaseDir in ability_context.h + * @tc.desc : Verify that the result of GetDatabaseDir function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDatabaseDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dataBaseDir1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDatabaseDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string dataBaseDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << dataBaseDir1; + GTEST_LOG_(INFO) << dataBaseDir2; + + EXPECT_NE(dataBaseDir1, ""); + EXPECT_NE(dataBaseDir2, ""); + EXPECT_NE(dataBaseDir1, dataBaseDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01200 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01300 + * @tc.name : test GetDataDir in ability_context.h + * @tc.desc : Verify that the result of GetDataDir function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDataDir) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dataDir = g_eventMessage; + + GTEST_LOG_(INFO) << dataDir; + + EXPECT_NE(dataDir, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01300 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01400 + * @tc.name : test GetDataDir in ability_context.h + * @tc.desc : Verify that the result of GetDataDir function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDataDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dataDir1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDataDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string dataDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << dataDir1; + GTEST_LOG_(INFO) << dataDir2; + + EXPECT_NE(dataDir1, ""); + EXPECT_EQ(dataDir1, dataDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01400 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01500 + * @tc.name : test GetDataDir in ability_context.h + * @tc.desc : Verify that the result of GetDataDir function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDataDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dataDir1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDataDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string dataDir2 = g_eventMessage; + + GTEST_LOG_(INFO) << dataDir1; + GTEST_LOG_(INFO) << dataDir2; + + EXPECT_NE(dataDir1, ""); + EXPECT_NE(dataDir2, ""); + EXPECT_NE(dataDir1, dataDir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01500 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01600 + * @tc.name : test GetDir in ability_context.h + * @tc.desc : Verify that the result of GetDir function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDir) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dir = g_eventMessage; + + GTEST_LOG_(INFO) << dir; + + EXPECT_NE(dir, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01600 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01700 + * @tc.name : test GetDir in ability_context.h + * @tc.desc : Verify that the result of GetDir function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dir1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDir) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string dir2 = g_eventMessage; + + GTEST_LOG_(INFO) << dir1; + GTEST_LOG_(INFO) << dir2; + + EXPECT_NE(dir1, ""); + EXPECT_EQ(dir1, dir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01700 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01800 + * @tc.name : test GetDir in ability_context.h + * @tc.desc : Verify that the result of GetDir function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string dir1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetDir) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string dir2 = g_eventMessage; + + GTEST_LOG_(INFO) << dir1; + GTEST_LOG_(INFO) << dir2; + + EXPECT_NE(dir1, ""); + EXPECT_NE(dir2, ""); + EXPECT_NE(dir1, dir2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01800 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_01900 + * @tc.name : test GetBundleManager in ability_context.h + * @tc.desc : Verify that the result of GetBundleManager function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_01900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleManager) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string result = g_eventMessage; + + GTEST_LOG_(INFO) << result; + EXPECT_EQ(result, "1"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_01900 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02000 + * @tc.name : test GetBundleCodePath in ability_context.h + * @tc.desc : Verify that the result of GetBundleCodePath function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleCodePath) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleCodePath = g_eventMessage; + + GTEST_LOG_(INFO) << bundleCodePath; + EXPECT_NE(bundleCodePath, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02000 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02100 + * @tc.name : test GetBundleCodePath in ability_context.h + * @tc.desc : Verify that the result of GetBundleCodePath function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleCodePath) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleCodePath1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleCodePath) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string bundleCodePath2 = g_eventMessage; + + GTEST_LOG_(INFO) << bundleCodePath1; + GTEST_LOG_(INFO) << bundleCodePath2; + + EXPECT_NE(bundleCodePath1, ""); + EXPECT_EQ(bundleCodePath1, bundleCodePath2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02100 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02200 + * @tc.name : test GetBundleCodePath in ability_context.h + * @tc.desc : Verify that the result of GetBundleCodePath function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleCodePath) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleCodePath1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleCodePath) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string bundleCodePath2 = g_eventMessage; + + GTEST_LOG_(INFO) << bundleCodePath1; + GTEST_LOG_(INFO) << bundleCodePath2; + + EXPECT_NE(bundleCodePath1, ""); + EXPECT_NE(bundleCodePath2, ""); + EXPECT_NE(bundleCodePath1, bundleCodePath2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02200 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02300 + * @tc.name : test GetBundleName in ability_context.h + * @tc.desc : Verify that the result of GetBundleName function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleName) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleName = g_eventMessage; + + GTEST_LOG_(INFO) << bundleName; + EXPECT_NE(bundleName, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02300 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02400 + * @tc.name : test GetBundleName in ability_context.h + * @tc.desc : Verify that the result of GetBundleName function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleName) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleName1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleName) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string bundleName2 = g_eventMessage; + + GTEST_LOG_(INFO) << bundleName1; + GTEST_LOG_(INFO) << bundleName2; + + EXPECT_NE(bundleName1, ""); + EXPECT_EQ(bundleName1, bundleName2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02400 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02500 + * @tc.name : test GetBundleName in ability_context.h + * @tc.desc : Verify that the result of GetBundleName function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleName) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleName1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetBundleName) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + + string bundleName2 = g_eventMessage; + + GTEST_LOG_(INFO) << bundleName1; + GTEST_LOG_(INFO) << bundleName2; + + EXPECT_NE(bundleName1, ""); + EXPECT_NE(bundleName2, ""); + EXPECT_NE(bundleName1, bundleName2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02500 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02600 + * @tc.name : test GetBundleResourcePath in ability_context.h + * @tc.desc : Verify that the result of GetBundleResourcePath function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::GetBundleResourcePath) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleResourcePath = g_eventMessage; + + GTEST_LOG_(INFO) << bundleResourcePath; + EXPECT_NE(bundleResourcePath, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02600 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02700 + * @tc.name : test GetBundleResourcePath in ability_context.h + * @tc.desc : Verify that the result of GetBundleResourcePath function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::GetBundleResourcePath) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleResourcePath1 = g_eventMessage; + + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::GetBundleResourcePath) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string bundleResourcePath2 = g_eventMessage; + + GTEST_LOG_(INFO) << bundleResourcePath1; + GTEST_LOG_(INFO) << bundleResourcePath2; + + EXPECT_NE(bundleResourcePath1, ""); + EXPECT_EQ(bundleResourcePath1, bundleResourcePath2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02700 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02800 + * @tc.name : test GetBundleResourcePath in ability_context.h + * @tc.desc : Verify that the result of GetBundleResourcePath function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::GetBundleResourcePath) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string bundleResourcePath1 = g_eventMessage; + + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRSTB, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::GetBundleResourcePath) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string bundleResourcePath2 = g_eventMessage; + + GTEST_LOG_(INFO) << bundleResourcePath1; + GTEST_LOG_(INFO) << bundleResourcePath2; + + EXPECT_NE(bundleResourcePath1, ""); + EXPECT_NE(bundleResourcePath2, ""); + EXPECT_NE(bundleResourcePath1, bundleResourcePath2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02800 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_02900 + * @tc.name : test GetApplicationContext in ability_context.h + * @tc.desc : Verify that the result of GetApplicationContext function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_02900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::GetApplicationContext) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string result = g_eventMessage; + GTEST_LOG_(INFO) << result; + EXPECT_EQ(result, "1"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_02900 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03000 + * @tc.name : test GetCallingAbility in ability_context.h + * @tc.desc : Verify that the result of GetCallingAbility function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_0"); + + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string callingAbility = g_eventMessage; + GTEST_LOG_(INFO) << callingAbility; + EXPECT_NE(callingAbility, ""); + } + + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03000 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03100 + * @tc.name : test GetCallingAbility in ability_context.h + * @tc.desc : Verify that the result of GetCallingAbility function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_1"); + + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + // start second ability + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string callingAbility1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string callingAbility2 = g_eventMessage; + + GTEST_LOG_(INFO) << callingAbility1; + GTEST_LOG_(INFO) << callingAbility2; + + EXPECT_NE(callingAbility1, ""); + EXPECT_NE(callingAbility2, ""); + EXPECT_EQ(callingAbility1, callingAbility2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03100 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03200 + * @tc.name : test GetCallingAbility in ability_context.h + * @tc.desc : Verify that the result of GetCallingAbility function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_ + 1, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_ + 1, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_ + 1), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string callingAbility1 = g_eventMessage; + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, + CODE_ + 1, + "Ability_" + std::to_string((int)AbilityContextApi::GetCallingAbility) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_ + 1), 0); + string callingAbility2 = g_eventMessage; + + GTEST_LOG_(INFO) << callingAbility1; + GTEST_LOG_(INFO) << callingAbility2; + + EXPECT_NE(callingAbility1, ""); + EXPECT_NE(callingAbility2, ""); + EXPECT_NE(callingAbility1, callingAbility2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03200 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03300 + * @tc.name : test GetContext in ability_context.h + * @tc.desc : Verify that the result of GetContext function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetContext) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string result = g_eventMessage; + + GTEST_LOG_(INFO) << result; + EXPECT_EQ(result, "1"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03300 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03400 + * @tc.name : test GetAbilityManager in ability_context.h + * @tc.desc : Verify that the result of GetAbilityManager function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetAbilityManager) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string result = g_eventMessage; + + GTEST_LOG_(INFO) << result; + EXPECT_EQ(result, "1"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03400 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03500 + * @tc.name : test GetProcessInfo in ability_context.h + * @tc.desc : Verify that the result of GetProcessInfo function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetProcessInfo) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string processInfo = g_eventMessage; + + GTEST_LOG_(INFO) << processInfo; + EXPECT_NE(processInfo, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03500 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03600 + * @tc.name : test GetProcessInfo in ability_context.h + * @tc.desc : Verify that the result of GetProcessInfo function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetProcessInfo) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string processInfo1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetProcessInfo) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string processInfo2 = g_eventMessage; + + GTEST_LOG_(INFO) << processInfo1; + GTEST_LOG_(INFO) << processInfo2; + + EXPECT_NE(processInfo1, ""); + EXPECT_NE(processInfo2, ""); + EXPECT_EQ(processInfo1, processInfo2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03600 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03700 + * @tc.name : test GetProcessInfo in ability_context.h + * @tc.desc : Verify that the result of GetProcessInfo function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetProcessInfo) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string processInfo1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetProcessInfo) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string processInfo2 = g_eventMessage; + + GTEST_LOG_(INFO) << processInfo1; + GTEST_LOG_(INFO) << processInfo2; + + EXPECT_NE(processInfo1, ""); + EXPECT_NE(processInfo2, ""); + EXPECT_NE(processInfo1, processInfo2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03700 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03800 + * @tc.name : test GetAppType in ability_context.h + * @tc.desc : Verify that the result of GetAppType function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetAppType) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appType = g_eventMessage; + + GTEST_LOG_(INFO) << appType; + EXPECT_EQ(appType, "third-party"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03800 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_03900 + * @tc.name : test GetAppType in ability_context.h + * @tc.desc : Verify that the result of GetAppType function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_03900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetAppType) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appType1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetAppType) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string appType2 = g_eventMessage; + + GTEST_LOG_(INFO) << appType1; + GTEST_LOG_(INFO) << appType2; + EXPECT_EQ(appType1, "third-party"); + EXPECT_EQ(appType2, "third-party"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_03900 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04000 + * @tc.name : test GetAppType in ability_context.h + * @tc.desc : Verify that the result of GetAppType function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetAppType) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string appType1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetAppType) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string appType2 = g_eventMessage; + + GTEST_LOG_(INFO) << appType1; + GTEST_LOG_(INFO) << appType2; + EXPECT_EQ(appType1, "third-party"); + EXPECT_EQ(appType2, "third-party"); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04000 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04100 + * @tc.name : test GetCallingBundle in ability_context.h + * @tc.desc : Verify that the result of GetCallingBundle function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_0"); + + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string callingBundle = g_eventMessage; + + GTEST_LOG_(INFO) << callingBundle; + EXPECT_NE(callingBundle, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04100 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04200 + * @tc.name : test GetCallingBundle in ability_context.h + * @tc.desc : Verify that the result of GetCallingBundle function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_1"); + + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string callingBundle1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string callingBundle2 = g_eventMessage; + + GTEST_LOG_(INFO) << callingBundle1; + GTEST_LOG_(INFO) << callingBundle2; + + EXPECT_NE(callingBundle1, ""); + EXPECT_NE(callingBundle2, ""); + EXPECT_EQ(callingBundle1, callingBundle2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04200 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04300 + * @tc.name : test GetCallingBundle in ability_context.h + * @tc.desc : Verify that the result of GetCallingBundle function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_ + 1, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_ + 1), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string callingBundle1 = g_eventMessage; + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, + CODE_ + 1, + "Ability_" + std::to_string((int)AbilityContextApi::GetCallingBundle) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_ + 1), 0); + string callingBundle2 = g_eventMessage; + + GTEST_LOG_(INFO) << callingBundle1; + GTEST_LOG_(INFO) << callingBundle2; + + EXPECT_NE(callingBundle1, ""); + EXPECT_NE(callingBundle2, ""); + EXPECT_NE(callingBundle1, callingBundle2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04300 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04400 + * @tc.name : test StartAbility_Want_int in ability_context.h + * @tc.desc : Verify that the result of StartAbility_Want_int function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::StartAbility_Want_int) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string result = g_eventMessage; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + GTEST_LOG_(INFO) << result; + EXPECT_EQ(result, "startAbility"); + + Reinstall(KIT_HAP_NAME + "A", KIT_BUNDLE_NAME + "A"); + Reinstall(KIT_HAP_NAME + "B", KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04400 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04500 + * @tc.name : test StartAbility_Want_int in ability_context.h + * @tc.desc : Verify that the result of StartAbility_Want_int function in different application is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, + CODE_, + "Ability_" + std::to_string((int)AbilityContextApi::StartAbility_Want_int) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string result = g_eventMessage; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + GTEST_LOG_(INFO) << result; + EXPECT_EQ(result, "startAbility"); + Reinstall(KIT_HAP_NAME + "A", KIT_BUNDLE_NAME + "A"); + Reinstall(KIT_HAP_NAME + "B", KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04500 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04600 + * @tc.name : test TerminateAbility in ability_context.h + * @tc.desc : Verify that the result of TerminateAbility function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + sleep(50); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::TerminateAbility) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string result = g_eventMessage; + + EXPECT_EQ(TestWaitCompleted(event, "OnStop", MAIN_ABILITY_A_CODE, 30), 0); + + GTEST_LOG_(INFO) << result; + EXPECT_EQ(result, "TerminateAbility"); + sleep(50); + Reinstall(KIT_HAP_NAME + "A", KIT_BUNDLE_NAME + "A"); + Reinstall(KIT_HAP_NAME + "B", KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04600 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04700 + * @tc.name : test GetElementName in ability_context.h + * @tc.desc : Verify that the result of GetElementName function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string elementName = g_eventMessage; + GTEST_LOG_(INFO) << elementName; + + EXPECT_NE(elementName, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04700 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04800 + * @tc.name : test GetElementName in ability_context.h + * @tc.desc : Verify that the result of GetElementName function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string elementName1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string elementName2 = g_eventMessage; + + GTEST_LOG_(INFO) << elementName1; + GTEST_LOG_(INFO) << elementName2; + EXPECT_NE(elementName1, ""); + EXPECT_NE(elementName2, ""); + EXPECT_EQ(elementName1, elementName2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04800 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_04900 + * @tc.name : test GetElementName in ability_context.h + * @tc.desc : Verify that the result of GetElementName function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_04900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string elementName1 = g_eventMessage; + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string elementName2 = g_eventMessage; + + GTEST_LOG_(INFO) << elementName1; + GTEST_LOG_(INFO) << elementName2; + EXPECT_NE(elementName1, ""); + EXPECT_NE(elementName2, ""); + EXPECT_NE(elementName1, elementName2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_04900 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_05000 + * @tc.name : test GetHapModuleInfo in ability_context.h + * @tc.desc : Verify that the result of GetHapModuleInfo function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_05000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetHapModuleInfo) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string hapModuleInfo = g_eventMessage; + + GTEST_LOG_(INFO) << hapModuleInfo; + EXPECT_NE(hapModuleInfo, ""); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05000 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_05100 + * @tc.name : test GetHapModuleInfo in ability_context.h + * @tc.desc : Verify that the result of GetHapModuleInfo function in the same application is equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_05100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string hapModuleInfo1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + string hapModuleInfo2 = g_eventMessage; + + // -----------------------------EXPECT---------------------------------- + GTEST_LOG_(INFO) << hapModuleInfo1; + GTEST_LOG_(INFO) << hapModuleInfo2; + EXPECT_NE(hapModuleInfo1, ""); + EXPECT_NE(hapModuleInfo2, ""); + EXPECT_EQ(hapModuleInfo1, hapModuleInfo2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05100 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_05200 + * @tc.name : test GetHapModuleInfo in ability_context.h + * @tc.desc : Verify that the result of GetHapModuleInfo function in different application is not equal. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_05200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + // start first ability + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + // start second ability + want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + sleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRST, CODE_), 0); + string hapModuleInfo1 = g_eventMessage; + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_FIRSTB, CODE_, "Ability_" + std::to_string((int)AbilityContextApi::GetElementName) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_FIRSTB, CODE_), 0); + string hapModuleInfo2 = g_eventMessage; + + GTEST_LOG_(INFO) << hapModuleInfo1; + GTEST_LOG_(INFO) << hapModuleInfo2; + EXPECT_NE(hapModuleInfo1, ""); + EXPECT_NE(hapModuleInfo2, ""); + EXPECT_NE(hapModuleInfo1, hapModuleInfo2); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05200 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_05300 + * @tc.name : test REGISTER_AA in ability_context.h + * @tc.desc : Verify that the result of REGISTER_AA function is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_05300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIRST_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_A_CODE), 0); + + Reinstall(KIT_HAP_NAME + "A", KIT_BUNDLE_NAME + "A"); + Reinstall(KIT_HAP_NAME + "B", KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05300 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_05400 + * @tc.name : test REGISTER_AA in ability_context.h + * @tc.desc : Verify that the result of REGISTER_AA function in different ability is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_05400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SECOND_ABILITY_NAME, KIT_BUNDLE_NAME + "A", params); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", SECOND_ABILITY_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_A_CODE), 0); + Reinstall(KIT_HAP_NAME + "A", KIT_BUNDLE_NAME + "A"); + Reinstall(KIT_HAP_NAME + "B", KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05400 end"; +} + +/** + * @tc.number : AMS_Page_AbilityContext_05500 + * @tc.name : test REGISTER_AA in ability_context.h + * @tc.desc : Verify that the result of REGISTER_AA function in different application is correct. + */ +HWTEST_F(ActsAmsKitATest, AMS_Page_AbilityContext_05500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME + "B", params); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + sleep(WAIT_TIME); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE), 0); + Reinstall(KIT_HAP_NAME + "A", KIT_BUNDLE_NAME + "A"); + Reinstall(KIT_HAP_NAME + "B", KIT_BUNDLE_NAME + "B"); + STAbilityUtil::CleanMsg(event); + } + GTEST_LOG_(INFO) << "ActsAmsKitATest AMS_Page_AbilityContext_05500 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_data_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_data_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b60b5fcd921e7acaee9ac27396bdd0f3f9aaad7e --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_data_test.cpp @@ -0,0 +1,11728 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "ability_lifecycle_executor.h" +#include "ability_manager_errors.h" +#include "ability_manager_service.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "data_uri_utils.h" +#include "event.h" +#include "hilog_wrapper.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "semaphore_ex.h" +#include "stoperator.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "testConfigParser.h" +#include "uri.h" +namespace { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::EventFwk; +using Uri = OHOS::Uri; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; + +using MAP_STR_STR = std::map; +using VECTOR_STR = std::vector; +static const std::string BUNDLE_NAME_BASE = "com.ohos.amsst.AppKitData"; +static const std::string ABILITY_NAME_BASE = "AmsStKitDataAbility"; +static const std::string HAP_NAME_BASE = "amsKitSystemTestData"; +static const int ABILITY_CODE_BASE = 100; +static const long DEFAULT_ID = 100; +const int PAGE_ABILITY_CODE = 1; +const int DATA_ABILITY_CODE = 2; +const int SERVICE_ABILITY_CODE = 3; +const int ABILITY_KIT_PAGE_A_CODE = 130; +const int ABILITY_KIT_SERVICE_A_CODE = 310; +const int ABILITY_KIT_DATA_A1_CODE = 250; +const int LIFECYCLE_CALLBACKS_A1 = 251; +const int LIFECYCLE_OBSERVER_A1 = 252; +const int ABILITY_KIT_DATA_A2_CODE = 260; +const int LIFECYCLE_CALLBACKS_A2 = 261; +const int LIFECYCLE_OBSERVER_A2 = 262; +const int ABILITY_KIT_DATA_A3_CODE = 290; +const int LIFECYCLE_OBSERVER_A3 = 292; +const int ABILITY_KIT_PAGE_B_CODE = 140; +const int ABILITY_KIT_DATA_B_CODE = 270; +const int LIFECYCLE_CALLBACKS_B = 271; +const int LIFECYCLE_OBSERVER_B = 272; +const std::string DEVICE_ID = "device"; +const std::string ABILITY_TYPE_PAGE = "0"; +const std::string ABILITY_TYPE_SERVICE = "1"; +const std::string ABILITY_TYPE_DATA = "2"; +const std::string ABILITY_EVENT_NAME = "event_data_ability_callback"; +const std::string TEST_EVENT_NAME = "event_data_test_action"; +const std::string PAGE_STATE_ONSTART = "onStart"; +const std::string PAGE_STATE_ONACTIVE = "OnActive"; +const std::string DATA_STATE_ONSTART = "OnStart"; +const std::string DATA_STATE_ONSTOP = "OnStop"; +const std::string DATA_STATE_ONACTIVE = "OnActive"; +const std::string DATA_STATE_ONINACTIVE = "OnInactive"; +const std::string DATA_STATE_ONFOREGROUND = "OnForeground"; +const std::string DATA_STATE_ONBACKGROUND = "OnBackground"; +const std::string DATA_STATE_INSERT = "Insert"; +const std::string DATA_STATE_DELETE = "Delete"; +const std::string DATA_STATE_UPDATE = "Update"; +const std::string DATA_STATE_QUERY = "Query"; +const std::string DATA_STATE_GETFILETYPES = "GetFileTypes"; +const std::string DATA_STATE_OPENFILE = "OpenFile"; +const std::string SERVICE_STATE_ONSTART = "onStart"; +const std::string SERVICE_STATE_ONACTIVE = "OnActive"; +const std::string SERVICE_STATE_ONCOMMAND = "OnCommand"; +const std::string DATA_STATE_CHANGE = "OnStateChanged"; +const std::string DATA_STATE_ONNEWWANT = "OnNewWant"; +const std::string OPERATOR_INSERT = "Insert"; +const std::string OPERATOR_DELETE = "Delete"; +const std::string OPERATOR_UPDATE = "Update"; +const std::string OPERATOR_QUERY = "Query"; +const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; +const std::string OPERATOR_OPENFILE = "OpenFile"; +const std::string OPERATOR_GETTYPE = "GetType"; +const std::string OPERATOR_TEST_LIFECYCLE = "TestLifeCycle"; +const std::string OPERATOR_GETLIFECYCLESTATE = "GetLifecycleState"; +const std::string DEFAULT_INSERT_RESULT = "1111"; +const std::string DEFAULT_DELETE_RESULT = "2222"; +const std::string DEFAULT_UPDATE_RESULT = "3333"; +const std::string DEFAULT_OPENFILE_RESULT = "4444"; +const std::string DEFAULT_GETFILETYPE_RESULT = "filetypes"; +const std::string DEFAULT_QUERY_RESULT = "Query"; +const int WAIT_TIMEOUT = 3; +int g_StLevel = 1; +} +bool PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +class ActsAmsKitDataTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + void ResetSystem() const; + static bool SubscribeEvent(); + void ReInstallBundle() const; + void UnInstallBundle() const; + static sptr appMgrService; + static sptr abilityMgrService; + + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + + static STtools::Event event; + static StressTestLevel stLevel_; + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + PageAbilityState_ = { + {"onStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + }; + DataAbilityState_ = { + {"OnStart"}, + {"Insert"}, + {"Delete"}, + {"Update"}, + {"Query"}, + {"GetFileTypes"}, + {"OpenFile"}, + }; + AbilityOperator_ = { + {"Insert"}, + {"Delete"}, + {"Update"}, + {"Query"}, + {"GetFileTypes"}, + {"OpenFile"}, + }; + }; + ~AppEventSubscriber() + { + PageAbilityState_ = {}; + DataAbilityState_ = {}; + AbilityOperator_ = {}; + }; + virtual void OnReceiveEvent(const CommonEventData &data) override; + std::unordered_map PageAbilityState_; + std::set DataAbilityState_; + std::set AbilityOperator_; + }; +}; + +StressTestLevel ActsAmsKitDataTest::stLevel_ {}; +STtools::Event ActsAmsKitDataTest::event = STtools::Event(); + +void ActsAmsKitDataTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + std::string eventName = data.GetWant().GetAction(); + if (eventName.compare(ABILITY_EVENT_NAME) == 0) { + std::string target = data.GetData(); + if (target.find(" ") != target.npos) { + ActsAmsKitDataTest::TestCompleted(event, target, data.GetCode()); + return; + } + if (PAGE_ABILITY_CODE == data.GetCode() / ABILITY_CODE_BASE) { // page ability + ActsAmsKitDataTest::TestCompleted(event, target, data.GetCode()); + return; + } else if (DATA_ABILITY_CODE == data.GetCode() / ABILITY_CODE_BASE) { // data ability + ActsAmsKitDataTest::TestCompleted(event, target, data.GetCode()); + return; + } else if (SERVICE_ABILITY_CODE == data.GetCode() / ABILITY_CODE_BASE) { // data ability + ActsAmsKitDataTest::TestCompleted(event, target, data.GetCode()); + return; + } + } +} + +void ActsAmsKitDataTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + g_StLevel = stLevel_.AMSLevel; +} + +void ActsAmsKitDataTest::TearDownTestCase(void) +{} + +void ActsAmsKitDataTest::SetUp(void) +{ + ResetSystem(); + std::vector bundleNameSuffix = {"A", "B"}; + for (std::string suffix : bundleNameSuffix) { + STAbilityUtil::Install(HAP_NAME_BASE + suffix); + } + STAbilityUtil::CleanMsg(event); + + abilityMgrService = STAbilityUtil::GetAbilityManagerService(); + appMgrService = STAbilityUtil::GetAppMgrService(); +} + +void ActsAmsKitDataTest::TearDown(void) +{ + UnInstallBundle(); + STAbilityUtil::CleanMsg(event); +} + +bool ActsAmsKitDataTest::SubscribeEvent() +{ + std::vector eventList = {"event_data_ability_callback"}; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void ActsAmsKitDataTest::ReInstallBundle() const +{ + std::vector bundleNameSuffix = {"A", "B"}; + for (std::string suffix : bundleNameSuffix) { + STAbilityUtil::Uninstall(BUNDLE_NAME_BASE + suffix); + STAbilityUtil::Install(HAP_NAME_BASE + suffix); + } +} + +void ActsAmsKitDataTest::UnInstallBundle() const +{ + std::vector bundleNameSuffix = {"A", "B"}; + for (std::string suffix : bundleNameSuffix) { + STAbilityUtil::Uninstall(BUNDLE_NAME_BASE + suffix); + } +} + +sptr ActsAmsKitDataTest::appMgrService = nullptr; +sptr ActsAmsKitDataTest::abilityMgrService = nullptr; + +void ActsAmsKitDataTest::ResetSystem() const +{ + GTEST_LOG_(INFO) << "ResetSystem"; +} + +int ActsAmsKitDataTest::TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) +{ + GTEST_LOG_(INFO) << "TestWaitCompleted : " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} + +void ActsAmsKitDataTest::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + GTEST_LOG_(INFO) << "TestCompleted : " << eventName << " " << code; + return STAbilityUtil::Completed(event, eventName, code); +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00100 + * @tc.name : test onabilityactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the onabilityactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00100, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityActive() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00200 + * @tc.name : test onabilityactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onabilityactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00200, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityActive() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00300 + * @tc.name : test onabilityactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in the same app. Verify that the onabilityactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00300, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityActive() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00400 + * @tc.name : test onabilityactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onabilityactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00400, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityActive() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00500 + * @tc.name : test onabilityactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in the same app. Verify that the onabilityactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00500, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityActive() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_SERVICE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00600 + * @tc.name : test onabilityactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onabilityactive function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00600, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityActive() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_SERVICE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00700 + * @tc.name : test onAbilityInactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in same app. Verify that the onAbilityInactive function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00700, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityInactive() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00800 + * @tc.name : test onAbilityInactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the onAbilityInactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00800, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityInactive() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_00900 + * @tc.name : test onAbilityInactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in the same app. Verify that the onAbilityInactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_00900, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityInactive() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_00900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01000 + * @tc.name : test onAbilityInactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityInactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01000, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityInactive() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01100 + * @tc.name : test onAbilityInactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in the same app. Verify that the onAbilityInactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01100, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityInactive() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01200 + * @tc.name : test onAbilityInactive in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityInactive function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01200, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityInactive() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01300 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01300, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01400 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01400, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01500 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in the same app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01500, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01600 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01600, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01700 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in the same app. Verify that the onAbilityForeground function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01700, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01800 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityForeground function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01800, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_01900 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_01900, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 007 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_01900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02000 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02000, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 008 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02100 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in the same app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02100, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 009 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02200 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityForeground function in + * ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02200, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 010 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02300 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in the same app. Verify that the onAbilityForeground function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02300, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 011 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02400 + * @tc.name : test onAbilityForeground in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityForeground function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02400, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityForeground() 012 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02500 + * @tc.name : test onAbilityStop in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the onAbilityStop function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02500, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStop() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02600 + * @tc.name : test onAbilityStop in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityStop function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02600, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStop() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02700 + * @tc.name : test onAbilityStop in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in the same app. Verify that the onAbilityStop function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02700, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStop() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A2_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02800 + * @tc.name : test onAbilityStop in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityStop function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02800, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStop() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_02900 + * @tc.name : test onAbilityStop in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in the same app. Verify that the onAbilityStop function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_02900, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStop() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_02900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03000 + * @tc.name : test onAbilityStop in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityStop function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03000, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStop() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03100 + * @tc.name : test onAbilitySaveState in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the onAbilitySaveState function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03100, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilitySaveState(PacMap*) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03200 + * @tc.name : test onAbilitySaveState in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilitySaveState function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03200, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilitySaveState(PacMap*) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest ams_kit_data_test_032 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03300 + * @tc.name : test onAbilitySaveState in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in the same app. Verify that the onAbilitySaveState function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03300, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilitySaveState(PacMap*) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03400 + * @tc.name : test onAbilitySaveState in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilitySaveState function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03400, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilitySaveState(PacMap*) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03500 + * @tc.name : test onAbilitySaveState in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in the same app. Verify that the onAbilitySaveState function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03500, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilitySaveState(PacMap*) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03600 + * @tc.name : test onAbilitySaveState in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilitySaveState function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03600, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilitySaveState(PacMap*) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03700 + * @tc.name : test onAbilityBackground in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the onAbilityBackground function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03700, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityBackground() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03800 + * @tc.name : test onAbilityBackground in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityBackgrounds function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03800, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityBackground() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_03900 + * @tc.name : test onAbilityBackground in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityBackgrounds function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_03900, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityBackground() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_03900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04000 + * @tc.name : test onAbilityBackground in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityBackgrounds function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04000, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityBackground() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04100 + * @tc.name : test onAbilityBackground in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityBackgrounds function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04100, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityBackground() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04200 + * @tc.name : test onAbilityBackground in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityBackgrounds function + * in ability_lifecycle_callbacks is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04200, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityBackground() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04300 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04300, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04400 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04400, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04500 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04500, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A2), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04600 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04600, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_B), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04700 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04700, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04800 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04800, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_B), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_04900 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_04900, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 007 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_04900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_05000 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_05000, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 008 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_05100 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_05100, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 009 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A2), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_05200 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by data ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_05200, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 010 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_B), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_05300 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_05300, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 011 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleCallbacks_05400 + * @tc.name : test onAbilityStart in ability_lifecycle_callbacks + * @tc.desc : start data ability by service ability in different app. Verify that the onAbilityStart function + * in ability_lifecycle_callbacks is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleCallbacks_05400, Function | MediumTest | Level1) +{ + // ability_lifecycle_callbacks.h void onAbilityStart() 012 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_B), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleCallbacks_05400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00100 + * @tc.name : test insert in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the insert function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00100, Function | MediumTest | Level1) +{ + // ability.h int insert(Uri*, ValuesBucket) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00200 + * @tc.name : test insert in ability + * @tc.desc : start data ability by page ability in different app. Verify that the insert function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00200, Function | MediumTest | Level1) +{ + // ability.h int insert(Uri*, ValuesBucket) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00300 + * @tc.name : test insert in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the insert function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00300, Function | MediumTest | Level1) +{ + // ability.h int insert(Uri*, ValuesBucket) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00400 + * @tc.name : test insert in ability + * @tc.desc : start data ability by data ability in different app. Verify that the insert function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00400, Function | MediumTest | Level1) +{ + // ability.h int insert(Uri*, ValuesBucket) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00500 + * @tc.name : test insert in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the insert function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00500, Function | MediumTest | Level1) +{ + // ability.h int insert(Uri*, ValuesBucket) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00600 + * @tc.name : test insert in ability + * @tc.desc : start data ability by service ability in different app. Verify that the insert function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00600, Function | MediumTest | Level1) +{ + // ability.h int insert(Uri*, ValuesBucket) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00700 + * @tc.name : test update in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the update function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00700, Function | MediumTest | Level1) +{ + // ability.h int update(Uri, ValuesBucket, DataAbilityPredicates) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00800 + * @tc.name : test update in ability + * @tc.desc : start data ability by page ability in different app. Verify that the update function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00800, Function | MediumTest | Level1) +{ + // ability.h int update(Uri, ValuesBucket, DataAbilityPredicates) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_00900 + * @tc.name : test update in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the update function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_00900, Function | MediumTest | Level1) +{ + // ability.h int update(Uri, ValuesBucket, DataAbilityPredicates) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_UPDATE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_00900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01000 + * @tc.name : test update in ability + * @tc.desc : start data ability by data ability in different app. Verify that the update function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01000, Function | MediumTest | Level1) +{ + // ability.h int update(Uri, ValuesBucket, DataAbilityPredicates) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_UPDATE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01100 + * @tc.name : test update in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the update function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01100, Function | MediumTest | Level1) +{ + // ability.h int update(Uri, ValuesBucket, DataAbilityPredicates) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01200 + * @tc.name : test update in ability + * @tc.desc : start data ability by service ability in different app. Verify that the update function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01200, Function | MediumTest | Level1) +{ + // ability.h int update(Uri, ValuesBucket, DataAbilityPredicates) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01300 + * @tc.name : test onStart in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the onStart function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01300, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01400 + * @tc.name : test onStart in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onStart function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01400, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01500 + * @tc.name : test onStart in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the onStart function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01500, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01600 + * @tc.name : test onStart in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onStart function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01600, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01700 + * @tc.name : test onStart in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the onStart function in ability is + * executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01700, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01800 + * @tc.name : test onStart in ability + * @tc.desc : start data ability by service ability in different app. Verify that the onStart function in ability + * is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01800, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_01900 + * @tc.name : test onStart in ability + * @tc.desc : start data ability twice by page ability in the same app. Verify that the onStart function in + * ability is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_01900, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 007 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_01900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02000 + * @tc.name : test onStart in ability + * @tc.desc : start data ability twice by page ability in different app. Verify that the onStart function in + * ability is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02000, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 008 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02100 + * @tc.name : test onStart in ability + * @tc.desc : start data ability twice by data ability in the same app. Verify that the onStart function in ability + * is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02100, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 009 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A2_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02200 + * @tc.name : test onStart in ability + * @tc.desc : start data ability twice by data ability in different app. Verify that the onStart function in + * ability is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02200, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 010 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02100 + * @tc.name : test onStart in ability + * @tc.desc : start data ability twice by service ability in the same app. Verify that the onStart function in + * ability is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02300, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 011 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02200 + * @tc.name : test onStart in ability + * @tc.desc : start data ability twice by service ability in different app. Verify that the onStart function in + * ability is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02400, Function | MediumTest | Level1) +{ + // ability.h void onStart(Intent) 012 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02500 + * @tc.name : test onStop in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the onStop function in ability is not + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02500, Function | MediumTest | Level1) +{ + // ability.h void onStop() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02600 + * @tc.name : test onStop in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onStop function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02600, Function | MediumTest | Level1) +{ + // ability.h void onStop() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02700 + * @tc.name : test onStop in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the onStop function in ability is not + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02700, Function | MediumTest | Level1) +{ + // ability.h void onStop() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02800 + * @tc.name : test onStop in ability + * @tc.desc : start data ability by data ability in different app. Verify that the onStop function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02800, Function | MediumTest | Level1) +{ + // ability.h void onStop() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_02900 + * @tc.name : test onStop in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the onStop function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_02900, Function | MediumTest | Level1) +{ + // ability.h void onStop() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_02900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03000 + * @tc.name : test onStop in ability + * @tc.desc : start data ability by service ability in different app. Verify that the onStop function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03000, Function | MediumTest | Level1) +{ + // ability.h void onStop() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03100 + * @tc.name : test onNewIntent in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the onNewIntent function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03100, Function | MediumTest | Level1) +{ + // ability.h void onNewIntent(Intent) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONNEWWANT, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03200 + * @tc.name : test onNewIntent in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onNewIntent function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03200, Function | MediumTest | Level1) +{ + // ability.h void onNewIntent(Intent) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONNEWWANT, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03300 + * @tc.name : test onNewIntent in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the onNewIntent function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03300, Function | MediumTest | Level1) +{ + // ability.h void onNewIntent(Intent) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A2_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONNEWWANT, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03400 + * @tc.name : test onNewIntent in ability + * @tc.desc : start data ability by data ability in different app. Verify that the onNewIntent function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03400, Function | MediumTest | Level1) +{ + // ability.h void onNewIntent(Intent) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONNEWWANT, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03500 + * @tc.name : test onNewIntent in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the onNewIntent function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03500, Function | MediumTest | Level1) +{ + // ability.h void onNewIntent(Intent) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONNEWWANT, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03600 + * @tc.name : test onNewIntent in ability + * @tc.desc : start data ability by service ability in different app. Verify that the onNewIntent function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03600, Function | MediumTest | Level1) +{ + // ability.h void onNewIntent(Intent) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONNEWWANT, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03700 + * @tc.name : test onInactive in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the onInactive function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03700, Function | MediumTest | Level1) +{ + // ability.h void onInactive() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03800 + * @tc.name : test onInactive in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onInactive function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03800, Function | MediumTest | Level1) +{ + // ability.h void onInactive() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_03900 + * @tc.name : test onInactive in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the onInactive function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_03900, Function | MediumTest | Level1) +{ + // ability.h void onInactive() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_03900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04000 + * @tc.name : test onInactive in ability + * @tc.desc : start data ability by data ability in different app. Verify that the onInactive function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04000, Function | MediumTest | Level1) +{ + // ability.h void onInactive() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04100 + * @tc.name : test onInactive in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the onInactive function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04100, Function | MediumTest | Level1) +{ + // ability.h void onInactive() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04200 + * @tc.name : test onInactive in ability + * @tc.desc : start data ability by service ability in different app. Verify that the onInactive function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04200, Function | MediumTest | Level1) +{ + // ability.h void onInactive() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04300 + * @tc.name : test onActive in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the onActive function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04300, Function | MediumTest | Level1) +{ + // ability.h void onActive() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04400 + * @tc.name : test onActive in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onActive function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04400, Function | MediumTest | Level1) +{ + // ability.h void onActive() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04500 + * @tc.name : test onActive in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the onActive function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04500, Function | MediumTest | Level1) +{ + // ability.h void onActive() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04600 + * @tc.name : test onActive in ability + * @tc.desc : start data ability by data ability in different app. Verify that the onActive function in ability is + * not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04600, Function | MediumTest | Level1) +{ + // ability.h void onActive() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04700 + * @tc.name : test onActive in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the onActive function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04700, Function | MediumTest | Level1) +{ + // ability.h void onActive() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04800 + * @tc.name : test onActive in ability + * @tc.desc : start data ability by service ability in different app. Verify that the onActive function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04800, Function | MediumTest | Level1) +{ + // ability.h void onActive() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_04900 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the onForeground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_04900, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_04900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05000 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onForeground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05000, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05100 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the onForeground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05100, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05200 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability by data ability in different app. Verify that the onForeground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05200, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05300 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the onForeground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05300, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05400 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability by service ability in different app. Verify that the onForeground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05400, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05600 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability twice by page ability in the same app. Verify that the onForeground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05500, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 007 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05600 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability twice by page ability in different app. Verify that the onForeground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05600, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 008 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05700 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability twice by data ability in the same app. Verify that the onForeground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05700, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 009 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05800 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability twice by data ability in different app. Verify that the onForeground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05800, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 010 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_05900 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability twice by service ability in the same app. Verify that the onForeground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_05900, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 011 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_05900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06000 + * @tc.name : test onForeground in ability + * @tc.desc : start data ability twice by service ability in different app. Verify that the onForeground function + * in ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06000, Function | MediumTest | Level1) +{ + // ability.h void onForeground(Intent) 012 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06100 + * @tc.name : test onBackground in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the onBackground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06100, Function | MediumTest | Level1) +{ + // ability.h void onBackground() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06200 + * @tc.name : test onBackground in ability + * @tc.desc : start data ability by page ability in different app. Verify that the onBackground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06200, Function | MediumTest | Level1) +{ + // ability.h void onBackground() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06300 + * @tc.name : test onBackground in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the onBackground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06300, Function | MediumTest | Level1) +{ + // ability.h void onBackground() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, ABILITY_KIT_DATA_A2_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06400 + * @tc.name : test onBackground in ability + * @tc.desc : start data ability by data ability in different app. Verify that the onBackground function in ability + * is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06400, Function | MediumTest | Level1) +{ + // ability.h void onBackground() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06500 + * @tc.name : test onBackground in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the onBackground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06500, Function | MediumTest | Level1) +{ + // ability.h void onBackground() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, ABILITY_KIT_DATA_A1_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06600 + * @tc.name : test onBackground in ability + * @tc.desc : start data ability by service ability in different app. Verify that the onBackground function in + * ability is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06600, Function | MediumTest | Level1) +{ + // ability.h void onBackground() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, ABILITY_KIT_DATA_B_CODE, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06700 + * @tc.name : test delete in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the delete function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06700, Function | MediumTest | Level1) +{ + // ability.h int delete(Uri, DataAbilityPredicates) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06800 + * @tc.name : test delete in ability + * @tc.desc : start data ability by page ability in different app. Verify that the delete function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06800, Function | MediumTest | Level1) +{ + // ability.h int delete(Uri, DataAbilityPredicates) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_06900 + * @tc.name : test delete in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the delete function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_06900, Function | MediumTest | Level1) +{ + // ability.h int delete(Uri, DataAbilityPredicates) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_DELETE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_06900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07000 + * @tc.name : test delete in ability + * @tc.desc : start data ability by data ability in different app. Verify that the delete function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07000, Function | MediumTest | Level1) +{ + // ability.h int delete(Uri, DataAbilityPredicates) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_DELETE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07100 + * @tc.name : test delete in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the delete function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07100, Function | MediumTest | Level1) +{ + // ability.h int delete(Uri, DataAbilityPredicates) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07200 + * @tc.name : test delete in ability + * @tc.desc : start data ability by service ability in different app. Verify that the delete function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07200, Function | MediumTest | Level1) +{ + // ability.h int delete(Uri, DataAbilityPredicates) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07300 + * @tc.name : test getFileTypes in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the getFileTypes function in ability + * is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07300, Function | MediumTest | Level1) +{ + // ability.h String[] getFileTypes(Uri, String) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_PAGE_A_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07400 + * @tc.name : test getFileTypes in ability + * @tc.desc : start data ability by page ability in different app. Verify that the getFileTypes function in ability + * is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07400, Function | MediumTest | Level1) +{ + // ability.h String[] getFileTypes(Uri, String) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_PAGE_B_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07500 + * @tc.name : test getFileTypes in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the getFileTypes function in ability + * is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07500, Function | MediumTest | Level1) +{ + // ability.h String[] getFileTypes(Uri, String) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_DATA_A1_CODE), + 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07600 + * @tc.name : test getFileTypes in ability + * @tc.desc : start data ability by data ability in different app. Verify that the getFileTypes function in ability + * is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07600, Function | MediumTest | Level1) +{ + // ability.h String[] getFileTypes(Uri, String) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_DATA_A1_CODE), + 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07700 + * @tc.name : test getFileTypes in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the getFileTypes function in + * ability is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07700, Function | MediumTest | Level1) +{ + // ability.h String[] getFileTypes(Uri, String) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_SERVICE_A_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07800 + * @tc.name : test getFileTypes in ability + * @tc.desc : start data ability by service ability in different app. Verify that the getFileTypes function in + * ability is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07800, Function | MediumTest | Level1) +{ + // ability.h String[] getFileTypes(Uri, String) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_SERVICE_A_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_07900 + * @tc.name : test openFile in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the openFile function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_07900, Function | MediumTest | Level1) +{ + // ability.h FileDescriptor openFile(Uri, String) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_OPENFILE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_07900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08000 + * @tc.name : test openFile in ability + * @tc.desc : start data ability by page ability in different app. Verify that the openFile function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08000, Function | MediumTest | Level1) +{ + // ability.h FileDescriptor openFile(Uri, String) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_OPENFILE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08100 + * @tc.name : test openFile in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the openFile function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08100, Function | MediumTest | Level1) +{ + // ability.h FileDescriptor openFile(Uri, String) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_OPENFILE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08200 + * @tc.name : test openFile in ability + * @tc.desc : start data ability by data ability in different app. Verify that the openFile function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08200, Function | MediumTest | Level1) +{ + // ability.h FileDescriptor openFile(Uri, String) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_OPENFILE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08300 + * @tc.name : test openFile in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the openFile function in ability + * is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08300, Function | MediumTest | Level1) +{ + // ability.h FileDescriptor openFile(Uri, String) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_OPENFILE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08400 + * @tc.name : test openFile in ability + * @tc.desc : start data ability by service ability in different app. Verify that the openFile function in ability + * is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08400, Function | MediumTest | Level1) +{ + // ability.h FileDescriptor openFile(Uri, String) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_OPENFILE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_OPENFILE, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_OPENFILE + " " + DEFAULT_OPENFILE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08400 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08500 + * @tc.name : test query in ability + * @tc.desc : start data ability by page ability in the same app. Verify that the query function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08500, Function | MediumTest | Level1) +{ + // ability.h ResultSet query(Uri, string[], DataAbilityPredicates) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08500 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08600 + * @tc.name : test query in ability + * @tc.desc : start data ability by page ability in different app. Verify that the query function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08600, Function | MediumTest | Level1) +{ + // ability.h ResultSet query(Uri, string[], DataAbilityPredicates) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_B_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08600 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08700 + * @tc.name : test query in ability + * @tc.desc : start data ability by data ability in the same app. Verify that the query function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08700, Function | MediumTest | Level1) +{ + // ability.h ResultSet query(Uri, string[], DataAbilityPredicates) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_QUERY); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A2_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A2_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08700 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08800 + * @tc.name : test query in ability + * @tc.desc : start data ability by data ability in different app. Verify that the query function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08800, Function | MediumTest | Level1) +{ + // ability.h ResultSet query(Uri, string[], DataAbilityPredicates) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_QUERY); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_B_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08800 end"; +} + +/** + * @tc.number : AMS_Data_Ability_08900 + * @tc.name : test query in ability + * @tc.desc : start data ability by service ability in the same app. Verify that the query function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_08900, Function | MediumTest | Level1) +{ + // ability.h ResultSet query(Uri, string[], DataAbilityPredicates) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_08900 end"; +} + +/** + * @tc.number : AMS_Data_Ability_09000 + * @tc.name : test query in ability + * @tc.desc : start data ability by service ability in different app. Verify that the query function in ability is + * executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_09000, Function | MediumTest | Level1) +{ + // ability.h ResultSet query(Uri, string[], DataAbilityPredicates) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_B_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09000 end"; +} + +/** + * @tc.number : AMS_Data_Ability_09100 + * @tc.name : test getLifecycle in ability_lifecycle + * @tc.desc : start data ability by page ability in the same app. Verify that the getLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_09100, Function | MediumTest | Level1) +{ + // ability.h Lifecycle getLifecycle() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09100 end"; +} + +/** + * @tc.number : AMS_Data_Ability_09200 + * @tc.name : test getLifecycle in ability_lifecycle + * @tc.desc : start data ability by page ability in different app. Verify that the getLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_09200, Function | MediumTest | Level1) +{ + // ability.h Lifecycle getLifecycle() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09200 end"; +} + +/** + * @tc.number : AMS_Data_Ability_09300 + * @tc.name : test getLifecycleState in ability_lifecycle + * @tc.desc : start data ability by page ability in the same app. Verify that the getLifecycleState function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_09300, Function | MediumTest | Level1) +{ + // ability_lifecycle.h Lifecycle.Event getLifecycleState() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETLIFECYCLESTATE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETLIFECYCLESTATE + " " + OPERATOR_GETLIFECYCLESTATE, ABILITY_KIT_DATA_A1_CODE), + 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09300 end"; +} + +/** + * @tc.number : AMS_Data_Ability_09400 + * @tc.name : test getLifecycleState in ability_lifecycle + * @tc.desc : start data ability by page ability in different app. Verify that the getLifecycleState function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Ability_09400, Function | MediumTest | Level1) +{ + // ability_lifecycle.h Lifecycle.Event getLifecycleState() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETLIFECYCLESTATE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETLIFECYCLESTATE + " " + OPERATOR_GETLIFECYCLESTATE, ABILITY_KIT_DATA_A1_CODE), + 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Ability_09400 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00100 + * @tc.name : test delete in data_ability_helper + * @tc.desc : start data ability by page ability in the same app. Verify that the delete function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00100, Function | MediumTest | Level1) +{ + // data_ability_helper.h int delete(Uri, DataAbilityPredicates) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00100 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00200 + * @tc.name : test delete in data_ability_helper + * @tc.desc : start data ability by page ability in different app. Verify that the delete function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00200, Function | MediumTest | Level1) +{ + // data_ability_helper.h int delete(Uri, DataAbilityPredicates) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00200 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00300 + * @tc.name : test delete in data_ability_helper + * @tc.desc : start data ability by data ability in the same app. Verify that the delete function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00300, Function | MediumTest | Level1) +{ + // data_ability_helper.h int delete(Uri, DataAbilityPredicates) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_DELETE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00300 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00400 + * @tc.name : test delete in data_ability_helper + * @tc.desc : start data ability by data ability in different app. Verify that the delete function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00400, Function | MediumTest | Level1) +{ + // data_ability_helper.h int delete(Uri, DataAbilityPredicates) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_DELETE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00400 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00500 + * @tc.name : test delete in data_ability_helper + * @tc.desc : start data ability by service ability in the same app. Verify that the delete function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00500, Function | MediumTest | Level1) +{ + // data_ability_helper.h int delete(Uri, DataAbilityPredicates) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00500 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00600 + * @tc.name : test delete in data_ability_helper + * @tc.desc : start data ability by service ability in different app. Verify that the delete function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00600, Function | MediumTest | Level1) +{ + // data_ability_helper.h int delete(Uri, DataAbilityPredicates) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_DELETE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_DELETE, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_DELETE + " " + DEFAULT_DELETE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00600 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00700 + * @tc.name : test insert in data_ability_helper + * @tc.desc : start data ability by page ability in the same app. Verify that the insert function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00700, Function | MediumTest | Level1) +{ + // data_ability_helper.h int insert(Uri, ValuesBucket) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00700 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00800 + * @tc.name : test insert in data_ability_helper + * @tc.desc : start data ability by page ability in different app. Verify that the insert function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00800, Function | MediumTest | Level1) +{ + // data_ability_helper.h int insert(Uri, ValuesBucket) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00800 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_00900 + * @tc.name : test insert in data_ability_helper + * @tc.desc : start data ability by data ability in the same app. Verify that the insert function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_00900, Function | MediumTest | Level1) +{ + // data_ability_helper.h int insert(Uri, ValuesBucket) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_00900 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01000 + * @tc.name : test insert in data_ability_helper + * @tc.desc : start data ability by data ability in different app. Verify that the insert function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01000, Function | MediumTest | Level1) +{ + // data_ability_helper.h int insert(Uri, ValuesBucket) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01000 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01100 + * @tc.name : test insert in data_ability_helper + * @tc.desc : start data ability by service ability in the same app. Verify that the insert function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01100, Function | MediumTest | Level1) +{ + // data_ability_helper.h int insert(Uri, ValuesBucket) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01100 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01200 + * @tc.name : test insert in data_ability_helper + * @tc.desc : start data ability by service ability in different app. Verify that the insert function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01200, Function | MediumTest | Level1) +{ + // data_ability_helper.h int insert(Uri, ValuesBucket) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01200 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01300 + * @tc.name : test update in data_ability_helper + * @tc.desc : start data ability by page ability in the same app. Verify that the update function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01300, Function | MediumTest | Level1) +{ + // data_ability_helper.h int update(Uri, ValuesBucket, DataAbilityPredicates) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01300 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01400 + * @tc.name : test update in data_ability_helper + * @tc.desc : start data ability by page ability in different app. Verify that the update function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01400, Function | MediumTest | Level1) +{ + // data_ability_helper.h int update(Uri, ValuesBucket, DataAbilityPredicates) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01400 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01500 + * @tc.name : test update in data_ability_helper + * @tc.desc : start data ability by data ability in the same app. Verify that the update function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01500, Function | MediumTest | Level1) +{ + // data_ability_helper.h int update(Uri, ValuesBucket, DataAbilityPredicates) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_UPDATE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01500 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01600 + * @tc.name : test update in data_ability_helper + * @tc.desc : start data ability by data ability in different app. Verify that the update function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01600, Function | MediumTest | Level1) +{ + // data_ability_helper.h int update(Uri, ValuesBucket, DataAbilityPredicates) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_UPDATE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01600 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01700 + * @tc.name : test update in data_ability_helper + * @tc.desc : start data ability by service ability in the same app. Verify that the update function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01700, Function | MediumTest | Level1) +{ + // data_ability_helper.h int update(Uri, ValuesBucket, DataAbilityPredicates) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01700 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01800 + * @tc.name : test update in data_ability_helper + * @tc.desc : start data ability by service ability in different app. Verify that the update function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01800, Function | MediumTest | Level1) +{ + // data_ability_helper.h int update(Uri, ValuesBucket, DataAbilityPredicates) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_UPDATE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_UPDATE, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_UPDATE + " " + DEFAULT_UPDATE_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01800 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_01900 + * @tc.name : test getFileTypes in data_ability_helper + * @tc.desc : start data ability by page ability in the same app. Verify that the getFileTypes function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_01900, Function | MediumTest | Level1) +{ + // data_ability_helper.h String[] getFileTypes(Uri, String) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_PAGE_A_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_01900 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02000 + * @tc.name : test getFileTypes in data_ability_helper + * @tc.desc : start data ability by page ability in different app. Verify that the getFileTypes function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02000, Function | MediumTest | Level1) +{ + // data_ability_helper.h String[] getFileTypes(Uri, String) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_PAGE_B_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02000 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02100 + * @tc.name : test getFileTypes in data_ability_helper + * @tc.desc : start data ability by data ability in the same app. Verify that the getFileTypes function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02100, Function | MediumTest | Level1) +{ + // data_ability_helper.h String[] getFileTypes(Uri, String) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_DATA_A1_CODE), + 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02100 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02200 + * @tc.name : test getFileTypes in data_ability_helper + * @tc.desc : start data ability by data ability in different app. Verify that the getFileTypes function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02200, Function | MediumTest | Level1) +{ + // data_ability_helper.h String[] getFileTypes(Uri, String) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_DATA_A1_CODE), + 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02200 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02300 + * @tc.name : test getFileTypes in data_ability_helper + * @tc.desc : start data ability by service ability in the same app. Verify that the getFileTypes function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02300, Function | MediumTest | Level1) +{ + // data_ability_helper.h String[] getFileTypes(Uri, String) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_SERVICE_A_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02300 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02400 + * @tc.name : test getFileTypes in data_ability_helper + * @tc.desc : start data ability by service ability in different app. Verify that the getFileTypes function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02400, Function | MediumTest | Level1) +{ + // data_ability_helper.h String[] getFileTypes(Uri, String) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_SERVICE_A_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02400 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02500 + * @tc.name : test getType in data_ability_helper + * @tc.desc : start data ability by page ability in the same app. Verify that the getType function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02500, Function | MediumTest | Level1) +{ + // data_ability_helper.h String getType(Uri) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETTYPE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_GETTYPE + " ", ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02500 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02600 + * @tc.name : test getType in data_ability_helper + * @tc.desc : start data ability by page ability in different app. Verify that the getType function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02600, Function | MediumTest | Level1) +{ + // data_ability_helper.h String getType(Uri) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETTYPE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_GETTYPE + " ", ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02600 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02700 + * @tc.name : test getType in data_ability_helper + * @tc.desc : start data ability by data ability in the same app. Verify that the getType function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02700, Function | MediumTest | Level1) +{ + // data_ability_helper.h String getType(Uri) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_GETTYPE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_GETTYPE + " ", ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02700 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02800 + * @tc.name : test getType in data_ability_helper + * @tc.desc : start data ability by data ability in different app. Verify that the getType function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02800, Function | MediumTest | Level1) +{ + // data_ability_helper.h String getType(Uri) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_GETTYPE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_GETTYPE + " ", ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02800 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_02900 + * @tc.name : test getType in data_ability_helper + * @tc.desc : start data ability by service ability in the same app. Verify that the getType function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_02900, Function | MediumTest | Level1) +{ + // data_ability_helper.h String getType(Uri) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETTYPE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_GETTYPE + " ", ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_02900 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03000 + * @tc.name : test getType in data_ability_helper + * @tc.desc : start data ability by service ability in different app. Verify that the getType function in + * data_ability_helper isexecuted. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03000, Function | MediumTest | Level1) +{ + // data_ability_helper.h String getType(Uri) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_GETTYPE); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_GETTYPE + " ", ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03000 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03100 + * @tc.name : test query in data_ability_helper + * @tc.desc : start data ability by page ability in the same app. Verify that the query function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03100, Function | MediumTest | Level1) +{ + // data_ability_helper.h ResultSet query(Uri, string[], DataAbilityPredicates) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03100 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03200 + * @tc.name : test query in data_ability_helper + * @tc.desc : start data ability by page ability in different app. Verify that the query function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03200, Function | MediumTest | Level1) +{ + // data_ability_helper.h ResultSet query(Uri, string[], DataAbilityPredicates) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03200 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03300 + * @tc.name : test query in data_ability_helper + * @tc.desc : start data ability by data ability in the same app. Verify that the query function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03300, Function | MediumTest | Level1) +{ + // data_ability_helper.h ResultSet query(Uri, string[], DataAbilityPredicates) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_QUERY); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A2_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A2_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03300 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03400 + * @tc.name : test query in data_ability_helper + * @tc.desc : start data ability by data ability in different app. Verify that the query function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03400, Function | MediumTest | Level1) +{ + // data_ability_helper.h ResultSet query(Uri, string[], DataAbilityPredicates) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_QUERY); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_B_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03400 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03500 + * @tc.name : test query in data_ability_helper + * @tc.desc : start data ability by service ability in the same app. Verify that the query function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03500, Function | MediumTest | Level1) +{ + // data_ability_helper.h ResultSet query(Uri, string[], DataAbilityPredicates) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03500 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03600 + * @tc.name : test query in data_ability_helper + * @tc.desc : start data ability by service ability in different app. Verify that the query function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03600, Function | MediumTest | Level1) +{ + // data_ability_helper.h ResultSet query(Uri, string[], DataAbilityPredicates) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_QUERY); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_B_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03600 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03700 + * @tc.name : test creator in data_ability_helper + * @tc.desc : start data ability by page ability in the same app. Verify that the creator function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03700, Function | MediumTest | Level1) +{ + // data_ability_helper.h DataAbilityHelper creator(Context, Uri, bool) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_PAGE_A_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03700 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03800 + * @tc.name : test creator in data_ability_helper + * @tc.desc : start data ability by page ability in different app. Verify that the creator function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03800, Function | MediumTest | Level1) +{ + // data_ability_helper.h DataAbilityHelper creator(Context, Uri, bool) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_PAGE_B_CODE), + 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03800 end"; +} + +/** + * @tc.number : AMS_DataAbilityHelper_03900 + * @tc.name : test creator in data_ability_helper + * @tc.desc : start data ability by data ability in the same app. Verify that the creator function in + * data_ability_helper is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataAbilityHelper_03900, Function | MediumTest | Level1) +{ + // data_ability_helper.h DataAbilityHelper creator(Context, Uri, bool) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_GETFILETYPES); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_GETFILETYPES, ABILITY_KIT_DATA_A2_CODE), 0); + + EXPECT_EQ(TestWaitCompleted( + event, OPERATOR_GETFILETYPES + " " + DEFAULT_GETFILETYPE_RESULT, ABILITY_KIT_DATA_A1_CODE), + 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataAbilityHelper_03900 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00100 + * @tc.name : test getLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in the same app. Verify that the getLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00100, Function | MediumTest | Level1) +{ + // ability_lifecycle.h Lifecycle getLifecycle() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00100 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00200 + * @tc.name : test getLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the getLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00200, Function | MediumTest | Level1) +{ + // ability_lifecycle.h Lifecycle getLifecycle() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_CALLBACKS_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00200 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00300 + * @tc.name : test addObserver in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the addObserver function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00300, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void addObserver(ILifecycleObserver) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00300 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00400 + * @tc.name : test removeObserver in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the removeObserver function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00400, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void removeObserver(ILifecycleObserver) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA3", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A3), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A3_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest ams_kit_data_test_195 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00500 + * @tc.name : test dispatchLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the dispatchLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00500, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void dispatchLifecycle(Lifecycle.Event, Intent) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_TEST_LIFECYCLE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00500 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00600 + * @tc.name : test dispatchLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the dispatchLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00600, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void dispatchLifecycle(Lifecycle.Event, Intent) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_TEST_LIFECYCLE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00600 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00700 + * @tc.name : test dispatchLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the dispatchLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00700, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void dispatchLifecycle(Lifecycle.Event, Intent) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_TEST_LIFECYCLE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00700 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00800 + * @tc.name : test dispatchLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the dispatchLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00800, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void dispatchLifecycle(Lifecycle.Event, Intent) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_TEST_LIFECYCLE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00800 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_00900 + * @tc.name : test dispatchLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the dispatchLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_00900, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void dispatchLifecycle(Lifecycle.Event, Intent) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_TEST_LIFECYCLE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_00900 end"; +} + +/** + * @tc.number : AMS_Data_Lifecycle_01000 + * @tc.name : test dispatchLifecycle in ability_lifecycle_callbacks + * @tc.desc : start data ability by page ability in different app. Verify that the dispatchLifecycle function in + * ability_lifecycle is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_Lifecycle_01000, Function | MediumTest | Level1) +{ + // ability_lifecycle.h void dispatchLifecycle(Lifecycle.Event, Intent) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_01000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_TEST_LIFECYCLE); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_Lifecycle_01000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00100 + * @tc.name : test onActive in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onActive function in + * lifecycle_observer is executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00100, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onActive() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00200 + * @tc.name : test onActive in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onActive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00200, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onActive() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00300 + * @tc.name : test onActive in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onActive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00300, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onActive() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00300s end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00400 + * @tc.name : test onActive in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onActive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00400, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onActive() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00500 + * @tc.name : test onActive in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onActive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00500, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onActive() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00600 + * @tc.name : test onActive in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onActive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00600, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onActive() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONACTIVE, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00700 + * @tc.name : test onInactive in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onInactive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00700, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onInactive() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00800 + * @tc.name : test onInactive in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onInactive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00800, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onInactive() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_00900 + * @tc.name : test onInactive in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onInactive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_00900, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onInactive() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_00900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01000 + * @tc.name : test onInactive in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onInactive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01000, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onInactive() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01100 + * @tc.name : test onInactive in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onInactive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01100, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onInactive() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01200 + * @tc.name : test onInactive in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onInactive function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01200, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onInactive() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONINACTIVE, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01300 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01300, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01400 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01400, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01500 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01500, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01500s end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01600 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01600, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01700 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01700, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01800 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01800, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_01900 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability twice by page ability in the same app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_01900, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 007 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_01900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02000 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability twice by page ability in different app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02000, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 008 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02100 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability twice by data ability in the same app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02100, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 009 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02200 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability twice by data ability in different app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02200, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 010 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02300 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability twice by service ability in the same app. Verify that the onForeground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02300, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 011 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02400 + * @tc.name : test onForeground in lifecycle_observer + * @tc.desc : start data ability twice by service ability in different app. Verify that the onForeground function + * in lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02400, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onForeground(Intent) 012 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONFOREGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02500 + * @tc.name : test onStop in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onStop function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02500, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStop() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02600 + * @tc.name : test onStop in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onStop function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02600, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStop() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02700 + * @tc.name : test onStop in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onStop function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02700, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStop() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02800 + * @tc.name : test onStop in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onStop function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02800, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStop() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_02900 + * @tc.name : test onStop in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onStop function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_02900, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStop() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_02900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03000 + * @tc.name : test onStop in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onStop function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03000, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStop() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTOP, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03100 + * @tc.name : test onStateChanged in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onStateChanged function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03100, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStateChanged(Lifecycle.Event, Intent) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03200 + * @tc.name : test onStateChanged in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onStateChanged function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03200, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStateChanged(Lifecycle.Event, Intent) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03300 + * @tc.name : test onStateChanged in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onStateChanged function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03300, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStateChanged(Lifecycle.Event, Intent) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03400 + * @tc.name : test onStateChanged in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onStateChanged function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03400, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStateChanged(Lifecycle.Event, Intent) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03500 + * @tc.name : test onStateChanged in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onStateChanged function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03500, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStateChanged(Lifecycle.Event, Intent) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03600 + * @tc.name : test onStateChanged in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onStateChanged function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03600, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStateChanged(Lifecycle.Event, Intent) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_CHANGE, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03700 + * @tc.name : test onBackground in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onBackground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03700, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onBackground() 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03800 + * @tc.name : test onBackground in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onBackground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03800, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onBackground() 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_03900 + * @tc.name : test onBackground in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onBackground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_03900, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onBackground() 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_03900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04000 + * @tc.name : test onBackground in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onBackground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04000, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onBackground() 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04100 + * @tc.name : test onBackground in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onBackground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04100, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onBackground() 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04200 + * @tc.name : test onBackground in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onBackground function in + * lifecycle_observer is not executed. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04200, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onBackground() 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONBACKGROUND, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04300 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04300, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04400 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04400, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 002 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04400 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04500 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04500, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 003 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04500 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A2), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04500 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04600 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04600, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 004 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04600 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_B), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04600 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04700 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04700, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 005 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04700 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04700 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04800 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04800, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 006 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04800 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_B), 0); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04800 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_04900 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by page ability in the same app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_04900, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 007 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04900 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_04900 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_05000 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by page ability in different app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_05000, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 008 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05000 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName = ABILITY_NAME_BASE + "PageB"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(third); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_B_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_B_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_PAGE_B_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05000 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_05100 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by data ability in the same app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_05100, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 009 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05100 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA2", OPERATOR_INSERT); + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A2), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A2, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05100 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_05200 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by data ability in different app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_05200, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 010 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05200 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_QUERY); + std::shared_ptr third = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr third1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + + first->AddChildOperator(second); + second->AddChildOperator(third); + second->AddChildOperator(third1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONSTART, ABILITY_KIT_PAGE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, PAGE_STATE_ONACTIVE, ABILITY_KIT_PAGE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_PAGE_A_CODE, PAGE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_QUERY, ABILITY_KIT_DATA_A1_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_DATA_A1_CODE, DATA_STATE_QUERY); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_B), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, OPERATOR_QUERY + " " + DEFAULT_QUERY_RESULT, ABILITY_KIT_PAGE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05200 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_05300 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by service ability in the same app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_05300, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 011 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05300 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "A", ABILITY_NAME_BASE + "DataA1", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_A1, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_A1_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05300 end"; +} + +/** + * @tc.number : AMS_Data_LifeCycleObserver_05400 + * @tc.name : test onStart in lifecycle_observer + * @tc.desc : start data ability by service ability in different app. Verify that the onStart function in + * lifecycle_observer is executed only once. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_Data_LifeCycleObserver_05400, Function | MediumTest | Level1) +{ + // lifecycle_observer.h void onStart(Intent) 012 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05400 start"; + STAbilityUtil::CleanMsg(event); + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "ServiceA"; + + std::shared_ptr first = std::make_shared(ABILITY_TYPE_PAGE, bundleName, abilityName); + std::shared_ptr second = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + std::shared_ptr second1 = std::make_shared( + ABILITY_TYPE_DATA, BUNDLE_NAME_BASE + "B", ABILITY_NAME_BASE + "DataB", OPERATOR_INSERT); + first->AddChildOperator(second); + first->AddChildOperator(second1); + std::vector vectorOperator = STAbilityUtil::SerializationStOperatorToVector(*first); + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, vectorOperator); + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "StartAbility start"; + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService); + GTEST_LOG_(INFO) << eCode; + GTEST_LOG_(INFO) << "StartAbility done"; + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONSTART, ABILITY_KIT_SERVICE_A_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, SERVICE_STATE_ONCOMMAND, ABILITY_KIT_SERVICE_A_CODE), 0); + PublishEvent(TEST_EVENT_NAME, ABILITY_KIT_SERVICE_A_CODE, SERVICE_STATE_ONACTIVE); + + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_B), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + EXPECT_NE(TestWaitCompleted(event, DATA_STATE_ONSTART, LIFECYCLE_OBSERVER_B, WAIT_TIMEOUT), 0); + EXPECT_EQ(TestWaitCompleted(event, DATA_STATE_INSERT, ABILITY_KIT_DATA_B_CODE), 0); + + EXPECT_EQ( + TestWaitCompleted(event, OPERATOR_INSERT + " " + DEFAULT_INSERT_RESULT, ABILITY_KIT_SERVICE_A_CODE), 0); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_Data_LifeCycleObserver_05400 end"; +} + +/** + * @tc.number : AMS_DataUriUtils_0100 + * @tc.name : test attachId in data_uri_utils + * @tc.desc : Verify that the attachId function in data_uri_utils is executed. Verify that the result is right. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataUriUtils_0100, Function | MediumTest | Level1) +{ + // data_uri_utils.h Uri attachId(Uri, long) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataUriUtils_0100 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + Uri dataAbilityUri("dataability:///" + bundleName + "." + abilityName); + + long Id = DEFAULT_ID; + dataAbilityUri = DataUriUtils::AttachId(dataAbilityUri, Id); + + EXPECT_TRUE(DataUriUtils::IsAttachedId(dataAbilityUri)); + + EXPECT_EQ(Id, DataUriUtils::GetId(dataAbilityUri)); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataUriUtils_0100 end"; +} + +/** + * @tc.number : AMS_DataUriUtils_0200 + * @tc.name : test getId in data_uri_utils + * @tc.desc : Verify that the getId function in data_uri_utils is executed. Verify that the result is right. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataUriUtils_0200, Function | MediumTest | Level1) +{ + // data_uri_utils.h long getId(Uri) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataUriUtils_0200 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + Uri dataAbilityUri("dataability:///" + bundleName + "." + abilityName); + + const int errorCode = -1; + EXPECT_EQ(errorCode, DataUriUtils::GetId(dataAbilityUri)); + + long Id = DEFAULT_ID; + dataAbilityUri = DataUriUtils::AttachId(dataAbilityUri, Id); + + EXPECT_TRUE(DataUriUtils::IsAttachedId(dataAbilityUri)); + + EXPECT_EQ(Id, DataUriUtils::GetId(dataAbilityUri)); + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataUriUtils_0200 end"; +} + +/** + * @tc.number : AMS_DataUriUtils_0300 + * @tc.name : test deleteId in data_uri_utils + * @tc.desc : Verify that the deleteId function in data_uri_utils is executed. Verify that the result is right. + */ +HWTEST_F(ActsAmsKitDataTest, AMS_DataUriUtils_0300, Function | MediumTest | Level1) +{ + // data_uri_utils.h Uri deleteId(Uri) 001 + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataUriUtils_0300 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "PageA"; + + for (int i = 0; i < g_StLevel; i++) { + STAbilityUtil::CleanMsg(event); + Uri dataAbilityUri("dataability:///" + bundleName + "." + abilityName); + + long Id = DEFAULT_ID; + dataAbilityUri = DataUriUtils::AttachId(dataAbilityUri, Id); + GTEST_LOG_(INFO) << "DataUriUtils::AttachId(dataAbilityUri, Id)"; + + EXPECT_TRUE(DataUriUtils::IsAttachedId(dataAbilityUri)); + GTEST_LOG_(INFO) << "EXPECT_TRUE(DataUriUtils::IsAttachedId(dataAbilityUri))"; + + EXPECT_EQ(Id, DataUriUtils::GetId(dataAbilityUri)); + GTEST_LOG_(INFO) << "EXPECT_EQ(Id, DataUriUtils::GetId(dataAbilityUri))"; + + dataAbilityUri = DataUriUtils::DeleteId(dataAbilityUri); + GTEST_LOG_(INFO) << "DataUriUtils::DeleteId(dataAbilityUri)"; + + const int errorCode = -1; + EXPECT_EQ(errorCode, DataUriUtils::GetId(dataAbilityUri)); + GTEST_LOG_(INFO) << "DataUriUtils::GetId(dataAbilityUri))"; + + EXPECT_FALSE(DataUriUtils::IsAttachedId(dataAbilityUri)); + GTEST_LOG_(INFO) << "DataUriUtils::IsAttachedId(dataAbilityUri)"; + ReInstallBundle(); + } + GTEST_LOG_(INFO) << "ActsAmsKitDataTest AMS_DataUriUtils_0300 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_lifecycle_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_lifecycle_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..449dd0a8df47c995de2f01a8d000a588e4abd9d5 --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_lifecycle_test.cpp @@ -0,0 +1,7658 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "event.h" +#include "ability_lifecycle_executor.h" +#include "ability_lifecycle.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "kit_test_common_info.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; +using MAP_STR_STR = std::map; + +static const std::string kitPageBundleName = "com.ohos.amsst.page.AppKitA"; +static const std::string ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS = "LifecycleCallbacksAbility"; +static const std::string ABILTIY_NAME_ABILITY_CONTEXT = "AbilityContextAbility"; +static const std::string ABILTIY_NAME_ABILITY = "AbilityAbility"; +static const std::string ABILTIY_NAME_ABILITY_LIFE_CYCLE = "AbilityLifeCycleAbility"; +static const std::string ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER = "LifeCycleObserverAbility"; +static const std::string EVENT_RESP_LIFECYCLE_CALLBACK = + "resp_com_ohos_amsst_appkit_service_ability_lifecycle_callbacks"; +static const std::string EVENT_RESP_LIFECYCLE_OBSERVER = "resp_com_ohos_amsst_appkit_service_lifecycle_observer"; +static const std::string EVENT_RESP_FIRST_ABILITY = "resp_com_ohos_amsst_appkit_service_mainabilitydemo"; +static const std::string EVENT_RESP_SECOND_ABILITY = "resp_com_ohos_amsst_appkit_service_secondability"; +static const std::string EVENT_RESP_KITTEST_COMPLETE = "resp_com_ohos_amsst_appkit_service_kittest_completed"; +static const std::string EVENT_REQU_KITTEST = "requ_com_ohos_amsst_appkit_service_kittest"; +static const std::string EVENT_RESP_SECOND_ABILITY_CONTEXT = + "resp_com_ohos_amsst_appkit_service_secondability_ability_context"; +static const std::string EVENT_REQU_KITTEST_SECOND = "resp_com_ohos_amsst_appkit_service_secondability_kittest"; +static const std::string APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME = + "resp_com_ohos_amsst_service_app_life_cycle_call_backs"; +static const std::string APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME = + "req_com_ohos_amsst_service_app_life_cycle_call_backs"; +static const std::string APP_ABILITY_CONTEXT_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_context"; +static const std::string APP_ABILITY_CONTEXT_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_context"; +static const std::string APP_ABILITY_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability"; +static const std::string APP_ABILITY_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability"; +static const std::string APP_ABILITY_CONNECTION_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_connection"; +static const std::string APP_ABILITY_CONNECTION_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_connection"; +static const std::string APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_life_cycle"; +static const std::string APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_life_cycle"; +static const std::string APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME = + "resp_com_ohos_amsst_service_app_life_cycle_observer"; +static const std::string APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_life_cycle_observer"; +static const std::string EVENT_RESP_ON_ABILITY_RESULT = "resp_com_ohos_amsst_appkit_mainabilitydemo_onabilityresult"; +std::vector bundleNameList = { + "com.ohos.amsst.page.AppKitA", + "com.ohos.amsst.service.appA", + "com.ohos.amsst.service.AppKit", +}; +std::vector hapNameList = { + "amsKitSystemTestPageA", + "amsSystemTestServiceA", + "amsKitSystemTestService", +}; +constexpr int WAIT_TIME = 1000; +constexpr int DELAY_TIME = 3; +constexpr int WAIT_ABILITY_OK = 3 * 1000; +} // namespace + +class ActsAmsKitLifecycleTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber() = default; + }; + + static sptr appMs; + static sptr abilityMs; + static Event event; + static std::unordered_map mapState; + static std::vector eventList; + static std::shared_ptr subscriber; + + static StressTestLevel stLevel_; +}; + +StressTestLevel ActsAmsKitLifecycleTest::stLevel_ = {}; + +std::vector ActsAmsKitLifecycleTest::eventList = { + EVENT_RESP_LIFECYCLE_CALLBACK, + EVENT_RESP_LIFECYCLE_OBSERVER, + EVENT_RESP_FIRST_ABILITY, + EVENT_RESP_KITTEST_COMPLETE, + EVENT_RESP_SECOND_ABILITY_CONTEXT, + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, + APP_ABILITY_RESP_EVENT_NAME, + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, +}; + +Event ActsAmsKitLifecycleTest::event = Event(); +sptr ActsAmsKitLifecycleTest::appMs = nullptr; +sptr ActsAmsKitLifecycleTest::abilityMs = nullptr; + +std::shared_ptr ActsAmsKitLifecycleTest::subscriber = nullptr; + +std::unordered_map ActsAmsKitLifecycleTest::mapState = { + {"OnStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnAbilityActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnAbilityInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnAbilityForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, +}; + +void ActsAmsKitLifecycleTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto iter = std::find(eventList.begin(), eventList.end(), eventName); + if (iter != eventList.end()) { + STAbilityUtil::Completed(event, data.GetData(), data.GetCode()); + } +} + +void ActsAmsKitLifecycleTest::SetUpTestCase(void) +{ + STAbilityUtil::InstallHaps(hapNameList); + TestConfigParser tcp; + stLevel_.AMSLevel = 1; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + usleep(WAIT_TIME); +} + +void ActsAmsKitLifecycleTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber); + STAbilityUtil::UninstallBundle(bundleNameList); +} + +void ActsAmsKitLifecycleTest::SetUp(void) +{ + abilityMs = STAbilityUtil::GetAbilityManagerService(); + appMs = STAbilityUtil::GetAppMgrService(); +} + +void ActsAmsKitLifecycleTest::TearDown(void) +{ + STAbilityUtil::CleanMsg(event); +} + +bool ActsAmsKitLifecycleTest::SubscribeEvent() +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00100 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00100 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00200 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00200 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00300 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00300 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00400 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00400 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00500 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00500 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00600 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00600 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00700 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00700 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00800 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00800 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_00900 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_00900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_00900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_00900 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01000 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01000 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01100 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01100 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01200 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01200 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01300 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01300 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01400 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01400 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01500 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01500 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01600 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01600 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01700 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01700 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01800 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01800 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_01900 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_01900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_01900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_01900 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02000 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02000 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02100 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02100 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02200 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02200 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02300 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02300 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02400 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02400 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02500 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02500 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02600 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilitySaveState event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02600 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02700 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilitySaveState event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02700 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02800 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilitySaveState event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02800 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_02900 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_02900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_02900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_02900 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_03000 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_03000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03000 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_03100 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_03100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03100 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_03200 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_03200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03200 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_03300 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_03300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03300 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_03400 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_03400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03400 end"; +} + +/** + * @tc.number : AMS_Page_LifeCycleCallbacks_03500 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifeCycleCallbacks_03500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifeCycleCallbacks_03500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifeCycleCallbacks_03500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_03600 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Ability to terminate yourself. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_03600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_03600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_03600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_03700 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate other services in the same application. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_03700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_03700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_03700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_03800 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate services in another application. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_03800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_03800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_03800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_03900 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate the same page in the same application multiple times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_03900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_03900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_03900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_03900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04000 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate a non-existent page. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04100 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : No processing is done in the OnAbilityResult event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04200 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Start a task in the OnAbilityResult event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04300 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Start the while loop in the OnAbilityResult event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04400 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04500 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04600 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : No processing is done in the OnStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04700 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Start a task in the OnStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04800 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Start the while loop in the OnStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_04900 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_04900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_04900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_04900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_04900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05000 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05100 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : No processing is done in the OnStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05100 : " << i; + break; + } + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05200 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Start a task in the OnStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05200 : " << i; + break; + } + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05300 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Start the while loop in the OnStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05300 : " << i; + break; + } + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05400 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05400 : " << i; + break; + } + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05500 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05500 : " << i; + break; + } + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05600 + * @tc.name : Test the OnNewIntent event in the Ability class + * @tc.desc : No processing is done in the OnNewIntent event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewIntent", mapState["OnNewIntent"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05700 + * @tc.name : Test the OnNewIntent event in the Ability class + * @tc.desc : Start a task in the OnNewIntent event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewIntent", mapState["OnNewIntent"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05800 + * @tc.name : Test the OnNewIntent event in the Ability class + * @tc.desc : Start the while loop in the OnNewIntent event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewIntent", mapState["OnNewIntent"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_05900 + * @tc.name : Test the OnNewIntent event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_05900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewIntent", mapState["OnNewIntent"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_05900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_05900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_05900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06000 + * @tc.name : Test the OnNewIntent event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewIntent", mapState["OnNewIntent"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06100 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : No processing is done in the OnInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06200 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Start a task in the OnInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06300 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Start the while loop in the OnInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06400 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06500 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06600 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : No processing is done in the OnActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06700 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Start a task in the OnActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06800 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Start the while loop in the OnActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_06900 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_06900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_06900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_06900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_06900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07000 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07100 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : No processing is done in the OnForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07200 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Start a task in the OnForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07300 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Start the while loop in the OnForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07400 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07500 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07600 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : No processing is done in the OnBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07700 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Start a task in the OnBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07800 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Start the while loop in the OnBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_07900 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_07900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_07900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_07900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_07900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08000 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08100 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : No processing is done in the OnAbilityResult event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08200 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Start a task in the OnAbilityResult event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08300 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Start the while loop in the OnAbilityResult event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08400 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08500 + * @tc.name : Test the OnAbilityResult event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityForResult"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStartAbilityForResult", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityResult", mapState["OnAbilityResult"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08600 + * @tc.name : Test the StartAbility method in the Ability class + * @tc.desc : No processing is done in the StartAbility event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08600 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08700 + * @tc.name : Test the StartAbility method in the Ability class + * @tc.desc : Start a task in the StartAbility event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08700 : " << i; + break; + } + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08800 + * @tc.name : Test the StartAbility method in the Ability class + * @tc.desc : Start the while loop in the StartAbility event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08800 : " << i; + break; + } + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_08900 + * @tc.name : Test the StartAbility method in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_08900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_08900 : " << i; + break; + } + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_08900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_08900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09000 + * @tc.name : Test the StartAbility method in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09000 : " << i; + break; + } + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09100 + * @tc.name : Test the StartAbility method with AbilityStartSetting in the Ability class + * @tc.desc : Ability to start yourself. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09100 start"; + + MAP_STR_STR params; + + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityWithSetting"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbilityWithSetting", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09100 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09200 + * @tc.name : Test the StartAbility method with AbilityStartSetting in the Ability class + * @tc.desc : Start other services in the same application. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityWithSetting"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbilityWithSetting", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09200 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09300 + * @tc.name : Test the StartAbility method with AbilityStartSetting in the Ability class + * @tc.desc : Start services in another application. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityWithSetting"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbilityWithSetting", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09300 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09400 + * @tc.name : Test the StartAbility method with AbilityStartSetting in the Ability class + * @tc.desc : Start the same page in the same application multiple times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityWithSetting"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbilityWithSetting", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09400 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09500 + * @tc.name : Test the StartAbility method with AbilityStartSetting in the Ability class + * @tc.desc : Start a non-existent page. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StartAbilityWithSetting"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbilityWithSetting", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09500 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09600 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Get life cycle object. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09600 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09700 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Get the lifecycle object multiple times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09700 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09800 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call GetLifecycleState. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09800 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_09900 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call AddObserver. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_09900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_09900 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_09900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_09900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10000 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call DispatchLifecycle. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10000 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10100 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call RemoveObserver. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10100 start"; + + MAP_STR_STR params; + params["No."] = "6"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10100 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10200 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnStart function. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10200 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 4, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10200 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10300 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnActive function. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10300 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10300 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10400 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnBackground function. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10400 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 3, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10500 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in Init function. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10500 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 6, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10600 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnInactive function. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10600 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 6, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 3, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10700 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnForeground function. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10700 start"; + + MAP_STR_STR params; + params["No."] = "6"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnForeground", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10800 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnBackground function. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10800 start"; + + MAP_STR_STR params; + params["No."] = "7"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_10900 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add an observer object. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_10900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10900 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_10900 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_10900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_10900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11000 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add an observer object multi times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11000 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11000 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11100 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add multi observer objects. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11100 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11100 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11200 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add multi observer objects. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11200 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11200 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11300 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add multi observer objects. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11300 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11300 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11400 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_ACTIVE. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11400 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11500 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_FOREGROUND. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11500 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11500 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "OnForeground", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11600 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_BACKGROUND. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11600 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11700 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_INACTIVE. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11700 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11700 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11800 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_START. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11800 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11800 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11800 end"; +} + +/** + * @tc.number : AMS_Page_Ability_11900 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_STOP. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_11900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11900 start"; + + MAP_STR_STR params; + params["No."] = "6"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_11900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_11900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_11900 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12000 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle UNDEFINED. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12000 start"; + + MAP_STR_STR params; + params["No."] = "7"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12000 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "UnDefine", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12000 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12100 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_ACTIVE. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12100 start"; + + MAP_STR_STR params; + params["No."] = "8"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12100 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12200 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle UNDEFINED. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12200 start"; + + MAP_STR_STR params; + params["No."] = "9"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12200 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "UnDefine", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12200 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12300 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove a non-existent observer. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12300 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12300 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12300 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12400 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove the same observer multiple times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12400 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12400 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12400 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12500 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove different observers multiple times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12500 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12500 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12500 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12600 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove different observers multiple times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12600 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12600 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12600 end"; +} + +/** + * @tc.number : AMS_Page_Ability_12700 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove different observers multiple times. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_Ability_12700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12700 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_Ability_12700 : " << i; + break; + } + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Ability_12700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_Ability_12700 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_12800 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_12800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_12800 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_12800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_12800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_12800 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_12900 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Start a task in the OnActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_12900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_12900 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_12900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_12900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_12900 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13000 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnActive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13000 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13000 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13100 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13100 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13100 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13200 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13200 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13200 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13300 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13300 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13300 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13400 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Start a task in the OnBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13400 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13400 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13500 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnBackground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13500 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13500 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13600 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13600 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13600 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13700 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13700 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13700 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13800 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13800 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13800 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_13900 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Start a task in the OnForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_13900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13900 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_13900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_13900 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14000 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnForeground event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14000 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14000 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14100 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14100 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14100 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14200 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14200 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14200 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14300 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14300 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14300 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14400 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Start a task in the OnInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14400 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14400 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14500 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnInactive event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14500 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14500 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14600 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14600 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14600 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14700 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14700 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14700 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14800 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14800 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14800 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_14900 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Start a task in the OnStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_14900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14900 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_14900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_14900 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15000 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnStart event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15000 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15000 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15100 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15100 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15100 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15200 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15200 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15200 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15300 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15300 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15300 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15400 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Start a task in the OnStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15400 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15400 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15500 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnStop event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15500 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15500 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15600 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15600 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15600 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15700 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15700 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15700 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15800 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnStateChanged event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15800 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", mapState["OnStateChanged"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15800 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_15900 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Start a task in the OnStateChanged event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_15900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15900 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", mapState["OnStateChanged"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_15900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_15900 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_16000 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnStateChanged event. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_16000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_16000 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", mapState["OnStateChanged"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_16000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_16000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_16000 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_16100 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_16100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_16100 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", mapState["OnStateChanged"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_16100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_16100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_16100 end"; +} + +/** + * @tc.number : AMS_Page_LifecycleObserver_16200 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitLifecycleTest, AMS_Page_LifecycleObserver_16200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_16200 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = + STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, kitPageBundleName, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", mapState["OnStateChanged"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_16200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME, 1, "StopSelfAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_LifecycleObserver_16200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitLifecycleTest AMS_Page_LifecycleObserver_16200 end"; +} diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_processinfo_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_processinfo_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23cd159eb1e47db4b9225865b0b941af9a4e7b67 --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_processinfo_test.cpp @@ -0,0 +1,2125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "event.h" +#include "ability_lifecycle_executor.h" +#include "ability_lifecycle.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "kit_test_common_info.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; +using MAP_STR_STR = std::map; + +static const std::string bundleName = "com.ohos.amsst.AppKit"; +static const std::string thirdAbilityName = "ThirdAbility"; +static const std::string fifthAbilityName = "FifthAbility"; + +std::vector bundleNameList = { + "com.ohos.amsst.AppKit", +}; +std::vector hapNameList = { + "amsKitSystemTest", +}; +constexpr int WAIT_TIME = 1000; + +int amsKitSTCode = 0; +int amsKitSystemTestFifthAbilityCode = 0; +const int delay = 10; +} // namespace + +class ActsAmsKitProcessInfoTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + void TestSkills(Want want); + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + void StartSecondAbility(); + void StartFifthAbility(); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber() = default; + }; + + static sptr appMs; + static sptr abilityMs; + static Event event; + static Event abilityEvent; + static std::unordered_map mapState; + static std::vector eventList; + static StressTestLevel stLevel_; + static std::shared_ptr subscriber_; +}; + +std::vector ActsAmsKitProcessInfoTest::eventList = { + g_respPageThirdAbilityST, + g_EVENT_RESP_FIFTH, +}; + +StressTestLevel ActsAmsKitProcessInfoTest::stLevel_ {}; +std::shared_ptr ActsAmsKitProcessInfoTest::subscriber_ = nullptr; + +Event ActsAmsKitProcessInfoTest::event = Event(); +Event ActsAmsKitProcessInfoTest::abilityEvent = Event(); +sptr ActsAmsKitProcessInfoTest::appMs = nullptr; +sptr ActsAmsKitProcessInfoTest::abilityMs = nullptr; +std::unordered_map ActsAmsKitProcessInfoTest::mapState = { + {"OnStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnAbilityActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnAbilityInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnAbilityForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, +}; + +void ActsAmsKitProcessInfoTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + STAbilityUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); + STAbilityUtil::Completed(abilityEvent, data.GetData(), data.GetCode()); + + auto eventName = data.GetWant().GetAction(); + auto iter = std::find(eventList.begin(), eventList.end(), eventName); + if (iter != eventList.end()) { + STAbilityUtil::Completed(event, data.GetData(), data.GetCode()); + } +} + +void ActsAmsKitProcessInfoTest::SetUpTestCase(void) +{ + STAbilityUtil::InstallHaps(hapNameList); + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; +} + +void ActsAmsKitProcessInfoTest::TearDownTestCase(void) +{ + STAbilityUtil::UninstallBundle(bundleNameList); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ActsAmsKitProcessInfoTest::SetUp(void) +{} + +void ActsAmsKitProcessInfoTest::TearDown(void) +{ + STAbilityUtil::CleanMsg(event); + STAbilityUtil::CleanMsg(abilityEvent); +} + +bool ActsAmsKitProcessInfoTest::SubscribeEvent() +{ + const std::vector eventList = { + g_respPageThirdAbilityST, + g_EVENT_RESP_FIFTH, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ActsAmsKitProcessInfoTest::StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName) +{ + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, abilityName + g_abilityStateOnActive, 0), 0); +} + +void ActsAmsKitProcessInfoTest::StartFifthAbility() +{ + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", fifthAbilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, mapState["onActive"], 0)); +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0100 + * @tc.name : ProcessInfo::GetPid + * @tc.desc : judge whether the current process id is greater than 0 + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetPid)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0200 + * @tc.name : ProcessInfo::GetPid + * @tc.desc : get the intermediate value of process id + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetPid)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0300 + * @tc.name : ProcessInfo::GetPid + * @tc.desc : get the minimum value of process id + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetPid)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0400 + * @tc.name : ProcessInfo::GetPid + * @tc.desc : get the maximum value of process id + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetPid)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0500 + * @tc.name : ProcessInfo::GetProcessName + * @tc.desc : determine whether the current process name is equal to bundlename + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetProcessName)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0600 + * @tc.name : ProcessInfo::GetProcessName + * @tc.desc : get a null value of process name + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetProcessName)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0700 + * @tc.name : ProcessInfo::GetProcessName + * @tc.desc : gets the normal character of the process name + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetProcessName)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0800 + * @tc.name : ProcessInfo::GetProcessName + * @tc.desc : gets the special character of the process name + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::GetProcessName)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_0900 + * @tc.name : ProcessInfo::Marshalling + * @tc.desc : marshaling the current process ,get the processname after marshaling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_0900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Marshalling)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_0900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1000 + * @tc.name : ProcessInfo::Marshalling + * @tc.desc : marshaling the current process ,get the processid after marshaling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Marshalling)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1100 + * @tc.name : ProcessInfo::Marshalling + * @tc.desc : marshaling the construction processinfo ,get the processname after marshaling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Marshalling)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1200 + * @tc.name : ProcessInfo::Marshalling + * @tc.desc : marshaling the construction processinfo ,get the processid(minimum) after marshaling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Marshalling)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1300 + * @tc.name : ProcessInfo::Marshalling + * @tc.desc : marshaling the current process ,get the processname(null) after marshaling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Marshalling)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1400 + * @tc.name : ProcessInfo::Marshalling + * @tc.desc : marshaling the construction processinfo ,get the processid(maximum) after marshaling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Marshalling)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1500 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : use special string to customize parcel and test processInfo after unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1600 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : use normal string to customize parcel and test processInfo after unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1700 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : use null string to customize parcel and test processInfo after unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1800 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : use 0 to customize parcel and test processInfo after unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_1900 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : use minimum to customize parcel and test processInfo after unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_1900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_1900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2000 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : use maximum to customize parcel and test processInfo after unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2100 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : constructing processInfo with normal strings and minimum values, + * compare the data after marshalling and unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2200 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : constructing processInfo with special strings and maximum values, + * compare the data after marshalling and unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2300 + * @tc.name : ProcessInfo::Unmarshalling + * @tc.desc : constructing processInfo with special strings and minimum values, + * compare the data after marshalling and unmarshalling + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::Unmarshalling)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2400 + * @tc.name : ProcessInfoApi::ProcessInfo + * @tc.desc : use the constructor without parameters, judge determine the PID of the current object + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2500 + * @tc.name : ProcessInfoApi::ProcessInfo + * @tc.desc : use the constructor without parameters, + * judge determine the processName of the current object + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2600 + * @tc.name : ProcessInfo_String_int + * @tc.desc : use the constructor with parameters (PID is 0, processname is normal string), + * judge whether PID and processname are the same as the parameters + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = + "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo_String_int)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2700 + * @tc.name : ProcessInfo_String_int + * @tc.desc : use the constructor with parameters (PID is mininum, processname is normal string), + * judge whether PID and processname are the same as the parameters + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = + "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo_String_int)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2800 + * @tc.name : ProcessInfo_String_int + * @tc.desc : use the constructor with parameters (PID is maxinum, processname is normal string), + * judge whether PID and processname are the same as the parameters + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = + "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo_String_int)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_2900 + * @tc.name : ProcessInfo_String_int + * @tc.desc : use the constructor with parameters (PID is 0, processname is special string), + * judge whether PID and processname are the same as the parameters + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_2900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = + "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo_String_int)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_2900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_3000 + * @tc.name : ProcessInfo_String_int + * @tc.desc : use the constructor with parameters (PID is mininum, processname is special string), + * judge whether PID and processname are the same as the parameters + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_3000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = + "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo_String_int)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_3000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_ProcessInfo_3100 + * @tc.name : ProcessInfo_String_int + * @tc.desc : use the constructor with parameters (PID is maxinum, processname is special string), + * judge whether PID and processname are the same as the parameters + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_ProcessInfo_3100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(thirdAbilityName, bundleName); + std::string eventData = + "ProcessInfoApi_" + std::to_string(static_cast(ProcessInfoApi::ProcessInfo_String_int)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageThirdAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageThirdAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageThirdAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_ProcessInfo_3100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0100 + * @tc.name : WantParams.SetParam + * @tc.desc : set string param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0100, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0200 + * @tc.name : WantParams.SetParam + * @tc.desc : set bool param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0200, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0300 + * @tc.name : WantParams.SetParam + * @tc.desc : set byte param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0300, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0400 + * @tc.name : WantParams.SetParam + * @tc.desc : set char param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0400, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0500 + * @tc.name : WantParams.SetParam + * @tc.desc : set short param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0500, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0600 + * @tc.name : WantParams.SetParam + * @tc.desc : set int param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0600, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0700 + * @tc.name : WantParams.SetParam + * @tc.desc : set long param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0700, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0800 + * @tc.name : WantParams.SetParam + * @tc.desc : set float param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0800, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_0900 + * @tc.name : WantParams.SetParam + * @tc.desc : set double param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_0900, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_0900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1000 + * @tc.name : WantParams.SetParam + * @tc.desc : set string array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1000, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_9"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1100 + * @tc.name : WantParams.SetParam + * @tc.desc : set bool array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1100, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_10"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1200 + * @tc.name : WantParams.SetParam + * @tc.desc : set byte array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1200, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_11"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1300 + * @tc.name : WantParams.SetParam + * @tc.desc : set char array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1300, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_12"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1400 + * @tc.name : WantParams.SetParam + * @tc.desc : set short array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1400, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_13"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1500 + * @tc.name : WantParams.SetParam + * @tc.desc : set int array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1500, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_14"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1600 + * @tc.name : WantParams.SetParam + * @tc.desc : set long array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1600, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_15"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1700 + * @tc.name : WantParams.SetParam + * @tc.desc : set float array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1700, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_16"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1800 + * @tc.name : WantParams.SetParam + * @tc.desc : set double array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1800, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::SetParam) + "_17"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_1900 + * @tc.name : WantParams.HasParam + * @tc.desc : empty key on empty WantParams + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_1900, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::HasParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_1900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2000 + * @tc.name : WantParams.HasParam + * @tc.desc : empty key has value + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2000, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::HasParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2100 + * @tc.name : WantParams.HasParam + * @tc.desc : not empty key on empty WantParams + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2100, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::HasParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2200 + * @tc.name : WantParams.HasParam + * @tc.desc : not empty key has a value + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2200, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::HasParam) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2300 + * @tc.name : WantParams.HasParam + * @tc.desc : key with special character has a value + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2300, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::HasParam) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2400 + * @tc.name : WantParams.IsEmpty + * @tc.desc : empty WantParams + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2400, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::IsEmpty) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2500 + * @tc.name : WantParams.IsEmpty + * @tc.desc : WantParams with params + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2500, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::IsEmpty) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2600 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall string param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2600, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2700 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall bool param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2700, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2800 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall byte param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2800, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_2900 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall char param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_2900, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_2900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3000 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall short param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3000, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3100 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall int param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3100, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3200 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall long param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3200, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3300 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall float param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3300, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3400 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall double param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3400, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3500 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall string array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3500, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_9"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3600 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall bool array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3600, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_10"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3700 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall byte array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3700, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_11"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3800 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall char array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3800, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_12"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_3900 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall short array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_3900, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_13"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_3900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4000 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall int array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4000, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_14"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4100 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall long array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4100, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_15"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4200 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall float array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4200, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_16"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4300 + * @tc.name : WantParams.Marshalling + * @tc.desc : marshall and unmarshall double array param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4300, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Marshalling) + "_17"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4400 + * @tc.name : WantParams.Size + * @tc.desc : no any param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4400, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Size) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4500 + * @tc.name : WantParams.Size + * @tc.desc : only one param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4500, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Size) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4600 + * @tc.name : WantParams.Size + * @tc.desc : multiple params + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4600, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Size) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4700 + * @tc.name : WantParams.KeySet + * @tc.desc : no any key + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4700, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::KeySet) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4800 + * @tc.name : WantParams.KeySet + * @tc.desc : multiple keys + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4800, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::KeySet) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_4900 + * @tc.name : WantParams.WantParamsCopy + * @tc.desc : copy empty WantParams + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_4900, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::WantParamsCopy) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_4900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_5000 + * @tc.name : WantParams.WantParamsCopy + * @tc.desc : copy WantParams with multiple param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_5000, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::WantParamsCopy) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_5000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_5100 + * @tc.name : WantParams.Remove + * @tc.desc : remove not existed param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_5100, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Remove) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_5100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_WantParams_5200 + * @tc.name : WantParams.Remove + * @tc.desc : remove existed param + */ +HWTEST_F(ActsAmsKitProcessInfoTest, AMS_Page_WantParams_5200, Function | MediumTest | Level1) +{ + StartFifthAbility(); + std::string data = "WantParams_" + std::to_string((int)WantParamsApi::Remove) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIFTH, ++amsKitSystemTestFifthAbilityCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_FIFTH, amsKitSystemTestFifthAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "AMS_Page_WantParams_5200 : " << i; + break; + } + } +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_service_ability_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_service_ability_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13eb9464a0dbba07d463c68e02e8a9e886cd15b8 --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_service_ability_test.cpp @@ -0,0 +1,10229 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_lifecycle_executor.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "event.h" +#include "hilog_wrapper.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using namespace OHOS::STtools; +using namespace testing::ext; + +using MAP_STR_STR = std::map; + +const std::string BUNDLE_NAME = "com.ohos.amsst.service.AppKit"; +const std::string HAP_NAME = "amsKitSystemTestService"; +const std::string FIRST_ABILTIY_NAME = "MainAbilityDemo"; +const std::string SECOND_ABILTIY_NAME = "SecondAbility"; + +const std::string ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS = "LifecycleCallbacksAbility"; +const std::string ABILTIY_NAME_ABILITY_CONTEXT = "AbilityContextAbility"; +const std::string ABILTIY_NAME_ABILITY = "AbilityAbility"; +const std::string ABILTIY_NAME_ABILITY_CONNECTION = "AbilityConnectionAbility"; +const std::string ABILTIY_NAME_ABILITY_LIFE_CYCLE = "AbilityLifeCycleAbility"; +const std::string ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER = "LifeCycleObserverAbility"; + +constexpr int WAIT_TIME = 1000; +constexpr int DELAY_TIME = 3; +constexpr int WAIT_ABILITY_OK = 3 * 1000; + +const std::string EVENT_RESP_LIFECYCLE_CALLBACK = "resp_com_ohos_amsst_appkit_service_ability_lifecycle_callbacks"; +const std::string EVENT_RESP_LIFECYCLE_OBSERVER = "resp_com_ohos_amsst_appkit_service_lifecycle_observer"; +const std::string EVENT_RESP_FIRST_ABILITY = "resp_com_ohos_amsst_appkit_service_mainabilitydemo"; +const std::string EVENT_RESP_SECOND_ABILITY = "resp_com_ohos_amsst_appkit_service_secondability"; +const std::string EVENT_RESP_KITTEST_COMPLETE = "resp_com_ohos_amsst_appkit_service_kittest_completed"; +const std::string EVENT_REQU_KITTEST = "requ_com_ohos_amsst_appkit_service_kittest"; +const std::string EVENT_RESP_SECOND_ABILITY_CONTEXT = + "resp_com_ohos_amsst_appkit_service_secondability_ability_context"; +const std::string EVENT_REQU_KITTEST_SECOND = "resp_com_ohos_amsst_appkit_service_secondability_kittest"; + +const std::string APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_life_cycle_call_backs"; +const std::string APP_LIFE_CYCLE_CALL_BACKS_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_life_cycle_call_backs"; + +const std::string APP_ABILITY_CONTEXT_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_context"; +const std::string APP_ABILITY_CONTEXT_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_context"; + +const std::string APP_ABILITY_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability"; +const std::string APP_ABILITY_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability"; + +const std::string APP_ABILITY_CONNECTION_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_connection"; +const std::string APP_ABILITY_CONNECTION_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_connection"; + +const std::string APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_ability_life_cycle"; +const std::string APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_ability_life_cycle"; + +const std::string APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME = "resp_com_ohos_amsst_service_app_life_cycle_observer"; +const std::string APP_LIFE_CYCLE_OBSERVER_REQ_EVENT_NAME = "req_com_ohos_amsst_service_app_life_cycle_observer"; + +std::vector bundleNameList = { + "com.ohos.amsst.service.AppKit", + "com.ohos.amsst.service.appA", +}; +std::vector hapNameList = { + "amsKitSystemTestService", + "amsSystemTestServiceA", +}; + +class ActsAmsKitServiceAbilityTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static bool SubscribeEvent(); + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const CommonEventData &data) override; + void ReceiveEvent(); + }; + + static sptr appMs; + static sptr abilityMs; + static Event event; + static std::vector eventList; + static std::map mapState; + static std::shared_ptr subscriber; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityConnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; + }; + + static StressTestLevel stLevel_; +}; +size_t ActsAmsKitServiceAbilityTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +StressTestLevel ActsAmsKitServiceAbilityTest::stLevel_ = {}; + +std::vector ActsAmsKitServiceAbilityTest::eventList = { + EVENT_RESP_LIFECYCLE_CALLBACK, + EVENT_RESP_LIFECYCLE_OBSERVER, + EVENT_RESP_FIRST_ABILITY, + EVENT_RESP_KITTEST_COMPLETE, + EVENT_RESP_SECOND_ABILITY_CONTEXT, + APP_LIFE_CYCLE_CALL_BACKS_RESP_EVENT_NAME, + APP_ABILITY_CONTEXT_RESP_EVENT_NAME, + APP_ABILITY_RESP_EVENT_NAME, + APP_ABILITY_CONNECTION_RESP_EVENT_NAME, + APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, +}; + +Event ActsAmsKitServiceAbilityTest::event = Event(); +sptr ActsAmsKitServiceAbilityTest::appMs = nullptr; +sptr ActsAmsKitServiceAbilityTest::abilityMs = nullptr; +std::map ActsAmsKitServiceAbilityTest::mapState = { + {"OnStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnCommand", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnConnect", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnDisconnect", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnAbilityActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnAbilityInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnAbilityForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStateChanged", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"LifeCycle", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnNewWant", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, +}; + +std::shared_ptr ActsAmsKitServiceAbilityTest::subscriber = nullptr; + +void ActsAmsKitServiceAbilityTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto iter = std::find(eventList.begin(), eventList.end(), eventName); + if (iter != eventList.end()) { + STAbilityUtil::Completed(event, data.GetData(), data.GetCode()); + } +} + +void ActsAmsKitServiceAbilityTest::SetUpTestCase(void) +{ + STAbilityUtil::InstallHaps(hapNameList); + TestConfigParser tcp; + stLevel_.AMSLevel = 1; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void ActsAmsKitServiceAbilityTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber); + STAbilityUtil::UninstallBundle(bundleNameList); +} + +void ActsAmsKitServiceAbilityTest::SetUp(void) +{ + AbilityConnectCallback::onAbilityConnectDoneCount = 0; + abilityMs = STAbilityUtil::GetAbilityManagerService(); + appMs = STAbilityUtil::GetAppMgrService(); +} + +void ActsAmsKitServiceAbilityTest::TearDown(void) +{ + STAbilityUtil::CleanMsg(event); + STAbilityUtil::KillBundleProcess(bundleNameList); +} + +bool ActsAmsKitServiceAbilityTest::SubscribeEvent() +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00100 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00100 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00200 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00200 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00300 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00300 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00400 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00400 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00500 + * @tc.name : Test the OnAbilityStart event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00500 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00600 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00600 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00700 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00700 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00800 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00800 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_00900 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_00900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_00900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_00900 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01000 + * @tc.name : Test the OnAbilityActive event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01000 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01100 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01100 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01200 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01200 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01300 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01300 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01400 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01400 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01500 + * @tc.name : Test the OnAbilityInactive event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityInactive", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01500 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01600 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01600 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01700 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01700 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01800 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01800 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01800 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_01900 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_01900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_01900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_01900 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02000 + * @tc.name : Test the OnAbilityForeground event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityForeground", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02000 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02100 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02100 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02200 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02200 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02300 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02300 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02400 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02400 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02400 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02500 + * @tc.name : Test the OnAbilityStop event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02500 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02600 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilitySaveState event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02600 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02600 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02700 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilitySaveState event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02700 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02700 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02800 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilitySaveState event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02800 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02800 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_02900 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_02900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02900 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_02900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_02900 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_03000 + * @tc.name : Test the OnAbilitySaveState event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_03000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilitySaveState", 0, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03000 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03000 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_03100 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : No processing is done in the OnAbilityBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_03100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03100 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03100 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_03200 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start a task in the OnAbilityBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_03200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03200 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03200 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_03300 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Start the while loop in the OnAbilityBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_03300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03300 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03300 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_03400 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_03400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03400 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03400 end"; +} + +/** + * @tc.number : AMS_Service_LifeCycleCallbacks_03500 + * @tc.name : Test the OnAbilityBackground event in the AbilityLifecycleCallbacks class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifeCycleCallbacks_03500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_LIFE_CYCLE_CALL_BACKS, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityStart", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnAbilityActive", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityBackground", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03500 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifeCycleCallbacks_03500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifeCycleCallbacks_03500 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_03600 + * @tc.name : Test the ConnectAbility method in the AbilityContext class + * @tc.desc : Ability to connect yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_03600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "ConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03600 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_03700 + * @tc.name : Test the ConnectAbility method in the AbilityContext class + * @tc.desc : Connect to other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_03700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "ConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03700 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_03800 + * @tc.name : Test the ConnectAbility method in the AbilityContext class + * @tc.desc : Connect to other services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_03800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "ConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03800 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03800 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_03900 + * @tc.name : Test the ConnectAbility method in the AbilityContext class + * @tc.desc : Connect yourself many times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_03900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "ConnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_03900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_03900 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04000 + * @tc.name : Test the ConnectAbility method in the AbilityContext class + * @tc.desc : The connection callback is a local variable + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04000 start"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + MAP_STR_STR params; + params["No."] = "5"; + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "ConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04000 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04100 + * @tc.name : Test the StopAbility method in the AbilityContext class + * @tc.desc : Ability to stop yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04100 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04200 + * @tc.name : Test the StopAbility method in the AbilityContext class + * @tc.desc : Stop other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04200 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04200 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04300 + * @tc.name : Test the StopAbility method in the AbilityContext class + * @tc.desc : Stop other services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04300 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04300 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04400 + * @tc.name : Test the StopAbility method in the AbilityContext class + * @tc.desc : Stop yourself many times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04400 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04400 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04500 + * @tc.name : Test the StopAbility method in the AbilityContext class + * @tc.desc : Stop non-existent service ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04500 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04600 + * @tc.name : Test the DisconnectAbility method in the AbilityContext class + * @tc.desc : Ability to disconnect yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "DisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04600 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04700 + * @tc.name : Test the DisconnectAbility method in the AbilityContext class + * @tc.desc : Disconnect to other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "DisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04700 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04800 + * @tc.name : Test the DisconnectAbility method in the AbilityContext class + * @tc.desc : Disconnect to other services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "DisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04800 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_04900 + * @tc.name : Test the DisconnectAbility method in the AbilityContext class + * @tc.desc : Multiple disconnected services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_04900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "DisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_04900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_04900 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05000 + * @tc.name : Test the DisconnectAbility method in the AbilityContext class + * @tc.desc : Disconnect the non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "DisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05000 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05100 + * @tc.name : Test the StartAbility method in the AbilityContext class + * @tc.desc : Ability to start yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05100 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05200 + * @tc.name : Test the StartAbility method in the AbilityContext class + * @tc.desc : Start other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05200 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05300 + * @tc.name : Test the StartAbility method in the AbilityContext class + * @tc.desc : Start other services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05300 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05400 + * @tc.name : Test the StartAbility method in the AbilityContext class + * @tc.desc : Start the same service multiple times in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05400 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05400 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05500 + * @tc.name : Test the StartAbility method in the AbilityContext class + * @tc.desc : Start a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "StartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05500 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05600 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Ability to terminate yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05600 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05700 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05700 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05700 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05800 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05800 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05800 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_05900 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_05900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05900 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_05900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_05900 end"; +} + +/** + * @tc.number : AMS_Service_AbilityContext_06000 + * @tc.name : Test the TerminateAbility method in the AbilityContext class + * @tc.desc : Terminate a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_AbilityContext_06000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_06000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONTEXT, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_CONTEXT_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_06000 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_AbilityContext_06000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_AbilityContext_06000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06100 + * @tc.name : Test the TerminateAbility method in the Ability class + * @tc.desc : Ability to terminate yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06100 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06200 + * @tc.name : Test the TerminateAbility method in the Ability class + * @tc.desc : Terminate other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06200 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06300 + * @tc.name : Test the TerminateAbility method in the Ability class + * @tc.desc : Terminate services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06300 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06400 + * @tc.name : Test the TerminateAbility method in the Ability class + * @tc.desc : Terminate the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06400 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06500 + * @tc.name : Test the TerminateAbility method in the Ability class + * @tc.desc : Terminate a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "TerminateAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestTerminateAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06500 : " << i; + break; + } + + // stop ability + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06600 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : No processing is done in the OnStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06600 start"; + + MAP_STR_STR params; + params["No."] = "11"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06700 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Start a task in the OnStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06700 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06800 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Start the while loop in the OnStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06800 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_06900 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_06900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06900 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_06900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_06900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_06900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07000 + * @tc.name : Test the OnStart event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07000 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07100 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : No processing is done in the OnStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07200 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Start a task in the OnStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07300 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Start the while loop in the OnStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07400 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07500 + * @tc.name : Test the OnStop event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "StopAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestStopAbility", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07600 + * @tc.name : Test the OnNewWant event in the Ability class + * @tc.desc : No processing is done in the OnNewWant event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07600 start"; + + MAP_STR_STR params; + params["No."] = "11"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewWant", mapState["OnNewWant"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07700 + * @tc.name : Test the OnNewWant event in the Ability class + * @tc.desc : Start a task in the OnNewWant event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest ams_kit_service_ability_test_07700 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewWant", mapState["OnNewWant"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07800 + * @tc.name : Test the OnNewWant event in the Ability class + * @tc.desc : Start the while loop in the OnNewWant event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07800 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewWant", mapState["OnNewWant"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07800 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_07900 + * @tc.name : Test the OnNewWant event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_07900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07900 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewWant", mapState["OnNewWant"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_07900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_07900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_07900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08000 + * @tc.name : Test the OnNewWant event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08000 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnNewWant", mapState["OnNewWant"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08100 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : No processing is done in the OnInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08100 start"; + + MAP_STR_STR params; + params["No."] = "11"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08100 end"; +} +/** + * @tc.number : AMS_Service_Ability_08200 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Start a task in the OnInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08200 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08200 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08300 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Start the while loop in the OnInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08300 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08300 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08400 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08400 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08400 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08500 + * @tc.name : Test the OnInactive event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08500 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08600 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : No processing is done in the OnActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08600 start"; + + MAP_STR_STR params; + params["No."] = "11"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08700 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Start a task in the OnActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08700 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08800 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Start the while loop in the OnActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08800 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08800 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_08900 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_08900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08900 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_08900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_08900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_08900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09000 + * @tc.name : Test the OnActive event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09000 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09100 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : No processing is done in the OnForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09100 start"; + + MAP_STR_STR params; + params["No."] = "11"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09200 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Start a task in the OnForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09200 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09200 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09300 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Start the while loop in the OnForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09300 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09300 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09400 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09400 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09400 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09500 + * @tc.name : Test the OnForeground event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09500 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09600 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : No processing is done in the OnBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09600 start"; + + MAP_STR_STR params; + params["No."] = "11"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09600 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09700 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Start a task in the OnBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09700 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09800 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Start the while loop in the OnBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09800 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09800 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_09900 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_09900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09900 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_09900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_09900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_09900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10000 + * @tc.name : Test the OnBackground event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10000 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10100 + * @tc.name : Test the OnConnect event in the Ability class + * @tc.desc : No processing is done in the OnConnect event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10100 start"; + + MAP_STR_STR params; + params["No."] = "11"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10200 + * @tc.name : Test the OnConnect event in the Ability class + * @tc.desc : Start a task in the OnConnect event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10200 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10300 + * @tc.name : Test the OnConnect event in the Ability class + * @tc.desc : Start the while loop in the OnConnect event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10300 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10400 + * @tc.name : Test the OnConnect event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10400 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10500 + * @tc.name : Test the OnConnect event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10500 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10600 + * @tc.name : Test the OnCommand event in the Ability class + * @tc.desc : No processing is done in the OnCommand event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10600 start"; + + MAP_STR_STR params; + params["No."] = "11"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10700 + * @tc.name : Test the OnCommand event in the Ability class + * @tc.desc : Start a task in the OnCommand event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10700 start"; + + MAP_STR_STR params; + params["No."] = "12"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10800 + * @tc.name : Test the OnCommand event in the Ability class + * @tc.desc : Start the while loop in the OnCommand event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10800 start"; + + MAP_STR_STR params; + params["No."] = "13"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_10900 + * @tc.name : Test the OnCommand event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_10900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10900 start"; + + MAP_STR_STR params; + params["No."] = "14"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_10900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_10900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_10900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11000 + * @tc.name : Test the OnCommand event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11000 start"; + + MAP_STR_STR params; + params["No."] = "15"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11100 + * @tc.name : Test the OnDisconnect event in the Ability class + * @tc.desc : No processing is done in the OnDisconnect event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + int ret = STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11100 end" << mapState["OnDisconnect"]; +} + +/** + * @tc.number : AMS_Service_Ability_11200 + * @tc.name : Test the OnDisconnect event in the Ability class + * @tc.desc : Start a task in the OnDisconnect event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + int ret = STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11300 + * @tc.name : Test the OnDisconnect event in the Ability class + * @tc.desc : Start the while loop in the OnDisconnect event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + int ret = STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11400 + * @tc.name : Test the OnDisconnect event in the Ability class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + int ret = STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11500 + * @tc.name : Test the OnDisconnect event in the Ability class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + int ret = STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11600 + * @tc.name : Test the StartAbility method in the Ability class + * @tc.desc : Ability to start yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11700 + * @tc.name : Test the StartAbility event in the Ability class + * @tc.desc : Start other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11800 + * @tc.name : Test the StartAbility event in the Ability class + * @tc.desc : Start services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_11900 + * @tc.name : Test the StartAbility event in the Ability class + * @tc.desc : Start the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_11900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_11900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_11900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_11900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12000 + * @tc.name : Test the StartAbility event in the Ability class + * @tc.desc : Start a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStartAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStartAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12100 + * @tc.name : Test the ConnectAbility method in the Ability class + * @tc.desc : Ability to connect yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityConnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12200 + * @tc.name : Test the ConnectAbility method in the Ability class + * @tc.desc : Connect other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityConnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12300 + * @tc.name : Test the ConnectAbility method in the Ability class + * @tc.desc : Connect services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityConnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12400 + * @tc.name : Test the ConnectAbility method in the Ability class + * @tc.desc : Connect the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityConnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12500 + * @tc.name : Test the ConnectAbility method in the Ability class + * @tc.desc : Connect a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityConnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityConnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12600 + * @tc.name : Test the StopAbility method in the Ability class + * @tc.desc : Ability to stop yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12600 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12700 + * @tc.name : Test the StopAbility method in the Ability class + * @tc.desc : Stop other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12700 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStopAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12800 + * @tc.name : Test the StopAbility method in the Ability class + * @tc.desc : Stop services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12800 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStopAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_12900 + * @tc.name : Test the StopAbility method in the Ability class + * @tc.desc : Stop the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_12900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12900 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_12900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_12900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_12900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13000 + * @tc.name : Test the StopAbility method in the Ability class + * @tc.desc : Stop a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13000 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityStopAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityStopAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13100 + * @tc.name : Test the GetLifecycle method in the Ability class + * @tc.desc : Get life cycle object. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13100 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13200 + * @tc.name : Test the GetLifecycle method in the Ability class + * @tc.desc : Get the lifecycle object multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13200 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13200 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13300 + * @tc.name : Test the GetLifecycle method in the Ability class + * @tc.desc : Call GetLifecycleState. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13300 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted( + event, "TestAbilityGetLifecycle", AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13300 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13400 + * @tc.name : Test the GetLifecycle method in the Ability class + * @tc.desc : Call AddObserver. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13400 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13400 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13500 + * @tc.name : Test the GetLifecycle method in the Ability class + * @tc.desc : Call DispatchLifecycle. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13500 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13600 + * @tc.name : Test the GetLifecycle method in the Ability class + * @tc.desc : Call RemoveObserver. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13600 start"; + + MAP_STR_STR params; + params["No."] = "6"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13700 + * @tc.name : Test the DisconnectAbility method in the AbilityConnectionStub class + * @tc.desc : Ability to disconnect yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13700 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityDisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityDisconnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13800 + * @tc.name : Test the DisconnectAbility method in the AbilityConnectionStub class + * @tc.desc : Disconnect other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13800 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityDisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityDisconnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_13900 + * @tc.name : Test the DisconnectAbility method in the AbilityConnectionStub class + * @tc.desc : Disconnect services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_13900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13900 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityDisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityDisconnectAbility", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_13900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_13900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_13900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14000 + * @tc.name : Test the DisconnectAbility method in the AbilityConnectionStub class + * @tc.desc : Disconnect the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14000 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityDisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityDisconnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14100 + * @tc.name : Test the DisconnectAbility method in the AbilityConnectionStub class + * @tc.desc : Disconnect a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14100 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_REQ_EVENT_NAME, 1, "AbilityDisconnectAbility"); + int ret = STAbilityUtil::WaitCompleted(event, "TestAbilityDisconnectAbility", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14200 + * @tc.name : Test the OnAbilityConnectDone method in the AbilityConnectionStub class + * @tc.desc : Ability to connect yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14200 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 0, "ConnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14200 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14300 + * @tc.name : Test the OnAbilityConnectDone method in the AbilityConnectionStub class + * @tc.desc : Connect other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14300 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "ConnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14400 + * @tc.name : Test the OnAbilityConnectDone method in the AbilityConnectionStub class + * @tc.desc : Connect services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14400 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "ConnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14500 + * @tc.name : Test the OnAbilityConnectDone method in the AbilityConnectionStub class + * @tc.desc : Connect the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14500 start"; + + MAP_STR_STR params; + params["No."] = "4"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "ConnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14600 + * @tc.name : Test the OnAbilityConnectDone method in the AbilityConnectionStub class + * @tc.desc : Connect a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14600 start"; + + MAP_STR_STR params; + params["No."] = "5"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "ConnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestConnectAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14700 + * @tc.name : Test the OnAbilityDisconnectDone method in the AbilityConnectionStub class + * @tc.desc : Ability to disconnect yourself. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14700 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "DisconnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 1, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14800 + * @tc.name : Test the OnAbilityDisconnectDone method in the AbilityConnectionStub class + * @tc.desc : Disconnect other services in the same application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14800 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "DisconnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 1, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14800 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_14900 + * @tc.name : Test the OnAbilityDisconnectDone method in the AbilityConnectionStub class + * @tc.desc : Disconnect services in another application. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_14900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14900 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "DisconnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 1, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 1, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_14900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_14900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_14900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15000 + * @tc.name : Test the OnAbilityDisconnectDone method in the AbilityConnectionStub class + * @tc.desc : Disconnect the same service in the same application multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15000 start"; + + MAP_STR_STR params; + params["No."] = "4"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "DisconnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 3, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15100 + * @tc.name : Test the OnAbilityDisconnectDone method in the AbilityConnectionStub class + * @tc.desc : Disconnect a non-existent service. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15100 start"; + + MAP_STR_STR params; + params["No."] = "5"; + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_CONNECTION, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send connect message + STAbilityUtil::PublishEvent(APP_ABILITY_CONNECTION_REQ_EVENT_NAME, 1, "DisconnectAbility"); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "TestDisconnectAbility", 0, DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 1, DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15200 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Get life cycle object. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15200 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15200 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15300 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Get the lifecycle object multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15300 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15300 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15400 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call GetLifecycleState. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15400 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 0, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15400 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15500 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call AddObserver. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15500 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15600 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call DispatchLifecycle. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15600 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15700 + * @tc.name : Test the GetLifecycle method in the Lifecycle class + * @tc.desc : Call RemoveObserver. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15700 start"; + + MAP_STR_STR params; + params["No."] = "6"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15800 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : GetLifecycleState Called in OnStart function. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15800 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycleState"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15800 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_15900 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : GetLifecycleState Called in OnCommand function. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_15900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15900 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycleState"); + int ret = + STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", mapState["OnCommand"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_15900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_15900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_15900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16000 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : GetLifecycleState Called in OnActive function. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16000 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycleState"); + int ret = + STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16100 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : GetLifecycleState Called in OnStart function. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16100 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycleState"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16100 : " << i; + break; + } + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16200 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : GetLifecycleState Called in OnConnect function. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16200 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycleState"); + int ret = + STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", mapState["OnConnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16200 : " << i; + break; + } + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16300 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnDisconnect function. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16300 start"; + + MAP_STR_STR params; + params["No."] = "6"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycleState"); + int ret = + STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", mapState["OnDisconnect"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16400 + * @tc.name : Test the GetLifecycleState method in the Lifecycle class + * @tc.desc : Called in OnBackground function. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16400 start"; + + MAP_STR_STR params; + params["No."] = "7"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleGetLifecycleState"); + int ret = + STAbilityUtil::WaitCompleted(event, "TestLifeCycleGetLifecycleState", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16500 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add an observer object. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16500 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16600 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add an observer object multi times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16600 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16700 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add multi observer objects. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16700 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16800 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add multi observer objects, then call RemoveObserver. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16800 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16800 : " << i; + break; + } + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_16900 + * @tc.name : Test the AddObserver method in the Lifecycle class + * @tc.desc : Add multi nullptr objects, then call RemoveObserver. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_16900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16900 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleAddObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleAddObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_16900 : " << i; + break; + } + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_16900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_16900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17000 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_ACTIVE. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17000 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17100 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_BACKGROUND. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17100 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17200 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_FOREGROUND. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17200 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17200 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17300 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_INACTIVE. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17300 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnInactive", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17400 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_START. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17400 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17400 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17500 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_STOP. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17500 start"; + + MAP_STR_STR params; + params["No."] = "6"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17500 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17600 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle UNDEFINED. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17600 start"; + + MAP_STR_STR params; + params["No."] = "7"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17600 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "UnDefine", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17700 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle ON_ACTIVE. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17700 start"; + + MAP_STR_STR params; + params["No."] = "8"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17700 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17800 + * @tc.name : Test the DispatchLifecycle method in the Lifecycle class + * @tc.desc : DispatchLifecycle UNDEFINED. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17800 start"; + + MAP_STR_STR params; + params["No."] = "9"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleDispatchLifecycle"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleDispatchLifecycle", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17800 : " << i; + break; + } + EXPECT_EQ(-1, STAbilityUtil::WaitCompleted(event, "UnDefine", 0, DELAY_TIME)); + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_17900 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove a non-existent observer. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_17900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17900 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_17900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_17900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_17900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_18000 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove the same observer multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_18000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18000 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_18000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_18000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_18100 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove different observers multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_18100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18100 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnCommand", mapState["OnCommand"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_18100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_18100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_18200 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove observer after adding Observer many times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_18200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18200 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_18200 : " << i; + break; + } + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_18200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_18300 + * @tc.name : Test the RemoveObserver method in the Lifecycle class + * @tc.desc : Remove nullptr observer multiple times. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_Ability_18300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18300 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // send message + STAbilityUtil::PublishEvent(APP_ABILITY_LIFE_CYCLE_REQ_EVENT_NAME, 1, "LifeCycleRemoveObserver"); + int ret = STAbilityUtil::WaitCompleted(event, "TestLifeCycleRemoveObserver", 1, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_Ability_18300 : " << i; + break; + } + + // stop ability + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_Ability_18300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_Ability_18300 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_18400 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_18400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18400 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18400 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_18500 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Start a task in the OnActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_18500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18500 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18500 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_18600 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnActive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_18600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18600 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18600 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_18700 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_18700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18700 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18700 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_18800 + * @tc.name : Test the OnActive event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_18800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18800 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18800 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_18900 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_18900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18900 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18900 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_18900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_18900 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19000 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Start a task in the OnBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19000 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19000 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19000 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19100 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnBackground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19100 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19100 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19100 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19200 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19200 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19200 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19200 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19300 + * @tc.name : Test the OnBackground event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19300 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + int ret = STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19300 : " << i; + break; + } + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19300 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19400 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19400 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19400 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19400 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19500 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Start a task in the OnForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19500 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19500 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19500 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19600 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnForeground event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19600 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19600 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19600 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19700 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19700 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19700 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19700 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19800 + * @tc.name : Test the OnForeground event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19800 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + int ret = STAbilityUtil::WaitCompleted(event, "OnForeground", mapState["OnForeground"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19800 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19800 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_19900 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_19900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19900 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19900 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_19900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_19900 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20000 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Start a task in the OnInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20000 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20000 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20000 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20100 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnInactive event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20100 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20100 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20100 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20200 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20200 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20200 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20200 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20300 + * @tc.name : Test the OnInactive event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20300 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnInactive", mapState["OnInactive"], DELAY_TIME); + EXPECT_EQ(-1, ret); + if (ret != -1) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20300 : " << i; + break; + } + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20300 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20400 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20400 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20400 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20500 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Start a task in the OnStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20500 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20500 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20600 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnStart event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20600 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20600 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20700 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20700 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20700 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20700 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20800 + * @tc.name : Test the OnStart event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20800 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20800 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_20900 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_20900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20900 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20900 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_20900 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_20900 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21000 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Start a task in the OnStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21000 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21000 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21000 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21000 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21100 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnStop event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21100 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", 0, DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21100 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21100 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21100 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21200 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21200 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21200 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21200 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21200 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21300 + * @tc.name : Test the OnStop event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21300 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStop", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21300 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21300 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21300 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21400 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : No processing is done in the OnStateChanged event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21400 start"; + + MAP_STR_STR params; + params["No."] = "1"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21400 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21400 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21400 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21500 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Start a task in the OnStateChanged event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21500 start"; + + MAP_STR_STR params; + params["No."] = "2"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21500 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21500 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21500 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21600 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Start the while loop in the OnStateChanged event. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21600 start"; + + MAP_STR_STR params; + params["No."] = "3"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21600 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21600 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21600 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21700 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Stop ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21700 start"; + + MAP_STR_STR params; + params["No."] = "4"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21700 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21700 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21700 end"; +} + +/** + * @tc.number : AMS_Service_LifecycleObserver_21800 + * @tc.name : Test the OnStateChanged event in the LifecycleObserver class + * @tc.desc : Terminate ability immediately after starting ability. + */ +HWTEST_F(ActsAmsKitServiceAbilityTest, AMS_Service_LifecycleObserver_21800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21800 start"; + + MAP_STR_STR params; + params["No."] = "5"; + + bool result = true; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + Want want = STAbilityUtil::MakeWant("device", ABILTIY_NAME_ABILITY_LIFE_CYCLE_OBSERVER, BUNDLE_NAME, params); + // start ability + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStart", mapState["OnStart"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnActive", mapState["OnActive"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnConnect", mapState["OnConnect"], DELAY_TIME)); + int ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21800 : " << i; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + STAbilityUtil::DisconnectAbility(connCallback); + + ret = STAbilityUtil::WaitCompleted(event, "OnStateChanged", 0, DELAY_TIME); + EXPECT_EQ(0, ret); + if (ret != 0) { + result = false; + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21700 : " << i; + break; + } + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnDisconnect", mapState["OnDisconnect"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + + // stop ability + STAbilityUtil::StopServiceAbility(want); + + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnStop", mapState["OnStop"], DELAY_TIME)); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, "OnBackground", mapState["OnBackground"], DELAY_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_ABILITY_OK)); + } + if (result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Service_LifecycleObserver_21800 : " << stLevel_.AMSLevel; + } + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "ActsAmsKitServiceAbilityTest AMS_Service_LifecycleObserver_21800 end"; +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_skills_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_skills_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c48f73e905f967ecde1caa6620ca51ebf53736b8 --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_skills_test.cpp @@ -0,0 +1,6885 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "event.h" +#include "ability_lifecycle_executor.h" +#include "ability_lifecycle.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "kit_test_common_info.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; +using MAP_STR_STR = std::map; +static const std::string bundleName = "com.ohos.amsst.AppKit"; +static const std::string fourthAbilityName = "FourthAbility"; +std::vector bundleNameList = { + "com.ohos.amsst.AppKit", +}; +std::vector hapNameList = { + "amsKitSystemTest", +}; + +int amsKitSTCode = 0; +} // namespace + +class ActsAmsKitSkillsTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void CleanMsg(); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber() = default; + }; + + static sptr appMs; + static sptr abilityMs; + static Event event; + static Event abilityEvent; + static StressTestLevel stLevel_; + static std::shared_ptr subscriber_; +}; + +StressTestLevel ActsAmsKitSkillsTest::stLevel_ {}; +std::shared_ptr ActsAmsKitSkillsTest::subscriber_ = nullptr; +Event ActsAmsKitSkillsTest::event = Event(); +Event ActsAmsKitSkillsTest::abilityEvent = Event(); +sptr ActsAmsKitSkillsTest::appMs = nullptr; +sptr ActsAmsKitSkillsTest::abilityMs = nullptr; + +void ActsAmsKitSkillsTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + STAbilityUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); + STAbilityUtil::Completed(abilityEvent, data.GetData(), data.GetCode()); +} + +void ActsAmsKitSkillsTest::SetUpTestCase(void) +{ + STAbilityUtil::InstallHaps(hapNameList); + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; +} + +void ActsAmsKitSkillsTest::TearDownTestCase(void) +{ + STAbilityUtil::UninstallBundle(bundleNameList); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ActsAmsKitSkillsTest::SetUp(void) +{} + +void ActsAmsKitSkillsTest::TearDown(void) +{ + CleanMsg(); +} + +bool ActsAmsKitSkillsTest::SubscribeEvent() +{ + const std::vector eventList = { + g_respPageFourthAbilityST, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ActsAmsKitSkillsTest::StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName) +{ + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, abilityName + g_abilityStateOnActive, 0), 0); +} + +void ActsAmsKitSkillsTest::CleanMsg() +{ + STAbilityUtil::CleanMsg(event); + STAbilityUtil::CleanMsg(abilityEvent); +} + +/** + * @tc.number : AMS_Page_Skills_00100 + * @tc.name : Skills::CountActions + * @tc.desc : judge the return value of countactions after calling addaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountActions)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00200 + * @tc.name : Skills::CountActions + * @tc.desc : judge the return value of countaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountActions)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00300 + * @tc.name : Skills::CountActions + * @tc.desc : after calling addaction many times, judge the return value of countaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountActions)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00400 + * @tc.name : Skills::GetAction + * @tc.desc : add a normal string to judge the return value of getaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAction)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00500 + * @tc.name : Skills::GetAction + * @tc.desc : judge the return value of getaction, when the index value exceeds + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAction)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00600 + * @tc.name : Skills::GetAction + * @tc.desc : judge the return value of getaction when the index value is negative + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAction)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00700 + * @tc.name : Skills::GetAction + * @tc.desc : judge the return value of getaction when action is null + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAction)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00800 + * @tc.name : Skills::GetAction + * @tc.desc : add a special string to judge the return value of getaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAction)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_00900 + * @tc.name : Skills::GetAction + * @tc.desc : after calling addaction many times, judge the return value of getaction(index 0) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_00900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAction)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_00900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01000 + * @tc.name : Skills::GetAction + * @tc.desc : after calling addaction many times, judge the return value of getaction(index 150) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAction)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01100 + * @tc.name : Skills::HasAction + * @tc.desc : after calling addaction many times, judge the return value of hasaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasAction)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01200 + * @tc.name : Skills::HasAction + * @tc.desc : judge the return value of hasaction,when action is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasAction)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01300 + * @tc.name : Skills::HasAction + * @tc.desc : add a special string to judge the return value of hasaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasAction)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01400 + * @tc.name : Skills::RemoveAction + * @tc.desc : add specialstring. after deleting, judge hasaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01500 + * @tc.name : Skills::RemoveAction + * @tc.desc : add specialstring, after deleting, judge getaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01600 + * @tc.name : Skills::RemoveAction + * @tc.desc : loop add normalstring, after deleting, judge hasaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01700 + * @tc.name : Skills::RemoveAction + * @tc.desc : loop add normalstring, delete specialstring and judge hasaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01800 + * @tc.name : Skills::RemoveAction + * @tc.desc : loop add normalstring, after deleting, judge getaction (the index value exceeds) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_01900 + * @tc.name : Skills::RemoveAction + * @tc.desc : loop add normalstring, delete specialstring and judge getaction + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_01900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_01900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02000 + * @tc.name : Skills::RemoveAction + * @tc.desc : add specialstring, delete specialstring, and judge countactions + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02100 + * @tc.name : Skills::RemoveAction + * @tc.desc : loop add normalstring, delete normalstring, and judge countactions + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02200 + * @tc.name : Skills::RemoveAction + * @tc.desc : loop add normalstring, delete specialstring, and judge countactions + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAction)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02300 + * @tc.name : Skills::CountEntities + * @tc.desc : judge the return value of countentities after calling addentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountEntities)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02400 + * @tc.name : Skills::CountEntities + * @tc.desc : judge the return value of countentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountEntities)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02500 + * @tc.name : Skills::CountEntities + * @tc.desc : after calling addentity many times, judge the return value of countentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountEntities)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02600 + * @tc.name : Skills::GetEntity + * @tc.desc : add a normal string to judge the return value of getentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntity)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02700 + * @tc.name : Skills::GetEntity + * @tc.desc : judge the return value of getentity, when the index value exceeds + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntity)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02800 + * @tc.name : Skills::GetEntity + * @tc.desc : judge the return value of getentity when the index value is negative + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntity)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_02900 + * @tc.name : Skills::GetEntity + * @tc.desc : judge the return value of getentity when entity is null + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_02900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntity)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_02900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03000 + * @tc.name : Skills::GetEntity + * @tc.desc : add a special string to judge the return value of getentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntity)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03100 + * @tc.name : Skills::GetEntity + * @tc.desc : loop addentity, judge the return value of getentity(index 0) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntity)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03200 + * @tc.name : Skills::GetEntity + * @tc.desc : loop addentity, judge the return value of getentity(index 150) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntity)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03300 + * @tc.name : Skills::HasEntity + * @tc.desc : loop addentity, judge the return value of hasentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasEntity)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03400 + * @tc.name : Skills::HasEntity + * @tc.desc : judge the return value of hasentity,when entity is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasEntity)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03500 + * @tc.name : Skills::HasEntity + * @tc.desc : add a special string to judge the return value of hasentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasEntity)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03600 + * @tc.name : Skills::RemoveEntity + * @tc.desc : add specialstring. after deleting, judge hasentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03700 + * @tc.name : Skills::RemoveEntity + * @tc.desc : add specialstring, after deleting, judge getentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03800 + * @tc.name : Skills::RemoveEntity + * @tc.desc : loop add normalstring, after deleting, judge hasentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_03900 + * @tc.name : Skills::RemoveEntity + * @tc.desc : loop add normalstring, delete specialstring and judge hasentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_03900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_03900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04000 + * @tc.name : Skills::RemoveEntity + * @tc.desc : loop add normalstring, after deleting, judge getentity (the index value exceeds) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04100 + * @tc.name : Skills::RemoveEntity + * @tc.desc : loop add normalstring, delete specialstring and judge getentity + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04200 + * @tc.name : Skills::RemoveEntity + * @tc.desc : add specialstring, delete specialstring, and judge countentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04300 + * @tc.name : Skills::RemoveEntity + * @tc.desc : loop add normalstring, delete normalstring, and judge countentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04400 + * @tc.name : Skills::RemoveEntity + * @tc.desc : loop add normalstring, delete specialstring, and judge countentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveEntity)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04500 + * @tc.name : Skills::CountAuthorities + * @tc.desc : judge the return value of countauthorities after calling addauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountAuthorities)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04600 + * @tc.name : Skills::CountAuthorities + * @tc.desc : judge the return value of countauthorities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountAuthorities)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04700 + * @tc.name : Skills::CountAuthorities + * @tc.desc : after calling addauthority many times, judge the return value of countauthorities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountAuthorities)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04800 + * @tc.name : Skills::GetAuthority + * @tc.desc : add a normal string to judge the return value of getauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAuthority)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_04900 + * @tc.name : Skills::GetAuthority + * @tc.desc : judge the return value of getauthority, when the index value exceeds + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_04900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAuthority)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_04900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05000 + * @tc.name : Skills::GetAuthority + * @tc.desc : judge the return value of getauthority when the index value is negative + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAuthority)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05100 + * @tc.name : Skills::GetAuthority + * @tc.desc : judge the return value of getauthority when authority is null + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAuthority)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05200 + * @tc.name : Skills::GetAuthority + * @tc.desc : add a special string to judge the return value of getauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAuthority)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05300 + * @tc.name : Skills::GetAuthority + * @tc.desc : loop addauthority, judge the return value of getauthority(index 0) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAuthority)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05400 + * @tc.name : Skills::GetAuthority + * @tc.desc : loop addauthority, judge the return value of getauthority(index 150) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetAuthority)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05500 + * @tc.name : Skills::HasAuthority + * @tc.desc : loop addauthority, judge the return value of hasauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasAuthority)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05600 + * @tc.name : Skills::HasAuthority + * @tc.desc : judge the return value of hasauthority,when authority is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasAuthority)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05700 + * @tc.name : Skills::HasAuthority + * @tc.desc : add a special string to judge the return value of hasauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasAuthority)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05800 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : add specialstring. after deleting, judge hasauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_05900 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : add specialstring, after deleting, judge getauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_05900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_05900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06000 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : loop add normalstring, after deleting, judge hasauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06100 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : loop add normalstring, delete specialstring and judge hasauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06200 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : loop add normalstring, after deleting, judge getauthority (the index value exceeds) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06300 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : loop add normalstring, delete specialstring and judge getauthority + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06400 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : add specialstring, delete specialstring, and judge countauthorities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06500 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : loop add normalstring, delete normalstring, and judge countauthorities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06600 + * @tc.name : Skills::RemoveAuthority + * @tc.desc : loop add normalstring, delete specialstring, and judge countauthorities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveAuthority)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06700 + * @tc.name : Skills::CountSchemes + * @tc.desc : judge the return value of countschemes after calling addscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountSchemes)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06800 + * @tc.name : Skills::CountSchemes + * @tc.desc : judge the return value of countschemes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountSchemes)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_06900 + * @tc.name : Skills::CountSchemes + * @tc.desc : after calling addscheme many times, judge the return value of countschemes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_06900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountSchemes)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_06900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07000 + * @tc.name : Skills::GetScheme + * @tc.desc : add a normal string to judge the return value of getscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetScheme)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07100 + * @tc.name : Skills::GetScheme + * @tc.desc : judge the return value of getscheme, when the index value exceeds + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetScheme)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07200 + * @tc.name : Skills::GetScheme + * @tc.desc : judge the return value of getscheme when the index value is negative + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetScheme)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07300 + * @tc.name : Skills::GetScheme + * @tc.desc : judge the return value of getscheme when scheme is null + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetScheme)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07400 + * @tc.name : Skills::GetScheme + * @tc.desc : add a special string to judge the return value of getscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetScheme)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07500 + * @tc.name : Skills::GetScheme + * @tc.desc : loop addscheme, judge the return value of getscheme(index 0) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetScheme)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07600 + * @tc.name : Skills::GetScheme + * @tc.desc : loop addscheme, judge the return value of getscheme(index 150) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetScheme)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07700 + * @tc.name : Skills::HasScheme + * @tc.desc : loop addscheme, judge the return value of hasscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasScheme)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07800 + * @tc.name : Skills::HasScheme + * @tc.desc : judge the return value of hasscheme,when scheme is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasScheme)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_07900 + * @tc.name : Skills::HasScheme + * @tc.desc : add a special string to judge the return value of hasscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_07900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasScheme)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_07900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08000 + * @tc.name : Skills::RemoveScheme + * @tc.desc : add specialstring. after deleting, judge hasscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08100 + * @tc.name : Skills::RemoveScheme + * @tc.desc : add specialstring, after deleting, judge getscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08200 + * @tc.name : Skills::RemoveScheme + * @tc.desc : loop add normalstring, after deleting, judge hasscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08300 + * @tc.name : Skills::RemoveScheme + * @tc.desc : loop add normalstring, delete specialstring and judge hasscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08400 + * @tc.name : Skills::RemoveScheme + * @tc.desc : loop add normalstring, after deleting, judge getscheme (the index value exceeds) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08500 + * @tc.name : Skills::RemoveScheme + * @tc.desc : loop add normalstring, delete specialstring and judge getscheme + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08600 + * @tc.name : Skills::RemoveScheme + * @tc.desc : add specialstring, delete specialstring, and judge countschemes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08700 + * @tc.name : Skills::RemoveScheme + * @tc.desc : loop add normalstring, delete normalstring, and judge countschemes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08800 + * @tc.name : Skills::RemoveScheme + * @tc.desc : loop add normalstring, delete specialstring, and judge countschemes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveScheme)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_08900 + * @tc.name : Skills::CountSchemeSpecificParts + * @tc.desc : judge the return value of countschemespecificparts after calling addschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_08900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountSchemeSpecificParts)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_08900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09000 + * @tc.name : Skills::CountSchemeSpecificParts + * @tc.desc : judge the return value of countschemespecificparts + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountSchemeSpecificParts)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09100 + * @tc.name : Skills::CountSchemeSpecificParts + * @tc.desc : after calling addschemespecificpart many times, + * judge the return value of countschemespecificparts + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountSchemeSpecificParts)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09200 + * @tc.name : Skills::GetSchemeSpecificPart + * @tc.desc : add a normal string to judge the return value of getschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetSchemeSpecificPart)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09300 + * @tc.name : Skills::GetSchemeSpecificPart + * @tc.desc : judge the return value of getschemespecificpart, when the index value exceeds + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetSchemeSpecificPart)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09400 + * @tc.name : Skills::GetSchemeSpecificPart + * @tc.desc : judge the return value of getschemespecificpart when the index value is negative + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetSchemeSpecificPart)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09500 + * @tc.name : Skills::GetSchemeSpecificPart + * @tc.desc : judge the return value of getschemespecificpart when specificpart is null + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetSchemeSpecificPart)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09600 + * @tc.name : Skills::GetSchemeSpecificPart + * @tc.desc : add a special string to judge the return value of getschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetSchemeSpecificPart)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09700 + * @tc.name : Skills::GetSchemeSpecificPart + * @tc.desc : loop addschemespecificpart, judge the return value of getschemespecificpart(index 0) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetSchemeSpecificPart)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09800 + * @tc.name : Skills::GetSchemeSpecificPart + * @tc.desc : loop addschemespecificpart, judge the return value of getschemespecificpart(index 150) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetSchemeSpecificPart)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_09900 + * @tc.name : Skills::HasSchemeSpecificPart + * @tc.desc : loop addschemespecificpart, judge the return value of hasschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_09900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasSchemeSpecificPart)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_09900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10000 + * @tc.name : Skills::HasSchemeSpecificPart + * @tc.desc : judge the return value of hasschemespecificpart,when specificpart is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasSchemeSpecificPart)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10100 + * @tc.name : Skills::HasSchemeSpecificPart + * @tc.desc : add a special string to judge the return value of hasschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasSchemeSpecificPart)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10200 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : add specialstring. after deleting, judge hasschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10300 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : add specialstring, after deleting, judge getschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10400 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : loop add normalstring, after deleting, judge hasschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10500 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : loop add normalstring, delete specialstring and judge hasschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10600 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : loop add normalstring, after deleting, judge getschemespecificpart (the index value exceeds) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10700 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : loop add normalstring, delete specialstring and judge getschemespecificpart + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10800 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : add specialstring, delete specialstring, and judge countschemespecificparts + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_10900 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : loop add normalstring, delete normalstring, and judge countschemespecificparts + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_10900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_10900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11000 + * @tc.name : Skills::RemoveSchemeSpecificPart + * @tc.desc : loop add normalstring, delete specialstring, and judge countschemespecificparts + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveSchemeSpecificPart)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11100 + * @tc.name : Skills::AddPath_String_CountPaths + * @tc.desc : using addpath_string method to add path and judge the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_CountPaths)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11200 + * @tc.name : Skills::AddPath_String_CountPaths + * @tc.desc : loop uses addpath_string method to add path and judge the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_CountPaths)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11300 + * @tc.name : Skills::AddPath_String_MatchType_CountPaths + * @tc.desc : using addpath_string_matchtype method to add path and judge the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_CountPaths)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11400 + * @tc.name : Skills::AddPath_String_MatchType_CountPaths + * @tc.desc : loop uses addpath_string_matchtype method to add path and judge the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_CountPaths)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11500 + * @tc.name : Skills::AddPath_PatternMatcher_CountPaths + * @tc.desc : using addpath_patternmatcher method to add path and judge the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_CountPaths)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11600 + * @tc.name : Skills::AddPath_PatternMatcher_CountPaths + * @tc.desc : loop uses addpath_patternmatcher method to add path and judge the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_CountPaths)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11700 + * @tc.name : Skills::CountPaths + * @tc.desc : judge the return value of countpaths when path is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountPaths)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11800 + * @tc.name : Skills::AddPath_String_GetPath + * @tc.desc : add a normal string to judge the return value of getpath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_GetPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_11900 + * @tc.name : Skills::AddPath_String_GetPath + * @tc.desc : judge the return value of getpath, when the index value exceeds(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_11900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_GetPath)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_11900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12000 + * @tc.name : Skills::AddPath_String_GetPath + * @tc.desc : judge the return value of getpath when the index value is negative(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_GetPath)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12100 + * @tc.name : Skills::AddPath_String_GetPath + * @tc.desc : judge the return value of getpath when scheme is null(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_GetPath)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12200 + * @tc.name : Skills::AddPath_String_GetPath + * @tc.desc : add a special string to judge the return value of getpath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_GetPath)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12300 + * @tc.name : Skills::AddPath_String_GetPath + * @tc.desc : loop addscheme, judge the return value of getpath(index 0)(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_GetPath)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12400 + * @tc.name : Skills::AddPath_String_MatchType_GetPath + * @tc.desc : add a normal string to judge the return value of getpath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_GetPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12500 + * @tc.name : Skills::AddPath_String_MatchType_GetPath + * @tc.desc : judge the return value of getpath, when the index value exceeds(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_GetPath)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12600 + * @tc.name : Skills::AddPath_String_MatchType_GetPath + * @tc.desc : judge the return value of getpath when the index value is negative(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_GetPath)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12700 + * @tc.name : Skills::AddPath_String_MatchType_GetPath + * @tc.desc : judge the return value of getpath when scheme is null(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_GetPath)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12800 + * @tc.name : Skills::AddPath_String_MatchType_GetPath + * @tc.desc : add a special string to judge the return value of getpath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_GetPath)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_12900 + * @tc.name : Skills::AddPath_String_MatchType_GetPath + * @tc.desc : loop addscheme, judge the return value of getpath(index 0)(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_12900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_GetPath)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_12900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13000 + * @tc.name : Skills::AddPath_PatternMatcher_GetPath + * @tc.desc : add a normal string to judge the return value of getpath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_GetPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13100 + * @tc.name : Skills::AddPath_PatternMatcher_GetPath + * @tc.desc : judge the return value of getpath, when the index value exceeds(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_GetPath)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13200 + * @tc.name : Skills::AddPath_PatternMatcher_GetPath + * @tc.desc : judge the return value of getpath when the index value is negative(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_GetPath)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13300 + * @tc.name : Skills::AddPath_PatternMatcher_GetPath + * @tc.desc : judge the return value of getpath when scheme is null(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_GetPath)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13400 + * @tc.name : Skills::AddPath_PatternMatcher_GetPath + * @tc.desc : add a special string to judge the return value of getpath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_GetPath)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13500 + * @tc.name : Skills::AddPath_PatternMatcher_GetPath + * @tc.desc : loop addscheme, judge the return value of getpath(index 0)(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_GetPath)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13600 + * @tc.name : Skills::GetPath + * @tc.desc : judge the return value of getpath when path is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13700 + * @tc.name : Skills::AddPath_String_HasPath + * @tc.desc : loop addauthority, judge the return value of haspath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_HasPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13800 + * @tc.name : Skills::AddPath_String_HasPath + * @tc.desc : add a special string to judge the return value of haspath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_HasPath)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_13900 + * @tc.name : Skills::AddPath_String_MatchType_HasPath + * @tc.desc : loop addauthority, judge the return value of haspath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_13900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_HasPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_13900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14000 + * @tc.name : Skills::AddPath_String_MatchType_HasPath + * @tc.desc : add a special string to judge the return value of haspath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_String_MatchType_HasPath)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14100 + * @tc.name : Skills::AddPath_PatternMatcher_HasPath + * @tc.desc : loop addauthority, judge the return value of haspath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_HasPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14200 + * @tc.name : Skills::AddPath_PatternMatcher_HasPath + * @tc.desc : add a special string to judge the return value of haspath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddPath_PatternMatcher_HasPath)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14300 + * @tc.name : Skills::HasPath + * @tc.desc : judge the return value of haspath,when authority is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasPath)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14400 + * @tc.name : Skills::RemovePath_String + * @tc.desc : add specialstring. after deleting, judge haspath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14500 + * @tc.name : Skills::RemovePath_String + * @tc.desc : add specialstring, after deleting, judge getpath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14600 + * @tc.name : Skills::RemovePath_String + * @tc.desc : loop add normalstring, after deleting, judge haspath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14700 + * @tc.name : Skills::RemovePath_String + * @tc.desc : loop add normalstring, delete specialstring and judge haspath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14800 + * @tc.name : Skills::RemovePath_String + * @tc.desc : loop add normalstring, after deleting, judge getpath (the index value exceeds)(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_14900 + * @tc.name : Skills::RemovePath_String + * @tc.desc : loop add normalstring, delete specialstring and judge getpath(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_14900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_14900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15000 + * @tc.name : Skills::RemovePath_String + * @tc.desc : add specialstring, delete specialstring, and judge countpaths(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15100 + * @tc.name : Skills::RemovePath_String + * @tc.desc : loop add normalstring, delete normalstring, and judge countpaths(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15200 + * @tc.name : Skills::RemovePath_String + * @tc.desc : loop add normalstring, delete specialstring, and judge countpaths(addpath_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15300 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : add specialstring. after deleting, judge haspath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15400 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : add specialstring, after deleting, judge getpath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15500 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : loop add normalstring, after deleting, judge haspath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15600 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : loop add normalstring, delete specialstring and judge haspath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15700 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : loop add normalstring, after deleting, judge getpath + * (the index value exceeds)(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15800 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : loop add normalstring, delete specialstring and judge getpath(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_15900 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : add specialstring, delete specialstring, and judge countpaths(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_15900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_15900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16000 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : loop add normalstring, delete normalstring, and judge countpaths(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16100 + * @tc.name : Skills::RemovePath_String_MatchType + * @tc.desc : loop add normalstring, delete specialstring, and judge countpaths(addpath_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_String_MatchType)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16200 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : add specialstring. after deleting, judge haspath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16300 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : add specialstring, after deleting, judge getpath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16400 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : loop add normalstring, after deleting, judge haspath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16500 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : loop add normalstring, delete specialstring and judge haspath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16600 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : loop add normalstring, after deleting, + * judge getpath (the index value exceeds)(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16700 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : loop add normalstring, delete specialstring and judge getpath(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16800 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : add specialstring, delete specialstring, and judge countpaths(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_16900 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : loop add normalstring, delete normalstring, and judge countpaths(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_16900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_16900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17000 + * @tc.name : Skills::RemovePath_PatternMatcher + * @tc.desc : loop add normalstring, delete specialstring, and judge countpaths(addpath_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_PatternMatcher)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17100 + * @tc.name : Skills::RemovePath_Other + * @tc.desc : using addpath_string and addpath_ string_ matchtype two methods to add path, + * after deleting, judge the return value of haspath + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_Other)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17200 + * @tc.name : Skills::RemovePath_Other + * @tc.desc : loop uses addpath_string_ the matchtype method adds a path, and after deleting, + * judges the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_Other)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17300 + * @tc.name : Skills::RemovePath_Other + * @tc.desc : using addpath_string and addpath_ string_ matchtype two methods to add path, + * judge the return value of countpaths + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemovePath_Other)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17400 + * @tc.name : Skills::AddType_String_CountTypes + * @tc.desc : using addtype_string method to add type and judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_CountTypes)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17500 + * @tc.name : Skills::AddType_String_CountTypes + * @tc.desc : loop uses addtype_string method to add type and judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_CountTypes)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17600 + * @tc.name : Skills::AddType_String_MatchType_CountTypes + * @tc.desc : using addtype_string_matchtype method to add type and judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_CountTypes)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17700 + * @tc.name : Skills::AddType_String_MatchType_CountTypes + * @tc.desc : loop uses addtype_string_matchtype method to add type and judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_CountTypes)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17800 + * @tc.name : Skills::AddType_PatternMatcher_CountTypes + * @tc.desc : using addtype_patternmatcher method to add type and judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_CountTypes)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_17900 + * @tc.name : Skills::AddType_PatternMatcher_CountTypes + * @tc.desc : loop uses addtype_patternmatcher method to add type and judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_17900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_CountTypes)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_17900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18000 + * @tc.name : Skills::CountTypes + * @tc.desc : judge the return value of counttypes when type is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::CountTypes)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18100 + * @tc.name : Skills::AddType_String_GetType + * @tc.desc : add a normal string to judge the return value of gettype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_GetType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18200 + * @tc.name : Skills::AddType_String_GetType + * @tc.desc : judge the return value of gettype, when the index value exceeds(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_GetType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18300 + * @tc.name : Skills::AddType_String_GetType + * @tc.desc : judge the return value of gettype when the index value is negative(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_GetType)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18400 + * @tc.name : Skills::AddType_String_GetType + * @tc.desc : judge the return value of gettype when scheme is null(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_GetType)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18500 + * @tc.name : Skills::AddType_String_GetType + * @tc.desc : add a special string to judge the return value of gettype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_GetType)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18600 + * @tc.name : Skills::AddType_String_GetType + * @tc.desc : loop addscheme, judge the return value of gettype(index 0)(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_GetType)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18700 + * @tc.name : Skills::AddType_String_MatchType_GetType + * @tc.desc : add a normal string to judge the return value of gettype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_GetType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18800 + * @tc.name : Skills::AddType_String_MatchType_GetType + * @tc.desc : judge the return value of gettype, when the index value exceeds(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_GetType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_18900 + * @tc.name : Skills::AddType_String_MatchType_GetType + * @tc.desc : judge the return value of gettype when the index value is negative(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_18900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_GetType)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_18900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19000 + * @tc.name : Skills::AddType_String_MatchType_GetType + * @tc.desc : judge the return value of gettype when scheme is null(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_GetType)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19100 + * @tc.name : Skills::AddType_String_MatchType_GetType + * @tc.desc : add a special string to judge the return value of gettype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_GetType)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19200 + * @tc.name : Skills::AddType_String_MatchType_GetType + * @tc.desc : loop addscheme, judge the return value of gettype(index 0)(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_GetType)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19300 + * @tc.name : Skills::AddType_PatternMatcher_GetType + * @tc.desc : add a normal string to judge the return value of gettype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_GetType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19400 + * @tc.name : Skills::AddType_PatternMatcher_GetType + * @tc.desc : judge the return value of gettype, when the index value exceeds(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_GetType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19500 + * @tc.name : Skills::AddType_PatternMatcher_GetType + * @tc.desc : judge the return value of gettype when the index value is negative(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_GetType)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19600 + * @tc.name : Skills::AddType_PatternMatcher_GetType + * @tc.desc : judge the return value of gettype when scheme is null(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_GetType)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19700 + * @tc.name : Skills::AddType_PatternMatcher_GetType + * @tc.desc : add a special string to judge the return value of gettype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_GetType)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19800 + * @tc.name : Skills::AddType_PatternMatcher_GetType + * @tc.desc : loop addscheme, judge the return value of gettype(index 0)(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_GetType)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_19900 + * @tc.name : Skills::GetType + * @tc.desc : judge the return value of gettype when type is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_19900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_19900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20000 + * @tc.name : Skills::AddType_String_HasType + * @tc.desc : loop addauthority, judge the return value of hastype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_HasType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20100 + * @tc.name : Skills::AddType_String_HasType + * @tc.desc : add a special string to judge the return value of hastype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_HasType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20200 + * @tc.name : Skills::AddType_String_MatchType_HasType + * @tc.desc : loop addauthority, judge the return value of hastype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_HasType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20300 + * @tc.name : Skills::AddType_String_MatchType_HasType + * @tc.desc : add a special string to judge the return value of hastype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_String_MatchType_HasType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20400 + * @tc.name : Skills::AddType_PatternMatcher_HasType + * @tc.desc : loop addauthority, judge the return value of hastype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_HasType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20500 + * @tc.name : Skills::AddType_PatternMatcher_HasType + * @tc.desc : add a special string to judge the return value of hastype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddType_PatternMatcher_HasType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20600 + * @tc.name : Skills::HasType + * @tc.desc : judge the return value of hastype,when authority is empty + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::HasType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20700 + * @tc.name : Skills::RemoveType_String + * @tc.desc : add specialstring. after deleting, judge hastype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20800 + * @tc.name : Skills::RemoveType_String + * @tc.desc : add specialstring, after deleting, judge gettype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_20900 + * @tc.name : Skills::RemoveType_String + * @tc.desc : loop add normalstring, after deleting, judge hastype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_20900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_20900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21000 + * @tc.name : Skills::RemoveType_String + * @tc.desc : loop add normalstring, delete specialstring and judge hastype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21100 + * @tc.name : Skills::RemoveType_String + * @tc.desc : loop add normalstring, after deleting, judge gettype (the index value exceeds)(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21200 + * @tc.name : Skills::RemoveType_String + * @tc.desc : loop add normalstring, delete specialstring and judge gettype(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21300 + * @tc.name : Skills::RemoveType_String + * @tc.desc : add specialstring, delete specialstring, and judge counttypes(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21400 + * @tc.name : Skills::RemoveType_String + * @tc.desc : loop add normalstring, delete normalstring, and judge counttypes(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21500 + * @tc.name : Skills::RemoveType_String + * @tc.desc : loop add normalstring, delete specialstring, and judge counttypes(addtype_string) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21600 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : add specialstring. after deleting, judge hastype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21700 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : add specialstring, after deleting, judge gettype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21800 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : loop add normalstring, after deleting, judge hastype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_21900 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : loop add normalstring, delete specialstring and + * judge hastype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_21900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_21900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22000 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : loop add normalstring, after deleting, + * judge gettype (the index value exceeds)(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22100 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : loop add normalstring, delete specialstring and + * judge gettype(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22200 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : add specialstring, delete specialstring, + * and judge counttypes(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22300 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : loop add normalstring, delete normalstring, + * and judge counttypes(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22400 + * @tc.name : Skills::RemoveType_String_MatchType + * @tc.desc : loop add normalstring, delete specialstring, + * and judge counttypes(addtype_string_matchtype) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_String_MatchType)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22500 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : add specialstring. after deleting, judge hastype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22600 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : add specialstring, after deleting, judge gettype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22700 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : loop add normalstring, after deleting, judge hastype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22800 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : loop add normalstring, delete specialstring and judge hastype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_22900 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : loop add normalstring, after deleting, judge gettype + * (the index value exceeds)(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_22900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_22900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23000 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : loop add normalstring, delete specialstring + * and judge gettype(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23100 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : add specialstring, delete specialstring, + * and judge counttypes(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23200 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : loop add normalstring, delete normalstring, + * and judge counttypes(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23300 + * @tc.name : Skills::RemoveType_PatternMatcher + * @tc.desc : loop add normalstring, delete specialstring, + * and judge counttypes(addtype_patternmatcher) + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = + "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_PatternMatcher)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23400 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add type, + * after deleting, judge the return value of hastype + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23500 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : loop uses addtype_string_ the matchtype method adds a type, and after deleting, + * judges the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23600 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add type, + * judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23700 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add special type, + * judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23800 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add special type, + * judge the return value of hastypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_23900 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add special type, + * judge the return value of hastypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_23900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_23900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24000 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add special type, + * judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24100 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add special type, + * judge the return value of counttypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24200 + * @tc.name : Skills::RemoveType_Other + * @tc.desc : using addtype_string and addtype_string_matchtype two methods to add special type, + * judge the return value of hastypes + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::RemoveType_Other)) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24300 + * @tc.name : Skills::GetEntities + * @tc.desc : add entity to determine the size of getentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntities)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24400 + * @tc.name : Skills::GetEntities + * @tc.desc : repeatedly add entity to determine the size of getentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntities)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24500 + * @tc.name : Skills::GetEntities + * @tc.desc : add entity to determine whether the return value of + * countentities is the same as the size of getentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntities)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24600 + * @tc.name : Skills::GetEntities + * @tc.desc : add entity to determine whether the return value of getentity + * is the same as the data in getentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntities)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24700 + * @tc.name : Skills::GetEntities + * @tc.desc : add specialstring entity to determine whether the return value of + * getentity is the same as the data in getentities + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetEntities)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24800 + * @tc.name : Skills::GetWantParams + * @tc.desc : judge whether the bool type value of setwantpams is the same as that of getwantpams + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetWantParams)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_24900 + * @tc.name : Skills::GetWantParams + * @tc.desc : judge whether the loog type value of setwantpams is the same as that of getwantpams + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_24900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetWantParams)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_24900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25000 + * @tc.name : Skills::GetWantParams + * @tc.desc : judge whether the int type value of setwantpams is the same as that of getwantpams + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetWantParams)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25100 + * @tc.name : Skills::GetWantParams + * @tc.desc : judge whether the string type value(specialstring) of setwantpams + * is the same as that of getwantpams + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetWantParams)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25200 + * @tc.name : Skills::GetWantParams + * @tc.desc : judge whether the string type value(normalstring)of setwantpams + * is the same as that of getwantpams + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::GetWantParams)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25300 + * @tc.name : Skills::Match + * @tc.desc : set the skills object and want object to judge the return value of match + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Match)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25400 + * @tc.name : Skills::Match + * @tc.desc : set the skills object and want object to judge the return value of match + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Match)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25500 + * @tc.name : Skills::Match + * @tc.desc : set the skills object and want object to judge the return value of match + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Match)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25600 + * @tc.name : Skills::Match + * @tc.desc : set the skills object and want object to judge the return value of match + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Match)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25700 + * @tc.name : Skills::Match + * @tc.desc : set the skills object and want object to judge the return value of match + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Match)) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25800 + * @tc.name : Skills::Match + * @tc.desc : set the skills object and want object to judge the return value of match + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Match)) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_25900 + * @tc.name : Skills::Unmarshalling + * @tc.desc : set the skills object data to be empty and the current object is marshaling. + * judge whether the unmatched object is the same as the current object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_25900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Unmarshalling)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_25900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26000 + * @tc.name : Skills::Unmarshalling + * @tc.desc : set the skills object data to be normalstring and the current object is marshaling. + * judge whether the unmatched object is the same as the current object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Unmarshalling)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26100 + * @tc.name : Skills::Unmarshalling + * @tc.desc : set the skills object data to be specialstringg and the current object is marshaling. + * judge whether the unmatched object is the same as the current object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Unmarshalling)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26200 + * @tc.name : Skills::Unmarshalling + * @tc.desc : set the skills object data to be specialstringg(normalstring,empty) + * and the current object is marshaling. + * judge whether the unmatched object is the same as the current object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Unmarshalling)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26300 + * @tc.name : SkillsApi::Skills + * @tc.desc : use skills skill; construct skill object in this way, + * and call count method to judge whether the construction is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26400 + * @tc.name : SkillsApi::Skills + * @tc.desc : use skills skill; construct skill object in this way, + * and call get method to judge whether the construction is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26500 + * @tc.name : SkillsApi::Skills + * @tc.desc : use skills skill; construct skill object in this way, + * and call has method to judge whether the construction is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26600 + * @tc.name : SkillsApi::Skills + * @tc.desc : use skills skill; in this way, construct the skill object, + * and call the remove method to judge whether the construction is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26700 + * @tc.name : SkillsApi::Skills_Skills + * @tc.desc : use skills copy constructor to create skill object and + * judge whether the copied object is equal to the original object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills_Skills)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26800 + * @tc.name : SkillsApi::Skills_Skills + * @tc.desc : use skills copy constructor to create skill object and + * judge whether the copied object is equal to the original object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills_Skills)) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_26900 + * @tc.name : SkillsApi::Skills_Skills + * @tc.desc : use skills copy constructor to create skill object and + * judge whether the copied object is equal to the original object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_26900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills_Skills)) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_26900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_27000 + * @tc.name : SkillsApi::Skills_Skills + * @tc.desc : use skills copy constructor to create skill object and + * judge whether the copied object is equal to the original object + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_27000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::Skills_Skills)) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_27000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_27100 + * @tc.name : SkillsApi::AddAction + * @tc.desc : Add a variety of characters as action to the skills object, + * use the count function to verify whether the addition is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_27100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddAction)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_27100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_27200 + * @tc.name : SkillsApi::AddEntity + * @tc.desc : Add a variety of characters as Entity to the skills object, + * use the count function to verify whether the addition is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_27200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddEntity)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_27200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_27300 + * @tc.name : SkillsApi::AddAuthority + * @tc.desc : Add a variety of characters as Authority to the skills object, + * use the count function to verify whether the addition is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_27300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddAuthority)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_27300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_27400 + * @tc.name : SkillsApi::AddScheme + * @tc.desc : Add a variety of characters as Scheme to the skills object, + * use the count function to verify whether the addition is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_27400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddScheme)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_27400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Skills_27500 + * @tc.name : SkillsApi::AddSchemeSpecificPart + * @tc.desc : Add a variety of characters as SchemeSpecificPart to the skills object, + * use the count function to verify whether the addition is successful + */ +HWTEST_F(ActsAmsKitSkillsTest, AMS_Page_Skills_27500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(fourthAbilityName, bundleName); + std::string eventData = "SkillsApi_" + std::to_string(static_cast(SkillsApi::AddSchemeSpecificPart)) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageFourthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageFourthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageFourthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Skills_27500 : " << i; + break; + } + } +} diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abd73ea412c04147c77c57cb3ba4c2d83bf8abbc --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_test.cpp @@ -0,0 +1,2081 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "event.h" +#include "ability_lifecycle_executor.h" +#include "ability_lifecycle.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "kit_test_common_info.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; +using MAP_STR_STR = std::map; + +static const std::string bundleName1 = "com.ohos.amsst.AppKitAbilityManager"; +static const std::string bundleName2 = "com.ohos.amsst.AppKit"; +static const std::string bundleName3 = "com.ohos.amsst.appN"; +static const std::string bundleName4 = "com.ohos.amsst.AppKitAbilityManagerFirst"; + +static const std::string thirdAbilityName = "ThirdAbility"; +static const std::string sixthAbilityName = "SixthAbility"; +static const std::string abilityManagerName = "KitTestAbilityManager"; +static const std::string abilityManagerSecondName = "KitTestAbilityManagerSecond"; +static const std::string terminatePageAbility = "requ_page_ability_terminate"; +static const std::string eventNameAbilityN1 = "resp_st_page_ability_callback"; +static const std::string launcherBundleName = "com.ohos.launcher"; +static const std::string systemUiBundle = "com.ohos.systemui"; +constexpr int WAIT_TIME = 3 * 1000; +constexpr int WAIT_LAUNCHER_OK = 5 * 1000; +constexpr int appFreezingTime = 60; + +std::vector bundleNameList = { + bundleName2, + bundleName3, +}; +std::vector hapNameList = { + "amsKitSystemTest", + "amsSystemTestN", +}; +static const std::string abilityNameBase = "AmsStAbilityN1"; +int amsKitSTCode = 0; +} // namespace + +class ActsAmsKitTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + void TestSkills(Want want); + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void CleanMsg(); + void ShowDump(); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber() = default; + }; + + static sptr appMs; + static sptr abilityMs; + static Event event; + static Event abilityEvent; + static StressTestLevel stLevel_; + static std::shared_ptr subscriber_; +}; + +Event ActsAmsKitTest::event = Event(); +Event ActsAmsKitTest::abilityEvent = Event(); +sptr ActsAmsKitTest::appMs = nullptr; +sptr ActsAmsKitTest::abilityMs = nullptr; +StressTestLevel ActsAmsKitTest::stLevel_ {}; +std::shared_ptr ActsAmsKitTest::subscriber_ = nullptr; + +void ActsAmsKitTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + STAbilityUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); + STAbilityUtil::Completed(abilityEvent, data.GetData(), data.GetCode()); +} + +void ActsAmsKitTest::SetUpTestCase(void) +{ + STAbilityUtil::InstallHaps(hapNameList); + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + appMs = STAbilityUtil::GetAppMgrService(); + abilityMs = STAbilityUtil::GetAbilityManagerService(); + if (appMs) { + appMs->SetAppFreezingTime(appFreezingTime); + } +} + +void ActsAmsKitTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + STAbilityUtil::UninstallBundle(bundleNameList); +} + +void ActsAmsKitTest::SetUp(void) +{} + +void ActsAmsKitTest::TearDown(void) +{ + STAbilityUtil::RemoveStack(1, abilityMs, WAIT_TIME, WAIT_LAUNCHER_OK); + CleanMsg(); +} + +bool ActsAmsKitTest::SubscribeEvent() +{ + const std::vector eventList = { + g_respPageThirdAbilityST, + g_respPageSixthAbilityST, + g_respPageManagerAbilityST, + g_respPageManagerSecondAbilityST, + g_respPageSixthAbilityLifecycleCallbacks, + eventNameAbilityN1, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ActsAmsKitTest::StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName) +{ + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, abilityName + g_abilityStateOnActive, 0), 0); +} + +void ActsAmsKitTest::CleanMsg() +{ + STAbilityUtil::CleanMsg(event); + STAbilityUtil::CleanMsg(abilityEvent); +} + +void ActsAmsKitTest::ShowDump() +{ + if (abilityMs) { + std::vector dumpInfo; + abilityMs->DumpState("-a", dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0100 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.Get runningprocessinfo + * 2.judge whether the current abilityname is in runningprocessinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0200 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.Get runningprocessinfo + * 2.judge whether the current launchability is in runningprocessinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0300 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : Get runningprocessinfo,Judge the process status of launch as background + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0400 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.Get runningprocessinfo + * 2.Judge the process status of current ability as foreground + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0500 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.start a new ability + * 2.Get runningprocessinfo + * 3.judge whether the new abilityname is in runningprocessinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0500, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_4"; + + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0600 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.start a new ability + * 2.Get runningprocessinfo + * 3.judge whether the old abilityname is in runningprocessinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0600, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_5"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0700 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.start a new ability + * 2.Get runningprocessinfo + * 3.judge whether the launch abilityname is in runningprocessinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0700, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_6"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0800 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.start a new ability + * 2.Get runningprocessinfo + * 3.Judge the process status of launch as background + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0800, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_7"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_0900 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.start a new ability + * 2.Get runningprocessinfo + * 3.Judge the process status of new ability as foreground + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_0900, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_8"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_0900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1000 + * @tc.name : AbilityManager::GetAllRunningProcesses + * @tc.desc : 1.start a new ability + * 2.Get runningprocessinfo + * 3.Judge the process status of old ability as background + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1000, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllRunningProcesses); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_9"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1100 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Get missionstack info with missionstack ID 1 + * 2.Judge size of missionrecords in get missionstackinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1200 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Get missionstack info with missionstack ID 1 + * 2.Judge whether the current ability is at the top of the stack + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1300 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Get missionstack info with missionstack ID 0 + * 2.Judge size of missionrecords in get missionstackinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1400 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Get missionstack info with missionstack ID 0 + * 2.Judge whether the launch ability is at the stack + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1500 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Start a new ability + * 2.Get missionstack info with missionstack ID 0 + * 3.Judge size of missionrecords in get missionstackinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1500, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_4"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1600 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Start a new ability + * 2.Get missionstack info with missionstack ID 0 + * 3.Judge whether the launch ability is at the stack + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1600, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_5"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1700 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Start a new ability + * 2.Get missionstack info with missionstack ID 1 + * 3.Judge size of missionrecords in get missionstackinfo + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1700, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_6"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1800 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Start a new ability + * 2.Get missionstack info with missionstack ID 1 + * 3.Judge size of abilityRecordInfos in get missionstackinfo.abilityRecordInfos + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1800, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_7"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_1900 + * @tc.name : AbilityManager::GetAllStackInfo + * @tc.desc : 1.Start a new ability + * 2.Get missionstack info with missionstack ID 1 + * 3.Judge whether the current ability and bottom ability is at the stack + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_1900, Function | MediumTest | Level1) +{ + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::GetAllStackInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_8"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_1900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2000 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the numMax(-1) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2100 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the flags(-1) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2200 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the flags(0) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2300 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the flags(3) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2400 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the size() of the return value of the queryrecentabilitymissioninfo function + * (parameter:flags(RECENT_WITH_EXCLUDED) ) + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2500 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the size() of the return value of the queryrecentabilitymissioninfo function + * (parameter:flags(RECENT_IGNORE_UNAVAILABLE) ) + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2600 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the member variables contained in the return value of the queryrecentabilitymassioninfo + * function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2700 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : 1.Strat a new ability + * 2.Get the return value of the queryrecentabilitymassioninfo function + * 3.Test the baseAbility in test member variable + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2700, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_7"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2800 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : 1.Strat a new ability + * 2.Get the return value of the queryrecentabilitymassioninfo function + * 3.Test the size in test member variable + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2800, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_8"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_2900 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : 1.Strat a new ability + * 2.Get the return value of the queryrecentabilitymassioninfo function + * 3.Test the baseAbility(abilityName and bundleName) in test member variable + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_2900, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_9"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_2900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3000 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : Test the numMax(-1) parameter of the QueryRunningAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3100 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : Test the numMax(0) parameter of the QueryRunningAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3200 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : Test the size() of the return value of the QueryRunningAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3300 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : 1.Get the return value of the QueryRunningAbilityMissionInfo function + * 2.Test the size in test member variable + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3400 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : 1.Start a new ability + * 2.Get the return value of the QueryRunningAbilityMissionInfo function + * 3.Test the baseAbility in test member variable + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3400, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_4"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3500 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : 1.Start a new ability + * 2.Get the return value of the QueryRunningAbilityMissionInfo function + * 3.Test the size and id in test member variable + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3500, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_5"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3600 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : 1.Start a new ability + * 2.Get the return value of the QueryRunningAbilityMissionInfo function + * 3.Test the baseAbility(bundleName and abilityName) in test member variable + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3600, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_6"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3700 + * @tc.name : IAbilityManager::MoveMissionToTop + * @tc.desc : 1.Use movemissiontotop to move the launch to the top + * 2.Confirm that OnBackground() of the current ability is called + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3700, Function | MediumTest | Level1) +{ + bool result = false; + StartAbilityKitTest(abilityManagerName, bundleName4); + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + int apiIndex = static_cast(AbilityManagerApi::MoveMissionToTop); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_0"; + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3800 + * @tc.name : IAbilityManager::MoveMissionToTop + * @tc.desc : 1.Use movemissiontotop to move the launch to the top + * 2.Confirm that OnBackground() of the current ability is called + * 3.Get runningprocessinfo in OnBackground() + * 4.Judge whether the current process state of launch is foreground + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::MoveMissionToTop); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_3900 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the numMax(INT32_MIN) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_3900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_10"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_3900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_4000 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the numMax(INT32_MAX) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_4000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_11"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_4000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_4100 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the flags(INT32_MIN) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_4100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_12"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_4100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_4200 + * @tc.name : AbilityManager::QueryRecentAbilityMissionInfo + * @tc.desc : Test the flags(INT32_MAX) parameter of the QueryRecentAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_4200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_13"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_4200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_4300 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : Test the numMax(INT32_MIN) parameter of the QueryRunningAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_4300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_4300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_AbilityManager_4400 + * @tc.name : AbilityManager::QueryRunningAbilityMissionInfo + * @tc.desc : Test the numMax(INT32_MAX) parameter of the QueryRunningAbilityMissionInfo function + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_AbilityManager_4400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(abilityManagerName, bundleName4); + int apiIndex = static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo); + std::string eventData = "AbilityManagerApi_" + std::to_string(apiIndex) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageManagerAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageManagerAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageManagerAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_AbilityManager_4400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0100 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : register the abilitylifecyclecallbacks class and count the call + * times of onabilitystart function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0200 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : register the abilitylifecyclecallbacks class and count the call + * times of onabilityinactivefunction in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0300 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : register the abilitylifecyclecallbacks class and count the call + * times of onabilitybackground in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0400 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : register the abilitylifecyclecallbacks class and count the call + * times of onabilityforeground in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0500 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : register the abilitylifecyclecallbacks class and count the call + * times of onabilityactive in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0600 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : register the abilitylifecyclecallbacks class and count the call + * times ofonabilitystop in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0700 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : loop register the abilitylifecyclecallbacks class(same class) and count the call + * times of onabilitystart in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0800 + * @tc.name : OHOSApplicationApi::RegisterAbilityLifecycleCallbacks + * @tc.desc : loop register the abilitylifecyclecallbacks class(different class) and count the call + * times of onabilitystart in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_0900 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : unregister the abilitylifecyclecallbacks class and count the call + * times of onabilitystart function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_0900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_0900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1000 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : unregister the abilitylifecyclecallbacks class and count the call + * times of onabilityinactivefunction in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1100 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : unregister the abilitylifecyclecallbacks class and count the call + * times of onabilitybackground in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1200 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : unregister the abilitylifecyclecallbacks class and count the call + * times of onabilityforeground in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1300 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : unregister the abilitylifecyclecallbacks class and count the call + * times of onabilityactive in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1400 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : unregister the abilitylifecyclecallbacks class and count the call + * times ofonabilitystop in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1500 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : loop unregister the abilitylifecyclecallbacks class(same class) and count the call + * times of onabilitystart in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1600 + * @tc.name : OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks + * @tc.desc : loop unregister the abilitylifecyclecallbacks class(different class) and count the call + * times of onabilitystart in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterAbilityLifecycleCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1700 + * @tc.name : OHOSApplicationApi::DispatchAbilitySavedState + * @tc.desc : register the abilitylifecyclecallbacks class and count the call + * times of onabilitysavestate function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1700, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::DispatchAbilitySavedState); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1800 + * @tc.name : OHOSApplicationApi::DispatchAbilitySavedState + * @tc.desc : loop register the abilitylifecyclecallbacks class(same class) and count the call + * times of onabilitysavestate in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1800, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::DispatchAbilitySavedState); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_1900 + * @tc.name : OHOSApplicationApi::RegisterElementsCallbacks + * @tc.desc : register elementscallbacks class and count the call times of + * onconfigurationupdated function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_1900, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_1900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2000 + * @tc.name : OHOSApplicationApi::RegisterElementsCallbacks + * @tc.desc : register elementscallbacks class and count the call times of + * onmemorylevel function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2000, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_2000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2100 + * @tc.name : OHOSApplicationApi::RegisterElementsCallbacks + * @tc.desc : loop register elementscallbacks class and count the call times of onconfigurationupdated function + in + * the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2100, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_2100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2200 + * @tc.name : OHOSApplicationApi::RegisterElementsCallbacks + * @tc.desc : loop register elementscallbacks class and count the call times of onmemorylevel function in the + * callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2200, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::RegisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_2200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2300 + * @tc.name : OHOSApplicationApi::UnregisterElementsCallbacks + * @tc.desc : unregister elementscallbacks class and count the call + * times of onconfigurationupdated function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2300, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_2300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2400 + * @tc.name : OHOSApplicationApi::UnregisterElementsCallbacks + * @tc.desc : unregister elementscallbacks class and count the call times of + * onmemorylevel function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2400, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_2400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2500 + * @tc.name : OHOSApplicationApi::UnregisterElementsCallbacks + * @tc.desc : loop unregister elementscallbacks class and count the call times of + * onconfigurationupdated function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2500, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_2500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2600 + * @tc.name : OHOSApplicationApi::UnregisterElementsCallbacks + * @tc.desc : loop unregister elementscallbacks class and count the call times of + * onmemorylevel function in the callback class + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2600, Function | MediumTest | Level1) +{ + StartAbilityKitTest(sixthAbilityName, bundleName2); + int apiIndex = static_cast(OHOSApplicationApi::UnregisterElementsCallbacks); + std::string eventData = "OHOSApplicationApi_" + std::to_string(apiIndex) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_requPageSixthAbilityST, ++amsKitSTCode, eventData); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_respPageSixthAbilityST, amsKitSTCode)); + std::string data = STAbilityUtil::GetData(event, g_respPageSixthAbilityST, amsKitSTCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + CleanMsg(); + if (!result && stLevel_.AMSLevel > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Application_2600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Application_2700 + * @tc.name : OHOSApplicationApi::Lifecycle callback function + * @tc.desc : 1.Control the life cycle of the ability + * 2.Application registration capability life cycle callback + * 3.The callback function corresponding to the registered class will be called + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2700, Function | MediumTest | Level1) +{ + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = thirdAbilityName; + Want want = STAbilityUtil::MakeWant("device", sixthAbilityName, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, sixthAbilityName + g_onAbilityActive, 0), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, sixthAbilityName + g_onAbilityInactive, 0), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, thirdAbilityName + g_onAbilityStart, 0), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, thirdAbilityName + g_onAbilityActive, 0), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, sixthAbilityName + g_onAbilityBackground, 0), 0); + CleanMsg(); + STAbilityUtil::RemoveStack(1, abilityMs, WAIT_TIME, WAIT_LAUNCHER_OK); + } +} + +/** + * @tc.number : AMS_Page_Application_2800 + * @tc.name : OHOSApplicationApi::Lifecycle callback function + * @tc.desc : 1.Control the life cycle of the ability + * 2.Application registration capability life cycle callback + * 3.The callback function corresponding to the registered class will be called + */ +HWTEST_F(ActsAmsKitTest, AMS_Page_Application_2800, Function | MediumTest | Level1) +{ + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + MAP_STR_STR params; + int onStopWantCount = 1; + params["targetBundle"] = bundleName3; + params["targetAbility"] = abilityNameBase; + Want want = STAbilityUtil::MakeWant("device", sixthAbilityName, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, sixthAbilityName + g_onAbilityActive, 0), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, sixthAbilityName + g_onAbilityInactive, 0), 0); + EXPECT_EQ( + STAbilityUtil::WaitCompleted(abilityEvent, abilityNameBase + g_abilityStateOnActive, onStopWantCount), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, sixthAbilityName + g_onAbilityBackground, 0), 0); + STAbilityUtil::StopAbility(terminatePageAbility, 0, abilityNameBase); + EXPECT_EQ(STAbilityUtil::WaitCompleted(abilityEvent, sixthAbilityName + g_onAbilityActive, 0), 0); + EXPECT_EQ( + STAbilityUtil::WaitCompleted(abilityEvent, abilityNameBase + g_abilityStateOnStop, onStopWantCount), 0); + + CleanMsg(); + STAbilityUtil::RemoveStack(1, abilityMs, WAIT_TIME, WAIT_LAUNCHER_OK); + } +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_want_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_want_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..387482148cf078d1b1ada390f423ace20f555e21 --- /dev/null +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_want_test.cpp @@ -0,0 +1,8981 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "semaphore_ex.h" +#include "skills.h" +#include "event.h" +#include "ability_lifecycle_executor.h" +#include "ability_lifecycle.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "kit_test_common_info.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; +using MAP_STR_STR = std::map; + +static const std::string bundleName = "com.ohos.amsst.AppKit"; +static const std::string secondAbilityName = "SecondAbility"; + +std::vector bundleNameList = { + "com.ohos.amsst.AppKit", +}; +std::vector hapNameList = { + "amsKitSystemTest", +}; +constexpr int WAIT_TIME = 1000; +int amsKitSystemTestSecondAbilityCode = 100; +constexpr int delay = 10; +} // namespace + +class ActsAmsKitWantTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + void StartSecondAbility(); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber() = default; + }; + + static sptr appMs; + static sptr abilityMs; + static Event event; + static std::map mapState; + static StressTestLevel stLevel_; + static std::shared_ptr subscriber_; +}; + +std::map ActsAmsKitWantTest::mapState = { + {"OnStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnCommand", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnConnect", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnDisConnect", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnAbilityActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnAbilityInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnAbilityForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStateChanged", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, +}; + +StressTestLevel ActsAmsKitWantTest::stLevel_ {}; +Event ActsAmsKitWantTest::event = Event(); +sptr ActsAmsKitWantTest::appMs = nullptr; +sptr ActsAmsKitWantTest::abilityMs = nullptr; +std::shared_ptr ActsAmsKitWantTest::subscriber_ = nullptr; + +void ActsAmsKitWantTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + STAbilityUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void ActsAmsKitWantTest::SetUpTestCase(void) +{ + STAbilityUtil::InstallHaps(hapNameList); + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; +} + +void ActsAmsKitWantTest::TearDownTestCase(void) +{ + STAbilityUtil::UninstallBundle(bundleNameList); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ActsAmsKitWantTest::SetUp(void) +{} + +void ActsAmsKitWantTest::TearDown(void) +{ + STAbilityUtil::CleanMsg(event); +} + +bool ActsAmsKitWantTest::SubscribeEvent() +{ + const std::vector eventList = { + g_EVENT_RESP_SECOND, + + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ActsAmsKitWantTest::StartSecondAbility() +{ + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", secondAbilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, mapState["onActive"], delay)); +} + +/** + * @tc.number : AMS_Page_Want_0100 + * @tc.name : Want copy constructor + * @tc.desc : Want object copy + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::WantCopy) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0200 + * @tc.name : Want copy-assignment + * @tc.desc : Want object assignment + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::WantAssign) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0300 + * @tc.name : Want.AddEntity + * @tc.desc : add empty entity + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::AddEntity) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0400 + * @tc.name : Want.AddEntity + * @tc.desc : add entity with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::AddEntity) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0500 + * @tc.name : Want.AddEntity + * @tc.desc : add entity continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::AddEntity) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0600 + * @tc.name : Want.AddFlags + * @tc.desc : add flags minimum + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::AddFlags) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0700 + * @tc.name : Want.AddFlags + * @tc.desc : add flags maximum + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::AddFlags) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0800 + * @tc.name : Want.AddFlags + * @tc.desc : add flags continuouly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::AddFlags) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_0900 + * @tc.name : Want.ClearWant + * @tc.desc : clear want normally + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_0900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ClearWant) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_0900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1000 + * @tc.name : Want.ClearWant + * @tc.desc : clear want continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ClearWant) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1100 + * @tc.name : Want.CountEntities + * @tc.desc : count entity on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::CountEntities) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1200 + * @tc.name : Want.CountEntities + * @tc.desc : count entity after add entity + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::CountEntities) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1300 + * @tc.name : Want.FormatMimeType + * @tc.desc : format normal mime type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatMimeType) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1400 + * @tc.name : Want.FormatMimeType + * @tc.desc : format uppercase mime type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatMimeType) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1500 + * @tc.name : Want.FormatMimeType + * @tc.desc : format mime type with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatMimeType) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1600 + * @tc.name : Want.FormatMimeType + * @tc.desc : format mime type with space and tab + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatMimeType) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1700 + * @tc.name : Want.FormatType + * @tc.desc : format normal type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatType) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1800 + * @tc.name : Want.FormatType + * @tc.desc : format uppercase type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatType) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_1900 + * @tc.name : Want.FormatType + * @tc.desc : format type with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_1900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatType) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_1900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2000 + * @tc.name : Want.FormatType + * @tc.desc : format type with space, uppercase and tab + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatType) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2100 + * @tc.name : Want.FormatUri + * @tc.desc : format uri string including duplicated property + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUri) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2200 + * @tc.name : Want.FormatUri + * @tc.desc : format uri string including property of ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUri) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2300 + * @tc.name : Want.FormatUri + * @tc.desc : format uri string including parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUri) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2400 + * @tc.name : Want.FormatUri + * @tc.desc : format return value of ToUri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUri) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2500 + * @tc.name : Want.FormatUriAndType + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUriAndType) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2600 + * @tc.name : Want.FormatUriAndType + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUriAndType) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2700 + * @tc.name : Want.FormatUriAndType + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUriAndType) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2800 + * @tc.name : Want.FormatUriAndType + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::FormatUriAndType) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_2900 + * @tc.name : Want.GetAction + * @tc.desc : get empty action + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_2900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetAction) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_2900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3000 + * @tc.name : Want.GetAction + * @tc.desc : set and get action + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetAction) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3100 + * @tc.name : Want.GetAction + * @tc.desc : set and get action continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetAction) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3200 + * @tc.name : Want.GetBundle + * @tc.desc : get empty bundle + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBundle) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3300 + * @tc.name : Want.GetBundle + * @tc.desc : set and get bundle + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBundle) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3400 + * @tc.name : Want.GetBundle + * @tc.desc : set and get bundle continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBundle) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3500 + * @tc.name : Want.GetEntities + * @tc.desc : get empty entities + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetEntities) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3600 + * @tc.name : Want.GetEntities + * @tc.desc : add entity and get entities + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetEntities) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3700 + * @tc.name : Want.GetEntities + * @tc.desc : add entity and get entities continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetEntities) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3800 + * @tc.name : Want.GetElement + * @tc.desc : get empty element + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetElement) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_3900 + * @tc.name : Want.GetElement + * @tc.desc : set and get element + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_3900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetElement) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_3900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4000 + * @tc.name : Want.GetElement + * @tc.desc : set and get element continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetElement) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4100 + * @tc.name : Want.GetUri + * @tc.desc : get empty uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetUri) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4200 + * @tc.name : Want.GetUri + * @tc.desc : set and get uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetUri) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4300 + * @tc.name : Want.GetUri + * @tc.desc : set and get uri continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetUri) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4400 + * @tc.name : Want.GetUriString + * @tc.desc : get empty uri string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetUriString) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4500 + * @tc.name : Want.GetUriString + * @tc.desc : set property and get uri string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetUriString) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4600 + * @tc.name : Want.GetUriString + * @tc.desc : set uri and get uri string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetUriString) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4700 + * @tc.name : Want.GetUriString + * @tc.desc : get uri string continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetUriString) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4800 + * @tc.name : Want.GetFlags + * @tc.desc : get empty flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFlags) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_4900 + * @tc.name : Want.GetFlags + * @tc.desc : set and get flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_4900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFlags) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_4900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5000 + * @tc.name : Want.GetFlags + * @tc.desc : set and get flags continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFlags) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5100 + * @tc.name : Want.GetScheme + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetScheme) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5200 + * @tc.name : Want.GetScheme + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetScheme) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5300 + * @tc.name : Want.GetScheme + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetScheme) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5400 + * @tc.name : Want.GetScheme + * @tc.desc : + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetScheme) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5500 + * @tc.name : Want.GetType + * @tc.desc : get empty type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetType) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5600 + * @tc.name : Want.GetType + * @tc.desc : set and get type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetType) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5700 + * @tc.name : Want.GetType + * @tc.desc : set and get type continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetType) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5800 + * @tc.name : Want.HasEntity + * @tc.desc : no any entity + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasEntity) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_5900 + * @tc.name : Want.HasEntity + * @tc.desc : no target entity + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_5900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasEntity) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_5900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6000 + * @tc.name : Want.HasEntity + * @tc.desc : target entity exists + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasEntity) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6100 + * @tc.name : Want.HasEntity + * @tc.desc : HasEntity continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasEntity) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6200 + * @tc.name : Want.MakeMainAbility + * @tc.desc : MakeMainAbility with empty ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::MakeMainAbility) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6300 + * @tc.name : Want.MakeMainAbility + * @tc.desc : MakeMainAbility with normal ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::MakeMainAbility) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6400 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6500 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with action + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6600 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6700 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6800 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with entity + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_6900 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with element + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_6900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_6900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7000 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with bool parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7100 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with bool array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7200 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with byte parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7300 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with byte array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_9"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7400 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with char parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_10"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7500 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with char array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_11"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7600 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with int parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_12"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7700 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with int array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_13"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7800 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with double parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_14"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_7900 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with double array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_7900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_15"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_7900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8000 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with float parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_16"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8100 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with float array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_17"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8200 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with long parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_18"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8300 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with long array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_19"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8400 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with short parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_20"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8500 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with short array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_21"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8600 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with string parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_22"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8700 + * @tc.name : Want.Marshalling + * @tc.desc : marshall and unmarshall Want with string array parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::Marshalling) + "_23"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8800 + * @tc.name : Want.ParseUri + * @tc.desc : parse uri that has only key, no equals sign and value + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_8900 + * @tc.name : Want.ParseUri + * @tc.desc : parse string parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_8900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_8900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9000 + * @tc.name : Want.ParseUri + * @tc.desc : parse uri that has special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9100 + * @tc.name : Want.ParseUri + * @tc.desc : parse flag that is a hexadecimal starting with "0X" + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9200 + * @tc.name : Want.ParseUri + * @tc.desc : parse flag that has no value + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9300 + * @tc.name : Want.ParseUri + * @tc.desc : parse uri that has no head "#Want;" + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9400 + * @tc.name : Want.ParseUri + * @tc.desc : parse uri that flag type is string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9500 + * @tc.name : Want.ParseUri + * @tc.desc : parse uri that has only all keys and equals sign, no value + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9600 + * @tc.name : Want.ParseUri + * @tc.desc : parse empty string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9700 + * @tc.name : Want.ParseUri + * @tc.desc : parse parameter of float array and string array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_9"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9800 + * @tc.name : Want.ParseUri + * @tc.desc : parse parameter of float array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_10"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_9900 + * @tc.name : Want.ParseUri + * @tc.desc : parse parameter of float and string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_9900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_11"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_9900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10000 + * @tc.name : Want.ParseUri + * @tc.desc : parse action, entity, flags, element + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_12"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10100 + * @tc.name : Want.ParseUri + * @tc.desc : parse uri that make empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_13"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10200 + * @tc.name : Want.ParseUri + * @tc.desc : parse uri that has only key and euqals sign, no value + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_14"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10300 + * @tc.name : Want.RemoveEntity + * @tc.desc : remove entity from empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveEntity) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10400 + * @tc.name : Want.RemoveEntity + * @tc.desc : add and remove normal entity + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveEntity) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10500 + * @tc.name : Want.RemoveEntity + * @tc.desc : add and remove entity alternatively + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveEntity) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10600 + * @tc.name : Want.RemoveEntity + * @tc.desc : add and remove entity with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveEntity) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10700 + * @tc.name : Want.RemoveEntity + * @tc.desc : add entity repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveEntity) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10800 + * @tc.name : Want.RemoveFlags + * @tc.desc : remove flags from empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveFlags) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_10900 + * @tc.name : Want.RemoveFlags + * @tc.desc : add and remove flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_10900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveFlags) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_10900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11000 + * @tc.name : Want.RemoveFlags + * @tc.desc : set and remove flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveFlags) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11100 + * @tc.name : Want.RemoveFlags + * @tc.desc : set, add and remove flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveFlags) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11200 + * @tc.name : Want.RemoveFlags + * @tc.desc : remove flags repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveFlags) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11300 + * @tc.name : Want.SetAction + * @tc.desc : get empty action + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetAction) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11400 + * @tc.name : Want.SetAction + * @tc.desc : set and get empty action + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetAction) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11500 + * @tc.name : Want.SetAction + * @tc.desc : set and get long action + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetAction) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11600 + * @tc.name : Want.SetAction + * @tc.desc : set and get action with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetAction) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11700 + * @tc.name : Want.SetAction + * @tc.desc : set and get action continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetAction) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11800 + * @tc.name : Want.SetBundle + * @tc.desc : get empty bundle + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetBundle) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_11900 + * @tc.name : Want.SetBundle + * @tc.desc : set and get empty bundle + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_11900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetBundle) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_11900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12000 + * @tc.name : Want.SetBundle + * @tc.desc : set and get long bundle + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetBundle) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12100 + * @tc.name : Want.SetBundle + * @tc.desc : set and get bundle with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetBundle) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12200 + * @tc.name : Want.SetBundle + * @tc.desc : set and get bundle continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetBundle) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12300 + * @tc.name : Want.SetElement + * @tc.desc : get empty element + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElement) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12400 + * @tc.name : Want.SetElement + * @tc.desc : set and get empty element + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElement) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12500 + * @tc.name : Want.SetElement + * @tc.desc : set and get element continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElement) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12600 + * @tc.name : Want.SetElementName_String_String + * @tc.desc : get empty ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12700 + * @tc.name : Want.SetElementName_String_String + * @tc.desc : set and get empty ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12800 + * @tc.name : Want.SetElementName_String_String + * @tc.desc : set and get long ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_12900 + * @tc.name : Want.SetElementName_String_String + * @tc.desc : set and get ElementName with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_12900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_12900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13000 + * @tc.name : Want.SetElementName_String_String + * @tc.desc : set and get ElementName continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13100 + * @tc.name : Want.SetElementName_String_String_String + * @tc.desc : get empty ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String_String) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13200 + * @tc.name : Want.SetElementName_String_String_String + * @tc.desc : set and get empty ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String_String) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13300 + * @tc.name : Want.SetElementName_String_String_String + * @tc.desc : set and get long ElementName + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String_String) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13400 + * @tc.name : Want.SetElementName_String_String_String + * @tc.desc : set and get ElementName with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String_String) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13500 + * @tc.name : Want.SetElementName_String_String_String + * @tc.desc : set and get ElementName continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetElementName_String_String_String) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13600 + * @tc.name : Want.SetFlags + * @tc.desc : get empty flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13700 + * @tc.name : Want.SetFlags + * @tc.desc : set max unsigned flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13800 + * @tc.name : Want.SetFlags + * @tc.desc : remove max unsigned flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_13900 + * @tc.name : Want.SetFlags + * @tc.desc : set and remove max unsigned flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_13900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_13900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14000 + * @tc.name : Want.SetFlags + * @tc.desc : add max unsigned flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14100 + * @tc.name : Want.SetFlags + * @tc.desc : add and remove max unsigned flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14200 + * @tc.name : Want.SetFlags + * @tc.desc : set and add flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14300 + * @tc.name : Want.SetFlags + * @tc.desc : add and set flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14400 + * @tc.name : Want.SetFlags + * @tc.desc : add one flags and remove another flags + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14500 + * @tc.name : Want.SetFlags + * @tc.desc : add and remove flags continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_9"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14600 + * @tc.name : Want.SetFlags + * @tc.desc : set flags continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetFlags) + "_10"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14700 + * @tc.name : Want.SetType + * @tc.desc : set empty type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetType) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14800 + * @tc.name : Want.SetType + * @tc.desc : set twice and get once + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetType) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_14900 + * @tc.name : Want.SetType + * @tc.desc : set type with special character + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_14900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetType) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_14900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15000 + * @tc.name : Want.SetType + * @tc.desc : set type repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetType) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15100 + * @tc.name : Want.SetUri + * @tc.desc : set empty uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUri) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15200 + * @tc.name : Want.SetUri + * @tc.desc : set uri with property action + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUri) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15300 + * @tc.name : Want.SetUri + * @tc.desc : set uri with string parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUri) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15400 + * @tc.name : Want.SetUri + * @tc.desc : set uri continuously + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUri) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15500 + * @tc.name : Want.SetUriAndType + * @tc.desc : set empty uri and type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUriAndType) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15600 + * @tc.name : Want.SetUriAndType + * @tc.desc : set bad format uri and type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUriAndType) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15700 + * @tc.name : Want.SetUriAndType + * @tc.desc : set uri with ElementName and type + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUriAndType) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15800 + * @tc.name : Want.SetUriAndType + * @tc.desc : set uri and type repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetUriAndType) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_15900 + * @tc.name : Want.ToUri + * @tc.desc : empty Want to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_15900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_15900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16000 + * @tc.name : Want.ToUri + * @tc.desc : Want with action to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16100 + * @tc.name : Want.ToUri + * @tc.desc : Want with entities to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16200 + * @tc.name : Want.ToUri + * @tc.desc : Want with flags to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16300 + * @tc.name : Want.ToUri + * @tc.desc : Want with ElementName to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16400 + * @tc.name : Want.ToUri + * @tc.desc : Want with string parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_5"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16500 + * @tc.name : Want.ToUri + * @tc.desc : Want with bool parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_6"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16600 + * @tc.name : Want.ToUri + * @tc.desc : Want with char parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_7"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16700 + * @tc.name : Want.ToUri + * @tc.desc : Want with byte parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_8"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16800 + * @tc.name : Want.ToUri + * @tc.desc : Want with short parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_9"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_16900 + * @tc.name : Want.ToUri + * @tc.desc : Want with int parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_16900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_10"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_16900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17000 + * @tc.name : Want.ToUri + * @tc.desc : Want with long parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_11"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17100 + * @tc.name : Want.ToUri + * @tc.desc : Want with float parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_12"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17200 + * @tc.name : Want.ToUri + * @tc.desc : Want with double parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_13"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17300 + * @tc.name : Want.ToUri + * @tc.desc : Want with string array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_14"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17400 + * @tc.name : Want.ToUri + * @tc.desc : Want with bool array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_15"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17500 + * @tc.name : Want.ToUri + * @tc.desc : Want with char array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_16"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17600 + * @tc.name : Want.ToUri + * @tc.desc : Want with byte array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_17"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17700 + * @tc.name : Want.ToUri + * @tc.desc : Want with short array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_18"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17800 + * @tc.name : Want.ToUri + * @tc.desc : Want with int array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_19"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_17900 + * @tc.name : Want.ToUri + * @tc.desc : Want with long array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_17900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_20"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_17900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18000 + * @tc.name : Want.ToUri + * @tc.desc : Want with float array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_21"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18100 + * @tc.name : Want.ToUri + * @tc.desc : Want with double array parameter to uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ToUri) + "_22"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18200 + * @tc.name : Want.WantParseUri + * @tc.desc : empty Want to and from uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::WantParseUri) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18300 + * @tc.name : Want.WantParseUri + * @tc.desc : Want with property to and from uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::WantParseUri) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18400 + * @tc.name : Want.WantParseUri + * @tc.desc : Want with parameter to and from uri + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::WantParseUri) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18500 + * @tc.name : Want.GetParams + * @tc.desc : get params from empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetParams) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18600 + * @tc.name : Want.GetParams + * @tc.desc : set and get params + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetParams) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18700 + * @tc.name : Want.GetParams + * @tc.desc : set and get params repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetParams) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18800 + * @tc.name : Want.GetByteParam + * @tc.desc : get byte on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetByteParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_18900 + * @tc.name : Want.GetByteParam + * @tc.desc : get existed byte param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_18900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetByteParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_18900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19000 + * @tc.name : Want.GetByteParam + * @tc.desc : get byte param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetByteParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19100 + * @tc.name : Want.GetByteArrayParam + * @tc.desc : get byte array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetByteArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19200 + * @tc.name : Want.GetByteArrayParam + * @tc.desc : get existed byte array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetByteArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19300 + * @tc.name : Want.GetByteArrayParam + * @tc.desc : get byte array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetByteArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19400 + * @tc.name : Want.GetBoolParam + * @tc.desc : get bool on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBoolParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19500 + * @tc.name : Want.GetBoolParam + * @tc.desc : get existed bool param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBoolParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19600 + * @tc.name : Want.GetBoolParam + * @tc.desc : get bool param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBoolParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19700 + * @tc.name : Want.GetBoolArrayParam + * @tc.desc : get bool array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBoolArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19800 + * @tc.name : Want.GetBoolArrayParam + * @tc.desc : get existed bool array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBoolArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_19900 + * @tc.name : Want.GetBoolArrayParam + * @tc.desc : get bool array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_19900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetBoolArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_19900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20000 + * @tc.name : Want.GetCharParam + * @tc.desc : get char on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetCharParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20100 + * @tc.name : Want.GetCharParam + * @tc.desc : get existed char param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetCharParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20200 + * @tc.name : Want.GetCharParam + * @tc.desc : get char param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetCharParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20300 + * @tc.name : Want.GetCharArrayParam + * @tc.desc : get char array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetCharArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20400 + * @tc.name : Want.GetCharArrayParam + * @tc.desc : get existed char array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetCharArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20500 + * @tc.name : Want.GetCharArrayParam + * @tc.desc : get char array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetCharArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20600 + * @tc.name : Want.GetIntParam + * @tc.desc : get int on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetIntParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20700 + * @tc.name : Want.GetIntParam + * @tc.desc : get existed int param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetIntParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20800 + * @tc.name : Want.GetIntParam + * @tc.desc : get int param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetIntParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_20900 + * @tc.name : Want.GetIntArrayParam + * @tc.desc : get int array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_20900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetIntArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_20900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21000 + * @tc.name : Want.GetIntArrayParam + * @tc.desc : get existed int array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetIntArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21100 + * @tc.name : Want.GetIntArrayParam + * @tc.desc : get int array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetIntArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21200 + * @tc.name : Want.GetDoubleParam + * @tc.desc : get double on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetDoubleParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21300 + * @tc.name : Want.GetDoubleParam + * @tc.desc : get existed double param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetDoubleParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21400 + * @tc.name : Want.GetDoubleParam + * @tc.desc : get double param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetDoubleParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21500 + * @tc.name : Want.GetDoubleArrayParam + * @tc.desc : get double array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetDoubleArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21600 + * @tc.name : Want.GetDoubleArrayParam + * @tc.desc : get existed double array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetDoubleArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21700 + * @tc.name : Want.GetDoubleArrayParam + * @tc.desc : get double array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetDoubleArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21800 + * @tc.name : Want.GetFloatParam + * @tc.desc : get float on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFloatParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_21900 + * @tc.name : Want.GetFloatParam + * @tc.desc : get existed float param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_21900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFloatParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_21900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22000 + * @tc.name : Want.GetFloatParam + * @tc.desc : get float param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFloatParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22100 + * @tc.name : Want.GetFloatArrayParam + * @tc.desc : get float array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFloatArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22200 + * @tc.name : Want.GetFloatArrayParam + * @tc.desc : get existed float array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFloatArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22300 + * @tc.name : Want.GetFloatArrayParam + * @tc.desc : get float array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetFloatArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22400 + * @tc.name : Want.GetLongParam + * @tc.desc : get long on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetLongParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22500 + * @tc.name : Want.GetLongParam + * @tc.desc : get existed long param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetLongParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22600 + * @tc.name : Want.GetLongParam + * @tc.desc : get long param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetLongParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22700 + * @tc.name : Want.GetLongArrayParam + * @tc.desc : get long array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetLongArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22800 + * @tc.name : Want.GetLongArrayParam + * @tc.desc : get existed long array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetLongArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_22900 + * @tc.name : Want.GetLongArrayParam + * @tc.desc : get long array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_22900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetLongArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_22900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23000 + * @tc.name : Want.GetShortParam + * @tc.desc : get short on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetShortParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23100 + * @tc.name : Want.GetShortParam + * @tc.desc : get existed short param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetShortParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23200 + * @tc.name : Want.GetShortParam + * @tc.desc : get short param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetShortParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23300 + * @tc.name : Want.GetShortArrayParam + * @tc.desc : get short array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetShortArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23400 + * @tc.name : Want.GetShortArrayParam + * @tc.desc : get existed short array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetShortArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23500 + * @tc.name : Want.GetShortArrayParam + * @tc.desc : get short array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetShortArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23600 + * @tc.name : Want.GetStringParam + * @tc.desc : get string on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetStringParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23700 + * @tc.name : Want.GetStringParam + * @tc.desc : get existed string param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetStringParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23800 + * @tc.name : Want.GetStringParam + * @tc.desc : get string param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetStringParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_23900 + * @tc.name : Want.GetStringArrayParam + * @tc.desc : get string array on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_23900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetStringArrayParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_23900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24000 + * @tc.name : Want.GetStringArrayParam + * @tc.desc : get existed string array param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetStringArrayParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24100 + * @tc.name : Want.GetStringArrayParam + * @tc.desc : get string array param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetStringArrayParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24200 + * @tc.name : Want.SetParam_byte + * @tc.desc : max byte + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24300 + * @tc.name : Want.SetParam_byte + * @tc.desc : min byte + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24400 + * @tc.name : Want.SetParam_byte + * @tc.desc : different byte value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24500 + * @tc.name : Want.SetParam_byte + * @tc.desc : different byte value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24600 + * @tc.name : Want.SetParam_byte + * @tc.desc : pressure of byte + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24700 + * @tc.name : Want.SetParam_byte_array + * @tc.desc : empty byte array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24800 + * @tc.name : Want.SetParam_byte_array + * @tc.desc : big byte array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_24900 + * @tc.name : Want.SetParam_byte_array + * @tc.desc : different byte array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_24900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_24900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25000 + * @tc.name : Want.SetParam_byte_array + * @tc.desc : different byte array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25100 + * @tc.name : Want.SetParam_byte_array + * @tc.desc : pressure of byte array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_byte_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25200 + * @tc.name : Want.SetParam_bool + * @tc.desc : bool value false + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25300 + * @tc.name : Want.SetParam_bool + * @tc.desc : bool value true + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25400 + * @tc.name : Want.SetParam_bool + * @tc.desc : different bool value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25500 + * @tc.name : Want.SetParam_bool + * @tc.desc : different bool value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25600 + * @tc.name : Want.SetParam_bool + * @tc.desc : pressure of bool + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25700 + * @tc.name : Want.SetParam_bool_array + * @tc.desc : empty bool array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25800 + * @tc.name : Want.SetParam_bool_array + * @tc.desc : big bool array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_25900 + * @tc.name : Want.SetParam_bool_array + * @tc.desc : different bool array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_25900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_25900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26000 + * @tc.name : Want.SetParam_bool_array + * @tc.desc : different bool array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26100 + * @tc.name : Want.SetParam_bool_array + * @tc.desc : pressure of bool array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_bool_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26200 + * @tc.name : Want.SetParam_char + * @tc.desc : empty char + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26300 + * @tc.name : Want.SetParam_char + * @tc.desc : char default value + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26400 + * @tc.name : Want.SetParam_char + * @tc.desc : different char value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26500 + * @tc.name : Want.SetParam_char + * @tc.desc : different char value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26600 + * @tc.name : Want.SetParam_char + * @tc.desc : pressure char + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26700 + * @tc.name : Want.SetParam_char_array + * @tc.desc : empty char array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26800 + * @tc.name : Want.SetParam_char_array + * @tc.desc : big char array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_26900 + * @tc.name : Want.SetParam_char_array + * @tc.desc : different char array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_26900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_26900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27000 + * @tc.name : Want.SetParam_char_array + * @tc.desc : different char array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27100 + * @tc.name : Want.SetParam_char_array + * @tc.desc : pressure char array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_char_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27200 + * @tc.name : Want.SetParam_int + * @tc.desc : max int + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27300 + * @tc.name : Want.SetParam_int + * @tc.desc : min int + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27400 + * @tc.name : Want.SetParam_int + * @tc.desc : different int value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27500 + * @tc.name : Want.SetParam_int + * @tc.desc : different int value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27600 + * @tc.name : Want.SetParam_int + * @tc.desc : pressure int + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27700 + * @tc.name : Want.SetParam_int_array + * @tc.desc : empty int array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27800 + * @tc.name : Want.SetParam_int_array + * @tc.desc : big int array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_27900 + * @tc.name : Want.SetParam_int_array + * @tc.desc : different int array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_27900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_27900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28000 + * @tc.name : Want.SetParam_int_array + * @tc.desc : different int array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28100 + * @tc.name : Want.SetParam_int_array + * @tc.desc : pressure byte array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_int_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28200 + * @tc.name : Want.SetParam_double + * @tc.desc : max double + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28300 + * @tc.name : Want.SetParam_double + * @tc.desc : min double + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28400 + * @tc.name : Want.SetParam_double + * @tc.desc : different double value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28500 + * @tc.name : Want.SetParam_double + * @tc.desc : different double value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28600 + * @tc.name : Want.SetParam_double + * @tc.desc : pressure double + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28700 + * @tc.name : Want.SetParam_double_array + * @tc.desc : empty double array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28800 + * @tc.name : Want.SetParam_double_array + * @tc.desc : big double array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_28900 + * @tc.name : Want.SetParam_double_array + * @tc.desc : different double array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_28900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_28900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29000 + * @tc.name : Want.SetParam_double_array + * @tc.desc : different double array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29100 + * @tc.name : Want.SetParam_double_array + * @tc.desc : pressure double array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_double_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29200 + * @tc.name : Want.SetParam_float + * @tc.desc : max float + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29300 + * @tc.name : Want.SetParam_float + * @tc.desc : min float + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29400 + * @tc.name : Want.SetParam_float + * @tc.desc : different float value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29500 + * @tc.name : Want.SetParam_float + * @tc.desc : different float value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29600 + * @tc.name : Want.SetParam_float + * @tc.desc : pressure float + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29700 + * @tc.name : Want.SetParam_float_array + * @tc.desc : empty float array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29800 + * @tc.name : Want.SetParam_float_array + * @tc.desc : big float array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_29900 + * @tc.name : Want.SetParam_float_array + * @tc.desc : different float array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_29900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_29900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30000 + * @tc.name : Want.SetParam_float_array + * @tc.desc : different float array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30100 + * @tc.name : Want.SetParam_float_array + * @tc.desc : pressure float array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_float_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30200 + * @tc.name : Want.SetParam_long + * @tc.desc : max long + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30300 + * @tc.name : Want.SetParam_long + * @tc.desc : min long + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30400 + * @tc.name : Want.SetParam_long + * @tc.desc : different long value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30500 + * @tc.name : Want.SetParam_long + * @tc.desc : different long value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30600 + * @tc.name : Want.SetParam_long + * @tc.desc : pressure long + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30700 + * @tc.name : Want.SetParam_long_array + * @tc.desc : empty long array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30800 + * @tc.name : Want.SetParam_long_array + * @tc.desc : big long array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_30900 + * @tc.name : Want.SetParam_long_array + * @tc.desc : different long array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_30900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_30900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31000 + * @tc.name : Want.SetParam_long_array + * @tc.desc : different long array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31100 + * @tc.name : Want.SetParam_long_array + * @tc.desc : pressure long array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_long_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31200 + * @tc.name : Want.SetParam_short + * @tc.desc : max short + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31300 + * @tc.name : Want.SetParam_short + * @tc.desc : min short + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31400 + * @tc.name : Want.SetParam_short + * @tc.desc : different short value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31500 + * @tc.name : Want.SetParam_short + * @tc.desc : different short value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31600 + * @tc.name : Want.SetParam_short + * @tc.desc : pressure short + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31700 + * @tc.name : Want.SetParam_short_array + * @tc.desc : empty short array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31800 + * @tc.name : Want.SetParam_short_array + * @tc.desc : big short array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_31900 + * @tc.name : Want.SetParam_short_array + * @tc.desc : different short array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_31900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_31900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32000 + * @tc.name : Want.SetParam_short_array + * @tc.desc : different short array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32100 + * @tc.name : Want.SetParam_short_array + * @tc.desc : pressure short array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_short_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32200 + * @tc.name : Want.SetParam_string + * @tc.desc : empty string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32300 + * @tc.name : Want.SetParam_string + * @tc.desc : long string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32400 + * @tc.name : Want.SetParam_string + * @tc.desc : different string value set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32500 + * @tc.name : Want.SetParam_string + * @tc.desc : different string value set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32600 + * @tc.name : Want.SetParam_string + * @tc.desc : pressure string + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32700 + * @tc.name : Want.SetParam_string_array + * @tc.desc : empty string array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string_array) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32800 + * @tc.name : Want.SetParam_string_array + * @tc.desc : big string array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string_array) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_32900 + * @tc.name : Want.SetParam_string_array + * @tc.desc : different string array set on one key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_32900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string_array) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_32900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33000 + * @tc.name : Want.SetParam_string_array + * @tc.desc : different string array set on different key + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string_array) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33100 + * @tc.name : Want.SetParam_string_array + * @tc.desc : pressure string array + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::SetParam_string_array) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33200 + * @tc.name : Want.HasParameter + * @tc.desc : empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasParameter) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33300 + * @tc.name : Want.HasParameter + * @tc.desc : parameter not exists + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasParameter) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33400 + * @tc.name : Want.HasParameter + * @tc.desc : parameter exits + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasParameter) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33500 + * @tc.name : Want.HasParameter + * @tc.desc : after remove parameter + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasParameter) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33600 + * @tc.name : Want.HasParameter + * @tc.desc : whether exists parameter repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::HasParameter) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33700 + * @tc.name : Want.ReplaceParams_WantParams + * @tc.desc : replace params on empty Want by empty WantParams + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_WantParams) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33800 + * @tc.name : Want.ReplaceParams_WantParams + * @tc.desc : set param and then replace it by empty WantParams + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_WantParams) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_33900 + * @tc.name : Want.ReplaceParams_WantParams + * @tc.desc : replace params on empty Want by not empty WantParams + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_33900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_WantParams) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_33900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34000 + * @tc.name : Want.ReplaceParams_WantParams + * @tc.desc : replace params twice by different WantParams + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_WantParams) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34100 + * @tc.name : Want.ReplaceParams_WantParams + * @tc.desc : replace params repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_WantParams) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34200 + * @tc.name : Want.ReplaceParams_Want + * @tc.desc : replace params on empty Want by another empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_Want) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34300 + * @tc.name : Want.ReplaceParams_Want + * @tc.desc : replace params on empty Want by another not empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_Want) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34400 + * @tc.name : Want.ReplaceParams_Want + * @tc.desc : replace params by another empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_Want) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34500 + * @tc.name : Want.ReplaceParams_Want + * @tc.desc : replace params by another Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_Want) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34600 + * @tc.name : Want.ReplaceParams_Want + * @tc.desc : replace params repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ReplaceParams_Want) + "_4"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34700 + * @tc.name : Want.RemoveParam + * @tc.desc : remove param from empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveParam) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34800 + * @tc.name : Want.RemoveParam + * @tc.desc : remove existed param + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveParam) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_34900 + * @tc.name : Want.RemoveParam + * @tc.desc : set and remove param repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_34900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::RemoveParam) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_34900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35000 + * @tc.name : Want.GetOperation + * @tc.desc : get operation from empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetOperation) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35100 + * @tc.name : Want.GetOperation + * @tc.desc : set and get operation + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetOperation) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35200 + * @tc.name : Want.GetOperation + * @tc.desc : get operation repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::GetOperation) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35300 + * @tc.name : Want.OperationEquals + * @tc.desc : compare empty Want operation + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::OperationEquals) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35400 + * @tc.name : Want.OperationEquals + * @tc.desc : compare Want operation not equal + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::OperationEquals) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35500 + * @tc.name : Want.OperationEquals + * @tc.desc : compare Want operation equal + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::OperationEquals) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35600 + * @tc.name : Want.OperationEquals + * @tc.desc : compare Want operation repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::OperationEquals) + "_3"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35700 + * @tc.name : Want.CloneOperation + * @tc.desc : clone operation on empty Want + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::CloneOperation) + "_0"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35700 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35800 + * @tc.name : Want.CloneOperation + * @tc.desc : clone not empty operation + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35800, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::CloneOperation) + "_1"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35800 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_35900 + * @tc.name : Want.CloneOperation + * @tc.desc : clone operation repeatedly + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_35900, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::CloneOperation) + "_2"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_35900 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36000 + * @tc.name : Want.ParseUri + * @tc.desc : parse boolean parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36000, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_15"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36000 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36100 + * @tc.name : Want.ParseUri + * @tc.desc : parse char parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36100, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_16"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36100 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36200 + * @tc.name : Want.ParseUri + * @tc.desc : parse byte parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36200, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_17"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36200 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36300 + * @tc.name : Want.ParseUri + * @tc.desc : parse short parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36300, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_18"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36300 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36400 + * @tc.name : Want.ParseUri + * @tc.desc : parse short parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36400, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_19"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36400 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36500 + * @tc.name : Want.ParseUri + * @tc.desc : parse short parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36500, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_20"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36500 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36600 + * @tc.name : Want.ParseUri + * @tc.desc : parse short parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36600, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_21"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36600 : " << i; + break; + } + } +} + +/** + * @tc.number : AMS_Page_Want_36700 + * @tc.name : Want.ParseUri + * @tc.desc : parse short parameters + */ +HWTEST_F(ActsAmsKitWantTest, AMS_Page_Want_36700, Function | MediumTest | Level1) +{ + StartSecondAbility(); + std::string data = "Want_" + std::to_string((int)WantApi::ParseUri) + "_22"; + bool result = false; + for (int i = 1; i <= stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_SECOND, ++amsKitSystemTestSecondAbilityCode, data); + EXPECT_EQ( + 0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode, delay)); + std::string respData = STAbilityUtil::GetData(event, g_EVENT_RESP_SECOND, amsKitSystemTestSecondAbilityCode); + result = respData.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 1) { + GTEST_LOG_(INFO) << "AMS_Page_Want_36700 : " << i; + break; + } + } +} diff --git a/test/systemtest/common/ams/ams_missionstack_test/BUILD.gn b/test/systemtest/common/ams/ams_missionstack_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2ce59a4578cfa6809d535d3646e1226204d3969f --- /dev/null +++ b/test/systemtest/common/ams/ams_missionstack_test/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_missionstack_test") { + module_out_path = module_output_path + + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_missionstack_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_missionstack_test" ] +} diff --git a/test/systemtest/common/ams/ams_missionstack_test/ams_missionstack_test.cpp b/test/systemtest/common/ams/ams_missionstack_test/ams_missionstack_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a552fa0a0df345c19f851e501068490aa67be428 --- /dev/null +++ b/test/systemtest/common/ams/ams_missionstack_test/ams_missionstack_test.cpp @@ -0,0 +1,674 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_append_test_info.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "hilog_wrapper.h" +#include "stoperator.h" +#include "st_ability_util.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; + +using MAP_STR_STR = std::map; +namespace { +static const string KIT_BUNDLE_NAME = "com.ohos.amsst.MissionStack"; +static const string KIT_HAP_NAME = "amsMissionStackTest"; +static const string KIT_BUNDLE_NAME_SUBSIDIARY = "com.ohos.amsst.MissionStackSubsidiary"; +static const string KIT_HAP_NAME_SUBSIDIARY = "amsMissionStackTestSubsidiary"; +static const string MAIN_ABILITY_NAME = "MainAbility"; +static const string SECOND_ABILITY_NAME = "SecondAbility"; +static const string THIRD_ABILITY_NAME = "ThirdAbility"; +static constexpr int WAIT_TIME = 1; +static constexpr int WAIT_LAUNCHER_TIME = 9; +static const std::string LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility"; +static const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher"; +} + +static string g_eventMessage = ""; +class AmsMissionStackTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static void Reinstall(const std::string &hapName, const std::string &bundleName); + void ResetSystem() const; + static bool SubscribeEvent(); + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber(){}; + }; + + static sptr abilityMgrService; + static Event event; +}; + +Event AmsMissionStackTest::event = Event(); +sptr AmsMissionStackTest::abilityMgrService = nullptr; + +void AmsMissionStackTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + if (data.GetWant().GetAction() == g_EVENT_RESP_MAIN_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_THIRD_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY + ) { + TestCompleted(event, data.GetData(), data.GetCode()); + } else if (data.GetWant().GetAction() == g_EVENT_RESP_MAIN || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND || + data.GetWant().GetAction() == g_EVENT_RESP_THIRD || + data.GetWant().GetAction() == g_EVENT_RESP_MAIN_SUBSIDIARY || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_SUBSIDIARY + ) { + g_eventMessage = data.GetData(); + TestCompleted(event, data.GetWant().GetAction(), data.GetCode()); + GTEST_LOG_(INFO) << "OnReceiveEvent: g_eventMessage=" << data.GetData(); + } +} + +int AmsMissionStackTest::TestWaitCompleted( + Event &event, const std::string &eventName, const int code, const int timeout) +{ + GTEST_LOG_(INFO) << "TestWaitCompleted : " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} + +void AmsMissionStackTest::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + GTEST_LOG_(INFO) << "TestCompleted : " << eventName << " " << code; + return STAbilityUtil::Completed(event, eventName, code); +} + +void AmsMissionStackTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void AmsMissionStackTest::TearDownTestCase(void) +{} + +static int CODE_ = 0; +void AmsMissionStackTest::SetUp(void) +{ + STAbilityUtil::Install(KIT_HAP_NAME); + STAbilityUtil::CleanMsg(event); + CODE_++; + sleep(WAIT_LAUNCHER_TIME); +} + +void AmsMissionStackTest::TearDown(void) +{ + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME); + STAbilityUtil::CleanMsg(event); +} + +bool AmsMissionStackTest::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_RESP_MAIN_LIFECYCLE, + g_EVENT_RESP_SECOND_LIFECYCLE, + g_EVENT_RESP_THIRD_LIFECYCLE, + g_EVENT_RESP_MAIN, + g_EVENT_RESP_SECOND, + g_EVENT_RESP_THIRD, + + g_EVENT_RESP_MAIN_SUBSIDIARY, + g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, + + g_EVENT_RESP_SECOND_SUBSIDIARY, + g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsMissionStackTest::Reinstall(const std::string &hapName, const std::string &bundleName) +{ + STAbilityUtil::Uninstall(bundleName); + STAbilityUtil::Install(hapName); +} + + +/** + * @tc.number : ACTS_FWK_MissionStack_0100 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, "OnStop", SECOND_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0100 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0200 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_NE(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0200 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0300 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + Want wantEntity; + wantEntity.SetElementName(LAUNCHER_BUNDLE_NAME, LAUNCHER_ABILITY_NAME); + STAbilityUtil::StartAbility(wantEntity, abilityMgrService); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_NE(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0300 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0400 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start third ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", THIRD_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", THIRD_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_THIRD, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_4"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_THIRD, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_NE(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0400 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0500 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start third ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_5"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_NE(TestWaitCompleted(event, "OnStart", THIRD_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0500 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0600 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_6"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + Want wantEntity; + wantEntity.SetElementName(LAUNCHER_BUNDLE_NAME, LAUNCHER_ABILITY_NAME); + STAbilityUtil::StartAbility(wantEntity, abilityMgrService); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0600 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0700 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_8"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_8"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnStop", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0700 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0800 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_9"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << "id=" << appInfo; + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0800 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_0900 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_0900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_11"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_0900 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_1000 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_1000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_12"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1000 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_1100 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_1100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_13"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_13"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1100 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_1200 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_1200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_14"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_14"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + EXPECT_NE(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1200 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_1300 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_1300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + Want wantEntity; + wantEntity.SetElementName(LAUNCHER_BUNDLE_NAME, LAUNCHER_ABILITY_NAME); + STAbilityUtil::StartAbility(wantEntity, abilityMgrService); + sleep(WAIT_LAUNCHER_TIME); + STAbilityUtil::CleanMsg(event); + + STAbilityUtil::Install(KIT_HAP_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + sleep(WAIT_LAUNCHER_TIME); + want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME_SUBSIDIARY, params); + // start first ability + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) <<"SUBSIDIARY:StartAbility:eCode=" << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN_SUBSIDIARY, + CODE_, + "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE_SUBSIDIARY, WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN_SUBSIDIARY, + CODE_, + "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE_SUBSIDIARY, WAIT_LAUNCHER_TIME), 0); + + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1300 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_1400 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_1400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + Want wantEntity; + wantEntity.SetElementName(LAUNCHER_BUNDLE_NAME, LAUNCHER_ABILITY_NAME); + STAbilityUtil::StartAbility(wantEntity, abilityMgrService); + sleep(WAIT_LAUNCHER_TIME); + STAbilityUtil::CleanMsg(event); + + STAbilityUtil::Install(KIT_HAP_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + sleep(WAIT_LAUNCHER_TIME); + want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME_SUBSIDIARY, params); + // start first ability + eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) <<"SUBSIDIARY:StartAbility:eCode=" << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN_SUBSIDIARY, CODE_, + "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE_SUBSIDIARY, WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent(g_EVENT_REQU_MAIN_SUBSIDIARY, CODE_, + "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE_SUBSIDIARY, WAIT_LAUNCHER_TIME), 0); + + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1400 end"; +} + +/** + * @tc.number : ACTS_FWK_MissionStack_1500 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, ACTS_FWK_MissionStack_1500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMgrService, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_17"); + sleep(WAIT_LAUNCHER_TIME); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + EXPECT_NE(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest ACTS_FWK_MissionStack_1500 end"; +} +} // namespace diff --git a/test/systemtest/common/ams/ams_page_ability_test/BUILD.gn b/test/systemtest/common/ams/ams_page_ability_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..2f6b611aca315360d093b26265ed80e9e527ab0a --- /dev/null +++ b/test/systemtest/common/ams/ams_page_ability_test/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_page_ability_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_page_ability_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_page_ability_test" ] +} diff --git a/test/systemtest/common/ams/ams_page_ability_test/ams_page_ability_test.cpp b/test/systemtest/common/ams/ams_page_ability_test/ams_page_ability_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00988b712d761befd296cd70c6be05077387eafc --- /dev/null +++ b/test/systemtest/common/ams/ams_page_ability_test/ams_page_ability_test.cpp @@ -0,0 +1,3678 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "app_mgr_service.h" +#include "ability_lifecycle_executor.h" +#include "ability_lifecycle.h" +#include "hilog_wrapper.h" +#include + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using namespace OHOS::EventFwk; + +typedef std::map MAP_STR_STR; +enum AbilityState_Test { + INITIAL = 0, + INACTIVE, + ACTIVE, + BACKGROUND, + SUSPENDED, + INACTIVATING, + ACTIVATING, + MOVING_BACKGROUND, + TERMINATING, + ALLSUM, +}; +namespace { +std::vector bundleNameSuffix = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "M", "N", "O", "P"}; +std::vector uninstallBundleNameSuffix = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "M", "N", "O"}; +static const std::string bundleNameBase = "com.ohos.amsst.app"; +static const std::string abilityNameBase = "AmsStAbility"; +static const std::string hapNameBase = "amsSystemTest"; +static const std::string launcherAbilityName = "com.ohos.launcher.MainAbility"; +static const std::string launcherBundleName = "com.ohos.launcher"; +static const std::string systemUiBundle = "com.ohos.systemui"; +static const std::string terminatePageAbility = "requ_page_ability_terminate"; +static const std::string abilityEventName = "resp_st_page_ability_callback"; +static const std::string pidEventName = "resp_st_page_ability_pid_callback"; +static const int amsStAbilityO1Code = 10; +static const int amsStAbilityP1Code = 11; +static constexpr int WAIT_TIME = 3 * 1000; +static constexpr int WAIT_LAUNCHER_OK = 5 * 1000; +static const std::string DUMP_STACK_LIST = "--stack-list"; +static const std::string DUMP_STACK = "--stack"; +static const std::string DUMP_MISSION = "--mission"; +static const std::string DUMP_TOP = "--top"; +static const std::string DUMP_ALL = "-a"; +static const std::string lifecycleStateUninitialized = + std::to_string(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED); +static const std::string lifecycleStateActive = std::to_string(AbilityLifecycleExecutor::LifecycleState::ACTIVE); +static const std::string lifecycleStateBackground = + std::to_string(AbilityLifecycleExecutor::LifecycleState::BACKGROUND); +static const std::string lifecycleStateInactive = std::to_string(AbilityLifecycleExecutor::LifecycleState::INACTIVE); +static const std::string lifecycleStateInitial = std::to_string(AbilityLifecycleExecutor::LifecycleState::INITIAL); +static const std::vector abilityStateVec = { + "INITIAL", + "INACTIVE", + "ACTIVE", + "BACKGROUND", + "SUSPENDED", + "INACTIVATING", + "ACTIVATING", + "MOVING_BACKGROUND", + "TERMINATING", +}; +static const std::string abilityStateOnStart = ":OnStart"; +static const std::string abilityStateOnStop = ":OnStop"; +static const std::string abilityStateOnActive = ":OnActive"; +static const std::string abilityStateOnInactive = ":OnInactive"; +static const std::string abilityStateOnBackground = ":OnBackground"; +static const std::string abilityStateOnForeground = ":OnForeground"; +static const std::string abilityStateOnNewWant = ":OnNewWant"; +static const int abilityStateCountOne = 1; +static const int abilityStateCountTwo = 2; +static const int FreezingTime = 60; +} // namespace + +class AmsPageAbilityTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static std::vector GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs); + static void CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState); + void ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, + const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = DUMP_ALL); + void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum); + void ClearSystem(); + void ShowDump(); + static bool SubscribeEvent(); + static void GetAllStackInfo(MissionStackInfo &missionStackInfo); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + {} + virtual ~AppEventSubscriber() + {} + virtual void OnReceiveEvent(const CommonEventData &data) override; + }; + static sptr abilityMs_; + static sptr appMs_; + static STtools::Event event_; + static STtools::Event processInfoEvent_; +}; + +STtools::Event AmsPageAbilityTest::event_ = STtools::Event(); +STtools::Event AmsPageAbilityTest::processInfoEvent_ = STtools::Event(); +sptr AmsPageAbilityTest::abilityMs_ = nullptr; +sptr AmsPageAbilityTest::appMs_ = nullptr; + +void AmsPageAbilityTest::ShowDump() +{ + std::vector dumpInfo; + abilityMs_->DumpState("-a", dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } +} + +void AmsPageAbilityTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest::SetUpTestCase(void)"; + std::vector hapNames = GetBundleNames(hapNameBase, bundleNameSuffix); + STAbilityUtil::InstallHaps(hapNames); + SubscribeEvent(); + appMs_ = STAbilityUtil::GetAppMgrService(); + abilityMs_ = STAbilityUtil::GetAbilityManagerService(); + if (appMs_) { + appMs_->SetAppFreezingTime(FreezingTime); + int time = 0; + appMs_->GetAppFreezingTime(time); + std::cout << "appMs_->GetAppFreezingTime();" << time << std::endl; + } +} + +void AmsPageAbilityTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest::TearDownTestCase(void)"; + std::vector bundleNames = GetBundleNames(bundleNameBase, uninstallBundleNameSuffix); + STAbilityUtil::UninstallBundle(bundleNames); +} + +void AmsPageAbilityTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest::SetUp(void)"; +} + +void AmsPageAbilityTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "void AmsPageAbilityTest::TearDown(void)"; + STAbilityUtil::RemoveStack(1, abilityMs_, WAIT_TIME, WAIT_LAUNCHER_OK); + std::vector vecBundleName; + for (const auto &suffix : bundleNameSuffix) { + vecBundleName.push_back(bundleNameBase + suffix); + } + STAbilityUtil::KillBundleProcess(vecBundleName); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::CleanMsg(processInfoEvent_); +} + +std::vector AmsPageAbilityTest::GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs) +{ + std::vector bundleNames; + for (auto strSuffix : strSuffixs) { + bundleNames.push_back(strBase + strSuffix); + } + return bundleNames; +} + +void AmsPageAbilityTest::CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState) +{ + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", info, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + // ability exist + EXPECT_NE(pos, result.end()); + MTDumpUtil::GetInstance()->GetAll("State", info, result); + EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } + // ability state + if (midState != "") { + bool compareResult = ((*pos == state) || (*pos == midState)); + EXPECT_EQ(1, compareResult); + } else { + EXPECT_EQ(*pos, state); + } +} + +void AmsPageAbilityTest::ExpectAbilityCurrentState(const std::string &abilityName, + const AbilityState_Test ¤tState, const AbilityState_Test &midState, const std::string &args) +{ + std::string strCurrentState = abilityStateVec.at(currentState); + std::string strMidState = ""; + if (midState != AbilityState_Test::ALLSUM) { + strMidState = abilityStateVec.at(midState); + } + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(args, dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, strCurrentState, strMidState); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsPageAbilityTest::ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(DUMP_STACK + " 1", dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsPageAbilityTest::ClearSystem() +{ + STAbilityUtil::KillService("appspawn"); + STAbilityUtil::KillService("installs"); + STAbilityUtil::KillService(launcherBundleName); + STAbilityUtil::KillService(systemUiBundle); + STAbilityUtil::KillService("foundation"); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LAUNCHER_OK)); +} + +bool AmsPageAbilityTest::SubscribeEvent() +{ + std::vector eventList = { + abilityEventName, + pidEventName, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsPageAbilityTest::GetAllStackInfo(MissionStackInfo &missionStackInfo) +{ + StackInfo stackInfo; + abilityMs_->GetAllStackInfo(stackInfo); + for (const auto &stackInfo : stackInfo.missionStackInfos) { + if (stackInfo.id == 1) { + missionStackInfo = stackInfo; + break; + } + } +} + +void AmsPageAbilityTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + std::string eventName = data.GetWant().GetAction(); + if (eventName == abilityEventName) { + std::string target = data.GetData(); + STAbilityUtil::Completed(event_, target, data.GetCode()); + } + if (eventName == pidEventName) { + STAbilityUtil::Completed(processInfoEvent_, eventName, data.GetCode(), data.GetData()); + } +} + +/* + * @tc.number : AMS_Page_Ability_0100 + * @tc.name : start a page ability with launchtype singletop,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0100 start"; + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0200 + * @tc.name : start a page ability twice,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.start page ability again + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0200 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + // only one record in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0200 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0300 + * @tc.name : start different page ability in the same app sequencely,launchtype[A1,A2:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.start a page ability A2 + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0300 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in the same app + std::string bundleName2 = bundleNameBase + "A"; + std::string abilityName2 = abilityNameBase + "A2"; + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "A1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "A2" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "A2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0300 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0400 + * @tc.name : start different page ability in different app sequencely,launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.start a page ability B1 + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0400 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in another app + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "A1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "B1" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "B1" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0400 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0500 + * @tc.name : start page ability by another ability in the same app,launchtype[A1,A2:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start a page ability A2 by A1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0500 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string abilityName2 = abilityNameBase + "A2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "A2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0500 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0600 + * @tc.name : start page ability by itself,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start itself by A1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0600 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnNewWant, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + // only one record in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0600 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0700 + * @tc.name : start page ability by another ability in different app,launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start a page ability B1 by A1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0700 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "B1" state ACTIVE + ExpectAbilityCurrentState(abilityNameBase + "B1", AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0700 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0800 + * @tc.name : verify mission stack management,launchtype[C1,C2,C3:singletop] + * @tc.desc : 1.start page ability C1,C2,C3,C2 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0800 start"; + + std::string bundleName = bundleNameBase + "C"; + std::string abilityName = abilityNameBase + "C1"; + std::string abilityName2 = abilityNameBase + "C2"; + std::string abilityName3 = abilityNameBase + "C3"; + std::string abilityName4 = abilityNameBase + "C2"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName, params); + STAbilityUtil::StartAbility(want3, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + Want want4 = STAbilityUtil::MakeWant("device", abilityName4, bundleName, params); + STAbilityUtil::StartAbility(want4, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName4 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + std::vector dumpInfo; + abilityMs_->DumpState(DUMP_STACK + " 1", dumpInfo); + + std::vector result; + // bundle name from top to bottom + MTDumpUtil::GetInstance()->GetAll("BundleName", dumpInfo, result); + std::vector expectedResult = { + bundleNameBase + "C", + bundleNameBase + "C", + bundleNameBase + "C", + bundleNameBase + "C", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // ability name from top to bottom + expectedResult = { + abilityNameBase + "C2", + abilityNameBase + "C3", + abilityNameBase + "C2", + abilityNameBase + "C1", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0800 end"; +} + +/* + * @tc.number : AMS_Page_Ability_0900 + * @tc.name : verify mission stack management(multiple apps),launchtype[C1,C2,B1:singletop] + * @tc.desc : 1.start page ability C1,C2,B1,C2,B1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_0900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0900 start"; + + std::string bundleName = bundleNameBase + "C"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName = abilityNameBase + "C1"; + std::string abilityName2 = abilityNameBase + "C2"; + std::string abilityName3 = abilityNameBase + "B1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName2, params); + STAbilityUtil::StartAbility(want3, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want3, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + std::vector dumpInfo; + abilityMs_->DumpState(DUMP_STACK + " 1", dumpInfo); + + std::vector result; + // bundle name from top to bottom + MTDumpUtil::GetInstance()->GetAll("BundleName", dumpInfo, result); + std::vector expectedResult = { + bundleNameBase + "B", + bundleNameBase + "C", + bundleNameBase + "B", + bundleNameBase + "C", + bundleNameBase + "C", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // ability name from top to bottom + expectedResult = { + abilityNameBase + "B1", + abilityNameBase + "C2", + abilityNameBase + "B1", + abilityNameBase + "C2", + abilityNameBase + "C1", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_0900 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1000 + * @tc.name : verify mission stack management(multiple apps + ENTITY_HOME),launchtype[C1,C2,B1:singletop] + * @tc.desc : 1.start page ability C1,C2,ENTITY_HOME,B1,C2,B1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1000 start"; + + std::string bundleName = bundleNameBase + "C"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName = abilityNameBase + "C1"; + std::string abilityName2 = abilityNameBase + "C2"; + std::string abilityName3 = abilityNameBase + "B1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName2, params); + STAbilityUtil::StartAbility(want3, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want3, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 2); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + // ability in mission #2 from top to bottom + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[2].mainName.compare(abilityName3)); + // ability in mission #1 from top to bottom + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1000 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1100 + * @tc.name : ability state transition to background when Home event,launchtype[A1:singletop] + * @tc.desc : 1.start page ability A1,ENTITY_HOME in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1100 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1200 + * @tc.name : last ability state transition to foreground when stopping top ability + * (same app),launchtype[A1,A2:singletop] + * @tc.desc : 1.start page ability A1,A2 in turn + * 2.stop ability A2 + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1200 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in the same app + std::string bundleName2 = bundleNameBase + "A"; + std::string abilityName2 = abilityNameBase + "A2"; + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "A1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "A2" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "A2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + STAbilityUtil::StopAbility(terminatePageAbility, 0, abilityName2); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + // ability "A1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "A2" not in stack + ExpectAbilityNumInStack(abilityName2, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1200 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1300 + * @tc.name : last ability state transition to foreground when stopping top ability + * (different app),launchtype[A1,B1:singletop] + * @tc.desc : 1.start page ability A1,B1 in turn + * 2.stop ability B1 + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1300 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in another app + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "A1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "B1" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "B1" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + STAbilityUtil::StopAbility(terminatePageAbility, 0, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "A1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "B1" not in stack + ExpectAbilityNumInStack(abilityName2, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1300 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1400 + * @tc.name : ability state transition to foreground when background app restart,launchtype[A1:singletop] + * @tc.desc : 1.start page ability A1,ENTITY_HOME,A1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1400 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + // background app restart + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + // ability "A1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1400 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1500 + * @tc.name : start page ability for the first time when system ready,launchtype[D1:singleton] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1500 start"; + + std::string bundleName = bundleNameBase + "D"; + std::string abilityName = abilityNameBase + "D1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1500 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1600 + * @tc.name : start page ability twice,launchtype[D1:singleton] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.start page ability again + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1600 start"; + + std::string bundleName = bundleNameBase + "D"; + std::string abilityName = abilityNameBase + "D1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnNewWant, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1600 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1700 + * @tc.name : start different page ability in the same app sequencely,launchtype[D1,D2:singleton] + * @tc.desc : 1.start a page ability D1 + * 2.wait for the event sent by the page ability + * 3.start a page ability D2 + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1700 start"; + + std::string bundleName = bundleNameBase + "D"; + std::string abilityName = abilityNameBase + "D1"; + std::string abilityName2 = abilityNameBase + "D2"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1700 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1800 + * @tc.name : start different page ability in different app sequencely,launchtype[D1,E1:singleton] + * @tc.desc : 1.start a page ability D1 + * 2.wait for the event sent by the page ability + * 3.start a page ability E1 + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1800 start"; + + std::string bundleName = bundleNameBase + "D"; + std::string abilityName = abilityNameBase + "D1"; + std::string bundleName2 = bundleNameBase + "E"; + std::string abilityName2 = abilityNameBase + "E1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + // start ability in another app + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1800 end"; +} + +/* + * @tc.number : AMS_Page_Ability_1900 + * @tc.name : start page ability by another ability in the same app,launchtype[D1,D2:singleton] + * @tc.desc : 1.start a page ability D1 + * 2.start a page ability D2 by D1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_1900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1900 start"; + + std::string bundleName = bundleNameBase + "D"; + std::string abilityName = abilityNameBase + "D1"; + std::string abilityName2 = abilityNameBase + "D2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_1900 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2000 + * @tc.name : start page ability by itself,launchtype[D1:singleton] + * @tc.desc : 1.start a page ability D1 + * 2.start itself by D1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2000 start"; + + std::string bundleName = bundleNameBase + "D"; + std::string abilityName = abilityNameBase + "D1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2000 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2100 + * @tc.name : start page ability by another ability in different app,launchtype[D1,E1:singleton] + * @tc.desc : 1.start a page ability D1 + * 2.start a page ability E1 by D1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2100 start"; + + std::string bundleName = bundleNameBase + "D"; + std::string abilityName = abilityNameBase + "D1"; + std::string bundleName2 = bundleNameBase + "E"; + std::string abilityName2 = abilityNameBase + "E1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2200 + * @tc.name : terminate page ability by ability itself(one ability),launchtype[A1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.terminate a page ability A1 by A1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2200 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "A1" not in stack(terminated) + ExpectAbilityNumInStack(abilityName, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2200 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2300 + * @tc.name : terminate page ability by ability itself(same app),launchtype[A1,A2:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start a page ability A2 by A1 onActive function. + * 3.terminate a page ability A2 by A2 onActive function. + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2300 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string abilityName2 = abilityNameBase + "A2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "A1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "A2" not in stack(terminated) + ExpectAbilityNumInStack(abilityName2, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2300 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2400 + * @tc.name : terminate page ability by ability itself(multiple app),launchtype[A1,B1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start a page ability B1 by A1 onActive function. + * 3.terminate a page ability B1 by B1 onActive function. + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2400 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "A1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "B1" not in stack(terminated) + ExpectAbilityNumInStack(abilityName2, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2400 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2500 + * @tc.name : terminate previous ability of current ability,launchtype[A1,A2:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.start a page ability A2 by A1 onActive function. + * 3.terminate a page ability A1 by A1 onActive function. + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2500 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string abilityName2 = abilityNameBase + "A2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "A1" not in stack(terminated) + ExpectAbilityNumInStack(abilityName, 0); + // ability "A2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2500 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2600 + * @tc.name : verify mission stack management(singletop(top) + SI),launchtype[I1,I2,I4:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1,I2,I3,I4 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2600 start"; + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string abilityName4 = abilityNameBase + "I4"; + MAP_STR_STR params; + // Start Ability I1(singletop) + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I4(singletop) + want = STAbilityUtil::MakeWant("device", abilityName4, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName4 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName4 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + std::vector dumpInfo; + abilityMs_->DumpState((DUMP_STACK + " 1"), dumpInfo); + std::vector result; + + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + std::vector expectedResult = {abilityName4, abilityName2, abilityName1, abilityName3}; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 2); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + // ability in mission from top to bottom + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName4)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[2].mainName.compare(abilityName1)); + // ability in mission from top to bottom + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2600 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2700 + * @tc.name : after ability back, the status of other page abilities is displayed + * (singletop back),launchtype[I1,I2,I4:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1,I2,I3,I4 in turn + * 2.page ability I4 back,dump other abilities state + * 3.page ability I2 back,dump other abilities state + * 4.page ability I1 back,dump other abilities state + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2700 start"; + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string abilityName4 = abilityNameBase + "I4"; + MAP_STR_STR params; + // Start Ability I1(singletop) + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I4(singletop) + want = STAbilityUtil::MakeWant("device", abilityName4, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName4 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Back Ability I4(singletop) + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName4); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName4 + abilityStateOnStop, abilityStateCountOne), 0); + + // Ability I4 back ,Expect that the current Ability I2 is active + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::BACKGROUND, AbilityState_Test::ACTIVATING); + // Back Ability I2(singletop) + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + // Ability I2 back ,Expect that the current Ability I1 is active + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // Back Ability I1(singletop) + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(launcherAbilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2700 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2800 + * @tc.name : verify mission stack management(singletop + singleton),launchtype[I1,I2,B1:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1,I2,I3,B1,I3 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2800 start"; + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName5 = abilityNameBase + "B1"; + // Start Ability I1(singletop) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability B1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I3(SI) Again + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + std::vector dumpInfo; + abilityMs_->DumpState((DUMP_STACK + " 1"), dumpInfo); + std::vector result; + // Get all AbilityNames in the stack + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + std::vector expectedResult = {abilityName3, abilityName5, abilityName2, abilityName1}; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 3); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + // ability in mission from top to bottom + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + // ability in mission from top to bottom + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName5)); + + // ability in mission from top to bottom + abilityInfos = missionStackInfo.missionRecords[2].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName1)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2800 end"; +} + +/* + * @tc.number : AMS_Page_Ability_2900 + * @tc.name : after ability back, the status of other page abilities is displayed + * (singleton back),launchtype[I1,I2,B1:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1,I2,I3,B1,I3 in turn + * 2.ability I3 back + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2900 start"; + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName5 = abilityNameBase + "B1"; + // Start Ability I1(singletop) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability B1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I3(SI) Again + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // Start Ability I3(SI) Back + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); + + // Ability I3 back ,Expect that the current Ability B1 is active + ExpectAbilityCurrentState(abilityName5, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_2900 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3000 + * @tc.name : verify mission stack management,After starting singletop singleton and + * ENTITY_HOME,launchtype[I1,I2,B1:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1,I2,I3,ENTITY_HOME,B1,I3 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3000 start"; + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName5 = abilityNameBase + "B1"; + + // Start Ability I1(singletop) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability B1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I3 again(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 3); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + // ability in mission from top to bottom + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + + // ability in mission from top to bottom + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName5)); + + // ability in mission from top to bottom + abilityInfos = missionStackInfo.missionRecords[2].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName1)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3000 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3100 + * @tc.name : after ability back, the status of other page abilities is displayed + * (singleton back),launchtype[I1,I2,B1:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1,I2,I3,ENTITY_HOME,B1,I3 in turn + * 2.ability I3 back + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3100 start"; + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName5 = abilityNameBase + "B1"; + + // Start Ability I1(singletop) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + // Start Ability B1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + + // Start Ability I3 again(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + // I3(SI) back + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountTwo), 0); + + // Ability I3 back, B1(singletop) State Is ACTIVE + ExpectAbilityCurrentState(abilityName5, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // B1(singletop) back + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName5); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnStop, abilityStateCountOne), 0); + + // Ability B1 back ,Expect that the current launcher is active + ExpectAbilityCurrentState(launcherAbilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3200 + * @tc.name : ability state transition in the same app,launchtype[G1:singleton,G2:singletop] + * @tc.desc : 1.start page ability G1,G2 in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3200 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string abilityName2 = abilityNameBase + "G2"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + // Start Ability G2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3200 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3300 + * @tc.name : ability state transition in the different app,launchtype[G1:singleton,H1:singletop] + * @tc.desc : 1.start page ability G1,H1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3300 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string bundleName2 = bundleNameBase + "H"; + std::string abilityName2 = abilityNameBase + "H1"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + // Start Ability H1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3300 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3400 + * @tc.name : ability state transition in the different app,launchtype[G1:singleton,ENTITY_HOME] + * @tc.desc : 1.start page ability G1,ENTITY_HOME in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3400 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + // simulate ENTITY_HOME,G1 go backstage. + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3400 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3500 + * @tc.name : ability state transition in the same app,launchtype[G1:singleton,G2:singletop] + * @tc.desc : 1.start a page ability G1 + * 2.start a page ability G2 by G1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3500 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string abilityName2 = abilityNameBase + "G2"; + + // Start Ability G1(SI) + MAP_STR_STR params; + params["targetBundle"] = bundleName1; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3500 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3600 + * @tc.name : ability state transition in the different app,launchtype[G1:singleton,H1:singletop] + * @tc.desc : 1.start a page ability G1 + * 2.start a page ability H1 by G1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3600 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string bundleName2 = bundleNameBase + "H"; + std::string abilityName2 = abilityNameBase + "H1"; + + // Start Ability G1(SI) + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3600 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3700 + * @tc.name : ability state transition in the same app when ability back,launchtype[G1:singleton,G2:singletop] + * @tc.desc : 1.start page ability G1,G2 in turn + * 2.ability G2 back + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3700 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string abilityName2 = abilityNameBase + "G2"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // Start Ability G2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // Back Ability G2(singletop) + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3700 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3800 + * @tc.name : ability state transition in the different app when ability back,launchtype[G1:singleton,H1:singletop] + * @tc.desc : 1.start page ability G1,H1 in turn + * 2.ability H1 back + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3800 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string bundleName2 = bundleNameBase + "H"; + std::string abilityName2 = abilityNameBase + "H1"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // Start Ability H1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // Back Ability H1(singletop) + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + // Back Ability H1(singletop), G1(SI) Ability State Is ACTIVE + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3800 end"; +} + +/* + * @tc.number : AMS_Page_Ability_3900 + * @tc.name : ability state transition when after ability enters + * the background and start it again,launchtype[G1:singleton] + * @tc.desc : 1.start page ability G1,ENTITY_HOME,G1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3900 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + // simulate ENTITY_HOME,G1 go backstage. + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + // Start Ability G1(SI) again + want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + + ExpectAbilityNumInStack(abilityName1, 1); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_3900 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4000 + * @tc.name : the transition state when ability terminate,launchtype[G1:singleton] + * @tc.desc : 1.start page ability G1 + * 2.wait for the event sent by the page ability + * 3.terminate ability G1 + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4000 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // Terminate Ability G1(SI) + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName1, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4000 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4100 + * @tc.name : the transition state when ability terminate(the same app), + * launchtype[G1:singleton,G2:singletop] + * @tc.desc : 1.start page ability G1,G2 in turn + * 2.wait for the event sent by the page ability + * 3.terminate ability G2 + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4100 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string abilityName2 = abilityNameBase + "G2"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // Start Ability G2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // terminate Ability G2(singletop) + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4200 + * @tc.name : the transition state when ability terminate(the different app), + * launchtype[G1:singleton,H1:singletop] + * @tc.desc : 1.start page ability G1,H1 in turn + * 2.wait for the event sent by the page ability + * 3.terminate ability H1 + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4200 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string bundleName2 = bundleNameBase + "H"; + std::string abilityName2 = abilityNameBase + "H1"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // Start Ability H1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + // terminate Ability H1(singletop) + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + + // terminate Ability H1(singletop), G1(SI) Ability State Is ACTIVE + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4200 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4300 + * @tc.name : the transition state when ability terminate, + * launchtype[G1:singleton,G2:singletop] + * @tc.desc : 1.start page ability G1,G2,G2 in turn + * 2.wait for the event sent by the page ability + * 3.terminate ability G1 + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4300 start"; + std::string bundleName1 = bundleNameBase + "G"; + std::string abilityName1 = abilityNameBase + "G1"; + std::string abilityName2 = abilityNameBase + "G2"; + + // Start Ability G1(SI) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // Start Ability G2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + // Start Ability G2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnNewWant, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + // terminate Ability G1(SI) + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4300 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4400 + * @tc.name : start a page ability with launchtype standard,launchtype[N1:standard] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4400 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4400 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4500 + * @tc.name : start a page ability twice,launchtype[N1:standard] + * @tc.desc : 1.start a page ability + * 2.wait for the event sent by the page ability + * 3.start page ability again + * 4.wait for the event sent by the page ability + * 5.dump the ability info + * 6.dump the stack info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4500 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // two record in stack + ExpectAbilityNumInStack(abilityName, 2); + // ability state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4500 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4600 + * @tc.name : start different page ability in the same app sequencely,launchtype[N1,N2:standard] + * @tc.desc : 1.start a page ability N1 + * 2.wait for the event sent by the page ability + * 3.start a page ability N2 + * 4.wait for the event sent by the page ability + * 5.dump the ability info + * 6.dump the stack info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4600 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in the same app + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "N1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "N1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "N2" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "N2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4600 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4700 + * @tc.name : start different page ability in different app sequencely,launchtype[N1,M1:standard] + * @tc.desc : 1.start a page ability N1 + * 2.wait for the event sent by the page ability + * 3.start a page ability M1 + * 4.wait for the event sent by the page ability + * 5.dump the ability info + * 6.dump the stack info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4700 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName2 = abilityNameBase + "M1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in another app + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_, 5 * 1000); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "N1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "N1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "M1" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "M1" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4700 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4800 + * @tc.name : start page ability by another ability in the same app,launchtype[N1,N2:standard] + * @tc.desc : 1.start a page ability N1 + * 2.start a page ability N2 by N1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4800 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "N1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "N2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4800 end"; +} + +/* + * @tc.number : AMS_Page_Ability_4900 + * @tc.name : start page ability by itself,launchtype[N1:standard] + * @tc.desc : 1.start a page ability N1 + * 2.start itself by N1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + * 5.dump the stack info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4900 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // two record in stack + ExpectAbilityNumInStack(abilityName, 2); + // ability state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4900 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5000 + * @tc.name : start page ability by another ability in different app,launchtype[A1,M1:singletop] + * @tc.desc : 1.start a page ability N1 + * 2.start a page ability M1 by N1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5000 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName2 = abilityNameBase + "M1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "N1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "M1" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5000 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5100 + * @tc.name : verify mission stack management,launchtype[N1,N2,N4:singletop] + * @tc.desc : 1.start page ability N1,N2,N2,N4,N2 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5100 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + std::string abilityName3 = abilityNameBase + "N4"; + std::string abilityName4 = abilityNameBase + "N2"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want2, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName, params); + STAbilityUtil::StartAbility(want3, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + Want want4 = STAbilityUtil::MakeWant("device", abilityName4, bundleName, params); + STAbilityUtil::StartAbility(want4, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + std::vector dumpInfo; + abilityMs_->DumpState(DUMP_STACK + " 1", dumpInfo); + std::vector result; + // bundle name from top to bottom + MTDumpUtil::GetInstance()->GetAll("BundleName", dumpInfo, result); + std::vector expectedResult = { + bundleNameBase + "N", + bundleNameBase + "N", + bundleNameBase + "N", + bundleNameBase + "N", + bundleNameBase + "N", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // ability name from top to bottom + expectedResult = { + abilityNameBase + "N2", + abilityNameBase + "N4", + abilityNameBase + "N2", + abilityNameBase + "N2", + abilityNameBase + "N1", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5200 + * @tc.name : verify mission stack management(multiple apps),launchtype[N1,N2,M1:standard] + * @tc.desc : 1.start page ability N1,N2,M1,N2,M1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5200 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName3 = abilityNameBase + "M1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName2, params); + STAbilityUtil::StartAbility(want3, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want3, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + std::vector dumpInfo; + abilityMs_->DumpState(DUMP_STACK + " 1", dumpInfo); + + std::vector result; + // bundle name from top to bottom + MTDumpUtil::GetInstance()->GetAll("BundleName", dumpInfo, result); + std::vector expectedResult = { + bundleNameBase + "M", + bundleNameBase + "N", + bundleNameBase + "M", + bundleNameBase + "N", + bundleNameBase + "N", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // ability name from top to bottom + expectedResult = { + abilityNameBase + "M1", + abilityNameBase + "N2", + abilityNameBase + "M1", + abilityNameBase + "N2", + abilityNameBase + "N1", + }; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5200 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5300 + * @tc.name : verify mission stack management(multiple apps + ENTITY_HOME),launchtype[N1,N2,M1:standard] + * @tc.desc : 1.start page ability N1,N2,ENTITY_HOME,M1,N2,M1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5300 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + std::string bundleName3 = bundleNameBase + "M"; + std::string abilityName3 = abilityNameBase + "M1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + Want want2 = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + Want want3 = STAbilityUtil::MakeWant("device", abilityName3, bundleName3, params); + STAbilityUtil::StartAbility(want3, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want2, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + + STAbilityUtil::StartAbility(want3, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 2); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + // ability in mission #2 from top to bottom + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityNameBase + "M1")); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityNameBase + "N2")); + EXPECT_EQ(0, abilityInfos[2].mainName.compare(abilityNameBase + "M1")); + // ability in mission #1 from top to bottom + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityNameBase + "N2")); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityNameBase + "N1")); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5300 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5400 + * @tc.name : ability state transition to background when Home event,launchtype[N1:standard] + * @tc.desc : 1.start page ability N1,ENTITY_HOME in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5400 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "N1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5400 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5500 + * @tc.name : last ability state transition to foreground when stopping top ability + * (same app),launchtype[N1,N2:standard] + * @tc.desc : 1.start page ability N1,N2 in turn + * 2.stop ability N2 + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5500 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in the same app + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "N1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "N1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "N2" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "N2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + STAbilityUtil::StopAbility(terminatePageAbility, 0, abilityName2); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "N1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "N2" not in stack + ExpectAbilityNumInStack(abilityName2, 0); + ShowDump(); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5500 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5600 + * @tc.name : last ability state transition to foreground when stopping top ability + * (different app),launchtype[N1,M1:standard] + * @tc.desc : 1.start page ability N1,M1 in turn + * 2.stop ability M1 + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5600 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName2 = abilityNameBase + "M1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // start ability in another app + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "N1" in stack + ExpectAbilityNumInStack(abilityName, 1); + // ability "N1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + // ability "M1" in stack + ExpectAbilityNumInStack(abilityName2, 1); + // ability "M1" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + STAbilityUtil::StopAbility(terminatePageAbility, 0, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnForeground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "N1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "M1" not in stack + ExpectAbilityNumInStack(abilityName2, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5600 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5700 + * @tc.name : ability state transition to foreground when background app restart,launchtype[N1:standard] + * @tc.desc : 1.start page ability N1,ENTITY_HOME,N1 in turn + * 2.wait for the event sent by the page ability + * 3.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5700 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + // ability "A1" state BACKGROUND + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + + // background app restart + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + // ability "A1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5700 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5800 + * @tc.name : terminate page ability by ability itself(one ability),launchtype[N1:standard] + * @tc.desc : 1.start a page ability N1 + * 2.terminate a page ability N1 by N1 onActive function. + * 3.wait for the event sent by the page ability + * 4.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5800 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "N1" not in stack(terminated) + ExpectAbilityNumInStack(abilityName, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5800 end"; +} + +/* + * @tc.number : AMS_Page_Ability_5900 + * @tc.name : terminate page ability by ability itself(same app),launchtype[N1,N2:standard] + * @tc.desc : 1.start a page ability N1 + * 2.start a page ability N2 by N1 onActive function. + * 3.terminate a page ability N2 by N2 onActive function. + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5900 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + // ability "N1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "N2" not in stack(terminated) + ExpectAbilityNumInStack(abilityName2, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5900 end"; +} + +/* + * @tc.number : AMS_Page_Ability_6000 + * @tc.name : terminate page ability by ability itself(multiple app),launchtype[N1,M1:standard] + * @tc.desc : 1.start a page ability N1 + * 2.start a page ability M1 by N1 onActive function. + * 3.terminate a page ability M1 by M1 onActive function. + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_6000 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName2 = abilityNameBase + "M1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + // ability "N1" state ACTIVE + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // ability "M1" not in stack(terminated) + ExpectAbilityNumInStack(abilityName2, 0); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_6000 end"; +} + +/* + * @tc.number : AMS_Page_Ability_6100 + * @tc.name : terminate previous ability of current ability,launchtype[N1,N2:standard] + * @tc.desc : 1.start a page ability N1 + * 2.start a page ability N2 by N1 onActive function. + * 3.terminate a page ability N1 by N1 onActive function. + * 4.wait for the event sent by the page ability + * 5.dump the ability info + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_6100 start"; + + std::string bundleName = bundleNameBase + "N"; + std::string abilityName = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + + // ability "N1" not in stack(terminated) + ExpectAbilityNumInStack(abilityName, 0); + // ability "N2" state ACTIVE + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_6100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_6200 + * @tc.name : verify mission stack management(standard + singleton),launchtype[N1,N2,M1:standard,N3:singleton] + * @tc.desc : 1.start page ability N1 + * 2.start page ability N2 by N1 onActive function + * 3.start page ability N3 by N2 onActive function + * 4.start page ability M1 by N3 onActive function + * 5.start page ability N3 by M1 onActive function + * 6.wait for the event sent by the page ability + * 7.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6200, Function | MediumTest | Level1) +{ + std::string bundleName1 = bundleNameBase + "N"; + std::string abilityName1 = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + std::string abilityName3 = abilityNameBase + "N3"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName5 = abilityNameBase + "M1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName1 + "," + bundleName1 + "," + bundleName2 + "," + bundleName1; + params["targetAbility"] = abilityName2 + "," + abilityName3 + "," + abilityName5 + "," + abilityName3; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnForeground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + std::vector result; + std::vector dumpInfo; + abilityMs_->DumpState((DUMP_STACK + " 1"), dumpInfo); + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + for (auto info : result) { + GTEST_LOG_(INFO) << info; + } + std::vector expectedResult = {abilityName3, abilityName5, abilityName2, abilityName1}; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 3); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName5)); + abilityInfos = missionStackInfo.missionRecords[2].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName1)); +} + +/* + * @tc.number : AMS_Page_Ability_6300 + * @tc.name : verify mission stack management(standard + singleton),launchtype[N1,N2,M1:standard,N3:singleton] + * @tc.desc : 1.start page ability N1 + * 2.start page ability N2 by N1 onActive function + * 3.start page ability N3 by N2 onActive function + * 4.start page ability M1 by N3 onActive function + * 5.start page ability N3 by M1 onActive function + * 6.start page ability N1 by N3 onActive function + * 7.wait for the event sent by the page ability + * 8.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6300, Function | MediumTest | Level1) +{ + std::string bundleName1 = bundleNameBase + "N"; + std::string abilityName1 = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + std::string abilityName3 = abilityNameBase + "N3"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName5 = abilityNameBase + "M1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName1 + "," + bundleName1; + params["targetAbility"] = abilityName2 + "," + abilityName3; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + params["targetBundle"] = bundleName1; + params["targetAbility"] = abilityName3; + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + params.clear(); + want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountTwo), 0); + std::vector result; + std::vector dumpInfo; + abilityMs_->DumpState((DUMP_STACK + " 1"), dumpInfo); + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + std::vector expectedResult = {abilityName1, abilityName2, abilityName1, abilityName3, abilityName5}; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 3); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName1)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[2].mainName.compare(abilityName1)); + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + abilityInfos = missionStackInfo.missionRecords[2].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName5)); +} + +/* + * @tc.number : AMS_Page_Ability_6400 + * @tc.name : verify mission stack management(standard + singleton),launchtype[N1,N2,M1:standard,N3:singleton] + * @tc.desc : 1.start page ability N1 + * 2.start page ability N2 by N1 onActive function + * 3.start page ability N3 by N2 onActive function + * 4.ENTITY_HOME + * 5.start page ability M1 by N3 onActive function + * 6.start page ability N3 by M1 onActive function + * 7.start page ability N2 by N3 onActive function + * 8.wait for the event sent by the page ability + * 9.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6400, Function | MediumTest | Level1) +{ + std::string bundleName1 = bundleNameBase + "N"; + std::string abilityName1 = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + std::string abilityName3 = abilityNameBase + "N3"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName5 = abilityNameBase + "M1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName1 + "," + bundleName1; + params["targetAbility"] = abilityName2 + "," + abilityName3; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + params["targetBundle"] = bundleName1; + params["targetAbility"] = abilityName3; + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + params.clear(); + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountTwo), 0); + std::vector result; + std::vector dumpInfo; + abilityMs_->DumpState((DUMP_STACK + " 1"), dumpInfo); + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + std::vector expectedResult = {abilityName2, abilityName2, abilityName1, abilityName3, abilityName5}; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 3); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[2].mainName.compare(abilityName1)); + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + abilityInfos = missionStackInfo.missionRecords[2].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName5)); +} + +/* + * @tc.number : AMS_Page_Ability_6500 + * @tc.name : verify mission stack management(singletop + singleton),launchtype[I1,I2,B1:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1 + * 2.start page ability I2 + * 3.start page ability I3 + * 4.ENTITY_HOME + * 5.start page ability B1 + * 6.start page ability I3 + * 7.start page ability I1 + * 8.wait for the event sent by the page ability + * 9.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6500, Function | MediumTest | Level1) +{ + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName5 = abilityNameBase + "B1"; + // Start Ability I1(singletop) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + // Start Ability B1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + // Start Ability I3 again(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountTwo), 0); + std::vector result; + std::vector dumpInfo; + abilityMs_->DumpState((DUMP_STACK + " 1"), dumpInfo); + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + std::vector expectedResult = {abilityName1, abilityName2, abilityName1, abilityName3, abilityName5}; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 3); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName1)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[2].mainName.compare(abilityName1)); + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + abilityInfos = missionStackInfo.missionRecords[2].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName5)); +} + +/* + * @tc.number : AMS_Page_Ability_6600 + * @tc.name : verify mission stack management(singletop + singleton),launchtype[I1,I2,B1:singletop,I3:singleton] + * @tc.desc : 1.start page ability I1 + * 2.start page ability I2 + * 3.start page ability I3 + * 4.ENTITY_HOME + * 5.start page ability B1 + * 6.start page ability I3 + * 7.start page ability I2 + * 8.wait for the event sent by the page ability + * 9.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6600, Function | MediumTest | Level1) +{ + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName5 = abilityNameBase + "B1"; + // Start Ability I1(singletop) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + // simulate ENTITY_HOME + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + // Start Ability B1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + // Start Ability I3 again(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName3, 1); + ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountTwo), 0); + std::vector result; + std::vector dumpInfo; + abilityMs_->DumpState((DUMP_STACK + " 1"), dumpInfo); + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + std::vector expectedResult = {abilityName2, abilityName1, abilityName3, abilityName5}; + EXPECT_TRUE(MTDumpUtil::GetInstance()->CompStrVec(result, expectedResult)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 3); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName2)); + EXPECT_EQ(0, abilityInfos[1].mainName.compare(abilityName1)); + abilityInfos = missionStackInfo.missionRecords[1].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName3)); + abilityInfos = missionStackInfo.missionRecords[2].abilityRecordInfos; + EXPECT_EQ(0, abilityInfos[0].mainName.compare(abilityName5)); +} + +/* + * @tc.number : AMS_Page_Ability_6700 + * @tc.name : verify mission stack management(standard + singleton),launchtype[N1,N2,M1:standard,N3:singleton] + * @tc.desc : 1.start page ability N1 + * 2.start page ability N2 by N1 onActive function + * 3.start page ability N3 by N2 onActive function + * 4.start page ability M1 by N3 onActive function + * 5.start page ability N3 by M1 onActive function + * 6.back N3,M1,N2,N1 in turn + * 7.wait for the event sent by the page ability + * 8.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6700, Function | MediumTest | Level1) +{ + std::string bundleName1 = bundleNameBase + "N"; + std::string abilityName1 = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + std::string abilityName3 = abilityNameBase + "N3"; + std::string bundleName2 = bundleNameBase + "M"; + std::string abilityName5 = abilityNameBase + "M1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName1 + "," + bundleName1 + "," + bundleName2; + params["targetAbility"] = abilityName2 + "," + abilityName3 + "," + abilityName5; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName5, 1); + ExpectAbilityCurrentState(abilityName5, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName5); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 0); + ExpectAbilityCurrentState(launcherAbilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); +} + +/* + * @tc.number : AMS_Page_Ability_6800 + * @tc.name : verify mission stack management(standard + singleton),launchtype[N1,N2,M1:standard,N3:singleton] + * @tc.desc : 1.start page ability I1 + * 2.start page ability I2 + * 3.start page ability I3 + * 4.start page ability B1 + * 5.start page ability I3 + * 6.back I3,B1,I2,I1 in turn + * 7.wait for the event sent by the page ability + * 8.dump the stack management + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6800, Function | MediumTest | Level1) +{ + std::string bundleName1 = bundleNameBase + "I"; + std::string abilityName1 = abilityNameBase + "I1"; + std::string abilityName2 = abilityNameBase + "I2"; + std::string abilityName3 = abilityNameBase + "I3"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName5 = abilityNameBase + "B1"; + // Start Ability I1(singletop) + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + // Start Ability I2(singletop) + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + // Start Ability I3(SI) + want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + // Start Ability B1(singletop) + want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName5, 1); + ExpectAbilityCurrentState(abilityName5, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName5); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo); + EXPECT_TRUE(missionStackInfo.missionRecords.size() == 0); + ExpectAbilityCurrentState(launcherAbilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); +} + +/* + * @tc.number : AMS_Page_Ability_6900 + * @tc.name : restart app after kill app process,launchtype[A1,C1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.determine process status + * 4.kill current Application + * 5.start page ability C1,A1 in turn + * 6.wait for the event sent by the page ability + * 7.determine process status and ability status + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_6900 start"; + + std::string bundleName1 = bundleNameBase + "A"; + std::string bundleName2 = bundleNameBase + "C"; + std::string abilityName1 = abilityNameBase + "A1"; + std::string abilityName2 = abilityNameBase + "C1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName1, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + STAbilityUtil::KillApplication(bundleName1, appMs_, WAIT_TIME); + STAbilityUtil::CleanMsg(event_); + params["targetBundle"] = bundleName1; + params["targetAbility"] = abilityName1; + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + + RunningProcessInfo pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName1, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo1.state_); + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo2.state_); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_6900 end"; +} + +/* + * @tc.number : AMS_Page_Ability_7000 + * @tc.name : restart app after kill app process,launchtype[A1:singletop] + * @tc.desc : 1.start a page ability A1 + * 2.wait for the event sent by the page ability + * 3.determine process status + * 4.kill current Application + * 5.start a page ability A1 + * 6.wait for the event sent by the page ability + * 7.determine process status and ability status + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_7000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7000 start"; + + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + STAbilityUtil::KillApplication(bundleName, appMs_, WAIT_TIME); + STAbilityUtil::CleanMsg(event_); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo2.state_); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7000 end"; +} + +/* + * @tc.number : AMS_Page_Ability_7100 + * @tc.name : different hap same bundleName,launchtype[O1,P1:standard] + * @tc.desc : 1.start a page ability O1 + * 2.wait for the event sent by the page ability + * 3.get ability O1 pidinfo + * 4.start a page ability P1 + * 6.wait for the event sent by the page ability + * 7.get ability P1 pidinfo + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_7100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7100 start"; + std::string bundleName = bundleNameBase + "O"; + std::string abilityName1 = abilityNameBase + "O1"; + std::string abilityName2 = abilityNameBase + "P1"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(processInfoEvent_, pidEventName, amsStAbilityO1Code), 0); + std::string abilityO1Pid = STAbilityUtil::GetData(processInfoEvent_, pidEventName, amsStAbilityO1Code); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + std::string abilityP1Pid = STAbilityUtil::GetData(processInfoEvent_, pidEventName, amsStAbilityP1Code); + EXPECT_EQ(abilityO1Pid, abilityP1Pid); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7100 end"; +} + +/* + * @tc.number : AMS_Page_Ability_7200 + * @tc.name : different hap same bundleName,launchtype[O1,P1:standard] + * @tc.desc : 1.start a page ability O1 + * 2.wait for the event sent by the page ability + * 3.get ability O1 status + * 4.start a page ability P1 + * 6.wait for the event sent by the page ability + * 7.get ability O1 status + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_7200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7200 start"; + std::string bundleName = bundleNameBase + "O"; + std::string abilityName1 = abilityNameBase + "O1"; + std::string abilityName2 = abilityNameBase + "P1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + want = STAbilityUtil::MakeWant("device", abilityName2, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7200 end"; +} + +/* + * @tc.number : AMS_Page_Ability_7300 + * @tc.name : different hap same bundleName,launchtype[M1:standard] + * @tc.desc : 1.start a page ability M1 + * 2.wait for the event sent by the page ability + * 3.terminate ability M1 + * 4.verify callback path and ability state transition + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_7300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7300 start"; + std::string bundleName = bundleNameBase + "M"; + std::string abilityName1 = abilityNameBase + "M1"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + std::string callBackPact = "InitOnStartOnActiveOnInactiveOnBackgroundOnStop"; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + callBackPact, eventCode), 0); + std::string abilityStatus = lifecycleStateInitial + lifecycleStateInactive + lifecycleStateActive + + lifecycleStateInactive + lifecycleStateBackground + lifecycleStateInitial; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStatus, eventCode), 0); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7300 end"; +} + +/* + * @tc.number : AMS_Page_Ability_7400 + * @tc.name : different hap same bundleName,launchtype[N1,N2:standard] + * @tc.desc : 1.start a page ability N1 + * 2.start page ability N2 by N1 onActive function + * 3.terminate ability N2,N1 + * 4.wait for the event sent by the page ability + * 5.verify callback path and ability state transition + */ +HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_7400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7400 start"; + std::string bundleName = bundleNameBase + "N"; + std::string abilityName1 = abilityNameBase + "N1"; + std::string abilityName2 = abilityNameBase + "N2"; + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName1, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + std::string callBackPactN1 = + "InitOnStartOnActiveOnInactiveOnBackgroundOnForegroundOnActiveOnInactiveOnBackgroundOnStop"; + std::string callBackPactN2 = "InitOnStartOnActiveOnInactiveOnBackgroundOnStop"; + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + callBackPactN1, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + callBackPactN2, eventCode), 0); + std::string abilityStatusN1 = lifecycleStateInitial + lifecycleStateInactive + lifecycleStateActive + + lifecycleStateInactive + lifecycleStateBackground + lifecycleStateInactive + + lifecycleStateActive + lifecycleStateInactive + lifecycleStateBackground + + lifecycleStateInitial; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStatusN1, eventCode), 0); + std::string abilityStatusN2 = lifecycleStateInitial + lifecycleStateInactive + lifecycleStateActive + + lifecycleStateInactive + lifecycleStateBackground + lifecycleStateInitial; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStatusN2, eventCode), 0); + GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_7400 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_power_test/BUILD.gn b/test/systemtest/common/ams/ams_power_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..159ac2e0264339fb0d5bf6a837a631b6c180b472 --- /dev/null +++ b/test/systemtest/common/ams/ams_power_test/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_power_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_power_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_power_test" ] +} diff --git a/test/systemtest/common/ams/ams_power_test/ams_power_test.cpp b/test/systemtest/common/ams/ams_power_test/ams_power_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3448baf7114c82d688835783fa0b7986b58565e --- /dev/null +++ b/test/systemtest/common/ams/ams_power_test/ams_power_test.cpp @@ -0,0 +1,528 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "module_test_dump_util.h" +#include "st_ability_util.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "common_event.h" +#include "common_event_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using namespace OHOS::EventFwk; + +namespace { +using MAP_STR_STR = std::map; +std::vector bundleNameSuffix = {"A", "B", "N"}; +std::string bundleNameBase = "com.ohos.amsst.app"; +std::string hapNameBase = "amsSystemTest"; +std::string abilityNameBase = "AmsStAbility"; +std::string launcherBundle = "com.ohos.launcher"; +std::string launcherAbility = "com.ohos.launcher.MainAbility"; +std::string systemUiBundle = "com.ohos.systemui"; +std::string terminatePageAbility = "requ_page_ability_terminate"; + +static const std::string DUMP_STACK_LIST = "--stack-list"; +static const std::string DUMP_STACK = "--stack"; +static const std::string DUMP_MISSION = "--mission"; +static const std::string DUMP_TOP = "--top"; +static const std::string DUMP_ALL = "-a"; +constexpr int WAIT_TIME = 3 * 1000; +constexpr int WAIT_LAUNCHER_OK = 5 * 1000; +static const std::string abilityStateInit = ":Init"; +static const std::string abilityStateOnStart = ":OnStart"; +static const std::string abilityStateOnStop = ":OnStop"; +static const std::string abilityStateOnActive = ":OnActive"; +static const std::string abilityStateOnInactive = ":OnInactive"; +static const std::string abilityStateOnBackground = ":OnBackground"; +static const std::string abilityStateOnForeground = ":OnForeground"; +static const std::string abilityStateOnNewWant = ":OnNewWant"; +static const int abilityStateCountOne = 1; +static const int abilityStateCountTwo = 2; +enum AbilityState_Test { + INITIAL = 0, + INACTIVE, + ACTIVE, + BACKGROUND, + SUSPENDED, + INACTIVATING, + ACTIVATING, + MOVING_BACKGROUND, + TERMINATING, + ALLSUM, +}; +static const std::vector abilityStateVec = { + "INITIAL", + "INACTIVE", + "ACTIVE", + "BACKGROUND", + "SUSPENDED", + "INACTIVATING", + "ACTIVATING", + "MOVING_BACKGROUND", + "TERMINATING", +}; +} // namespace +class AppEventSubscriber; + +class AmsPowerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static std::vector GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs); + static bool SubscribeEvent(); + void ShowDump(); + static void CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState); + void ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, + const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = (DUMP_STACK + " 1")); + void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + {} + virtual ~AppEventSubscriber() + {} + virtual void OnReceiveEvent(const CommonEventData &data) override; + }; + static sptr appMs_; + static sptr abilityMs_; + static STtools::Event event_; + static std::shared_ptr subscriber_; +}; + +sptr AmsPowerTest::appMs_ = nullptr; +sptr AmsPowerTest::abilityMs_ = nullptr; +STtools::Event AmsPowerTest::event_ = STtools::Event(); +std::shared_ptr AmsPowerTest::subscriber_ = nullptr; + +void AmsPowerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsPowerTest::SetUpTestCase(void)"; + std::vector hapNames = GetBundleNames(hapNameBase, bundleNameSuffix); + STAbilityUtil::InstallHaps(hapNames); + SubscribeEvent(); + appMs_ = STAbilityUtil::GetAppMgrService(); + abilityMs_ = STAbilityUtil::GetAbilityManagerService(); + if (appMs_) { + int freeTime = 60; + appMs_->SetAppFreezingTime(freeTime); + int time = 0; + appMs_->GetAppFreezingTime(time); + std::cout << "appMs_->GetAppFreezingTime();" << time << std::endl; + } +} + +void AmsPowerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsPowerTest::TearDownTestCase(void)"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); + STAbilityUtil::UninstallBundle(bundleNames); +} + +void AmsPowerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "void AmsPowerTest::SetUp(void)"; +} + +void AmsPowerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "void AmsPowerTest::TearDown(void)"; + STAbilityUtil::RemoveStack(1, abilityMs_, WAIT_TIME, WAIT_LAUNCHER_OK); + std::vector vecBundleName; + for (const auto &suffix : bundleNameSuffix) { + vecBundleName.push_back(bundleNameBase + suffix); + } + STAbilityUtil::KillBundleProcess(vecBundleName); + + STAbilityUtil::CleanMsg(event_); +} + +std::vector AmsPowerTest::GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs) +{ + std::vector bundleNames; + for (auto strSuffix : strSuffixs) { + bundleNames.push_back(strBase + strSuffix); + } + return bundleNames; +} + +bool AmsPowerTest::SubscribeEvent() +{ + std::vector eventList = {"resp_st_page_ability_callback"}; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsPowerTest::ShowDump() +{ + if (abilityMs_) { + std::vector dumpInfo; + abilityMs_->DumpState("-a", dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + } +} + +void AmsPowerTest::CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState) +{ + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", info, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + // ability exist + EXPECT_NE(pos, result.end()); + MTDumpUtil::GetInstance()->GetAll("State", info, result); + EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } + // ability state + if (midState != "") { + bool compareResult = ((*pos == state) || (*pos == midState)); + EXPECT_EQ(1, compareResult); + } else { + EXPECT_EQ(*pos, state); + } +} + +void AmsPowerTest::ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, + const AbilityState_Test &midState, const std::string &args) +{ + std::string strCurrentState = abilityStateVec.at(currentState); + std::string strMidState = ""; + if (midState != AbilityState_Test::ALLSUM) { + strMidState = abilityStateVec.at(midState); + } + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(args, dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, strCurrentState, strMidState); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsPowerTest::ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState("-a", dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsPowerTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + std::string eventName = data.GetWant().GetAction(); + if (eventName == "resp_st_page_ability_callback") { + std::string target = data.GetData(); + STAbilityUtil::Completed(event_, target, data.GetCode()); + } +} + +/* + * @tc.number : AMS_Power_0100 + * @tc.name : Verify poweroff and poweron functions + * @tc.desc : 1.start ability + * 2.called PowerOff + * 3.Check the stack status and process status, + * and verify the application callback function at the same time. + * 4.called PowerOn + * 5.Check the stack status and process status, + * and verify the application callback function at the same time. + */ +HWTEST_F(AmsPowerTest, AMS_Power_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0100 start"; + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + if (abilityMs_) { + abilityMs_->PowerOff(); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + if (abilityMs_) { + abilityMs_->PowerOn(); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnForeground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVATING, AbilityState_Test::ACTIVE); + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0100 end"; +} + +/* + * @tc.number : AMS_Power_0200 + * @tc.name : Verify poweroff and poweron functions(different bundle)[A1,B1:singleton] + * @tc.desc : 1.start ability + * 2.called PowerOff + * 3.Check the stack status and process status, + * and verify the application callback function at the same time. + * 4.called PowerOn + * 5.Check the stack status and process status, + * and verify the application callback function at the same time. + */ +HWTEST_F(AmsPowerTest, AMS_Power_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0200 start"; + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + ShowDump(); + if (abilityMs_) { + abilityMs_->PowerOff(); + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + ShowDump(); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + if (abilityMs_) { + abilityMs_->PowerOn(); + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + ShowDump(); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnForeground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVATING, AbilityState_Test::ACTIVE); + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0200 end"; +} + +/* + * @tc.number : AMS_Power_0300 + * @tc.name : Verify poweroff and poweron functions(different bundle)[A1,B1:singleton] + * @tc.desc : 1.start ability(PowerOff now) + * 2.called PowerOff + * 3.Check the stack status and process status, + * and verify the application callback function at the same time. + * 4.called PowerOn + * 5.Check the stack status and process status, + * and verify the application callback function at the same time. + */ +HWTEST_F(AmsPowerTest, AMS_Power_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0300 start"; + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "B"; + std::string abilityName2 = abilityNameBase + "B1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + + if (abilityMs_) { + int errCode = abilityMs_->PowerOff(); + EXPECT_EQ(POWER_OFF_WAITING, errCode); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + if (abilityMs_) { + abilityMs_->PowerOn(); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVATING, AbilityState_Test::ACTIVE); + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0300 end"; +} + +/* + * @tc.number : AMS_Power_0400 + * @tc.name : Verify poweroff and poweron functions(different bundle)[A1:singleton,N3:singleton] + * @tc.desc : 1.start ability(PowerOff now) + * 2.called PowerOff + * 3.Check the stack status and process status, + * and verify the application callback function at the same time. + * 4.called PowerOn + * 5.Check the stack status and process status, + * and verify the application callback function at the same time. + */ +HWTEST_F(AmsPowerTest, AMS_Power_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0400 start"; + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "N"; + std::string abilityName2 = abilityNameBase + "N3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + if (abilityMs_) { + abilityMs_->PowerOff(); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_BACKGROUND, pInfo.state_); + if (abilityMs_) { + abilityMs_->PowerOn(); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVATING, AbilityState_Test::ACTIVE); + pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0400 end"; +} + +/* + * @tc.number : AMS_Power_0500 + * @tc.name : Verify poweroff and poweron functions(different bundle)[A1:singleton,N3:singleton] + * @tc.desc : 1.start ability + * 2.called PowerOff(PowerOn now) + * 3.called PowerOn + * 4.Check the stack status and process status, + * and verify the application callback function at the same time. + */ +HWTEST_F(AmsPowerTest, AMS_Power_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0500 start"; + std::string bundleName = bundleNameBase + "A"; + std::string abilityName = abilityNameBase + "A1"; + std::string bundleName2 = bundleNameBase + "N"; + std::string abilityName2 = abilityNameBase + "N3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + if (abilityMs_) { + abilityMs_->PowerOff(); + } + if (abilityMs_) { + abilityMs_->PowerOn(); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVATING, AbilityState_Test::ACTIVE); + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs_, WAIT_TIME); + EXPECT_EQ(AppProcessState::APP_STATE_FOREGROUND, pInfo.state_); + + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0500 end"; +} + +/* + * @tc.number : AMS_Power_0600 + * @tc.name : Verify poweroff and poweron functions(launcher)[singleton] + * @tc.desc : 1.called PowerOff + * 2.Check the launcher process status + * 3.called PowerOn + * 4.Check the launcher process status + */ +HWTEST_F(AmsPowerTest, AMS_Power_0600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0600 start"; + ExpectAbilityCurrentState(launcherAbility, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); + ShowDump(); + if (abilityMs_) { + abilityMs_->PowerOff(); + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + ShowDump(); + ExpectAbilityCurrentState( + launcherAbility, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND, DUMP_ALL); + if (abilityMs_) { + abilityMs_->PowerOn(); + } + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME)); + ExpectAbilityCurrentState(launcherAbility, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); + ShowDump(); + + GTEST_LOG_(INFO) << "AmsPowerTest AMS_Power_0600 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_service_ability_test/BUILD.gn b/test/systemtest/common/ams/ams_service_ability_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..bfe0bf1033ce664bd2053053033fdf7cae5ac150 --- /dev/null +++ b/test/systemtest/common/ams/ams_service_ability_test/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_service_ability_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "ams_service_ability_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_service_ability_test" ] +} diff --git a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b7f40d9da40573ff12d23f4bdd989b818006482 --- /dev/null +++ b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp @@ -0,0 +1,2114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_lifecycle_executor.h" +#include "ability_manager_errors.h" +#include "ability_manager_service.h" +#include "ams_service_ability_test_def.h" +#include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "event.h" +#include "hilog_wrapper.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "st_ability_util.h" + +namespace { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; + +std::vector bundleNameList = { + BUNDLE_NAME_BASE + "A", + BUNDLE_NAME_BASE + "B", + BUNDLE_NAME_BASE + "C", + BUNDLE_NAME_BASE + "D", + BUNDLE_NAME_BASE + "E", + BUNDLE_NAME_BASE + "F", + BUNDLE_NAME_BASE + "G", +}; + +std::vector hapNameList = { + HAP_NAME_BASE + "A", + HAP_NAME_BASE + "B", + HAP_NAME_BASE + "C", + HAP_NAME_BASE + "D", + HAP_NAME_BASE + "E", + HAP_NAME_BASE + "F", + HAP_NAME_BASE + "G", + HAP_NAME_BASE + "H", +}; + +class AmsServiceAbilityTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + void CheckAbilityStateByName( + const std::string &abilityName, const std::vector &info, const std::string &state) const; + void ExpectPageAbilityCurrentState(const std::string &abilityName, const std::string ¤tState) const; + void ExpectServiceAbilityCurrentState(const std::string &abilityName, const std::string ¤tState) const; + void ExpectDataAbilityCurrentState(const std::string &abilityName, const std::string ¤tState) const; + void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum) const; + AbilityInfo MakeAbilityInfo( + const std::string &name, const std::string &appName, const std::string &bundleName) const; + static bool SubscribeEvent(); + + void AmsServiceAbilityTest16001() const; + void AmsServiceAbilityTest16002() const; + + void AmsServiceAbilityTest17001() const; + void AmsServiceAbilityTest17002() const; + + void AmsServiceAbilityTest18001() const; + void AmsServiceAbilityTest18002() const; + + void AmsServiceAbilityTest23001() const; + void AmsServiceAbilityTest23002() const; + + static sptr abilityMs; + static sptr appMs; + static std::vector eventList; + static STtools::Event event; + static std::map mapState; + + // Trim from start + static inline std::string &Ltrim(std::string &s) + { + s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) { return !std::isspace(c); })); + return s; + } + // Trim from end + static inline std::string &Rtrim(std::string &s) + { + s.erase(std::find_if(s.rbegin(), s.rend(), [](int c) { return !std::isspace(c); }).base(), s.end()); + return s; + } + + static inline std::string &Trim(std::string &s) + { + return Ltrim(Rtrim(s)); + } + + void ExecuteSystemForResult(const string &cmd, string &result) + { + result.clear(); + char bufPs[BUFFER_SIZE]; + FILE *ptr; + if (!cmd.empty() && (ptr = popen(cmd.c_str(), "r")) != NULL) { + while (fgets(bufPs, BUFFER_SIZE, ptr) != nullptr) { + result.append(bufPs); + } + pclose(ptr); + ptr = nullptr; + } + } + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityConnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + } + + static size_t onAbilityConnectDoneCount; + }; + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const CommonEventData &data) override; + }; + + static std::shared_ptr subscriber; +}; +size_t AmsServiceAbilityTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::shared_ptr AmsServiceAbilityTest::subscriber = nullptr; + +std::vector AmsServiceAbilityTest::eventList = { + "resp_com_ohos_amsst_service_app_a1", + "resp_com_ohos_amsst_service_app_b2", + "resp_com_ohos_amsst_service_app_b3", + "resp_com_ohos_amsst_service_app_c4", + "resp_com_ohos_amsst_service_app_d1", + "resp_com_ohos_amsst_service_app_e2", + "resp_com_ohos_amsst_service_app_f3", + "resp_com_ohos_amsst_service_app_g1", + "resp_com_ohos_amsst_service_app_h1", +}; + +std::map AmsServiceAbilityTest::mapState = { + {"OnStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnCommand", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnConnect", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnDisConnect", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStart", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityStop", AbilityLifecycleExecutor::LifecycleState::INITIAL}, + {"OnAbilityActive", AbilityLifecycleExecutor::LifecycleState::ACTIVE}, + {"OnAbilityInactive", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnAbilityBackground", AbilityLifecycleExecutor::LifecycleState::BACKGROUND}, + {"OnAbilityForeground", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, + {"OnStateChanged", AbilityLifecycleExecutor::LifecycleState::INACTIVE}, +}; + +STtools::Event AmsServiceAbilityTest::event = STtools::Event(); +void AmsServiceAbilityTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + auto eventName = data.GetWant().GetAction(); + auto iter = std::find(eventList.begin(), eventList.end(), eventName); + if (iter != eventList.end()) { + STAbilityUtil::Completed(event, data.GetData(), data.GetCode()); + } +} + +void AmsServiceAbilityTest::SetUpTestCase(void) +{ + // Subscribe Event + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "subscribeEvent error"; + } +} + +void AmsServiceAbilityTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber); +} + +void AmsServiceAbilityTest::SetUp(void) +{ + STAbilityUtil::InstallHaps(hapNameList); + AbilityConnectCallback::onAbilityConnectDoneCount = 0; + abilityMs = STAbilityUtil::GetAbilityManagerService(); + appMs = STAbilityUtil::GetAppMgrService(); + usleep(WAIT_TIME); +} + +bool AmsServiceAbilityTest::SubscribeEvent() +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsServiceAbilityTest::TearDown(void) +{ + STAbilityUtil::UninstallBundle(bundleNameList); + usleep(WAIT_TIME); + STAbilityUtil::CleanMsg(event); +} + +sptr AmsServiceAbilityTest::abilityMs = nullptr; +sptr AmsServiceAbilityTest::appMs = nullptr; + +void AmsServiceAbilityTest::ExpectPageAbilityCurrentState( + const std::string &abilityName, const std::string ¤tState) const +{ + std::vector dumpInfo; + if (abilityMs != nullptr) { + abilityMs->DumpState(DUMP_STACK + " 1", dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, currentState); + } else { + HILOG_ERROR("ability manager service(abilityMs) is nullptr"); + } +} + +void AmsServiceAbilityTest::ExpectServiceAbilityCurrentState( + const std::string &abilityName, const std::string ¤tState) const +{ + std::vector dumpInfo; + if (abilityMs != nullptr) { + abilityMs->DumpState(DUMP_SERVICE, dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, currentState); + } else { + HILOG_ERROR("ability manager service(abilityMs) is nullptr"); + } +} + +void AmsServiceAbilityTest::ExpectDataAbilityCurrentState( + const std::string &abilityName, const std::string ¤tState) const +{ + std::vector dumpInfo; + if (abilityMs != nullptr) { + abilityMs->DumpState(DUMP_DATA, dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, currentState); + } else { + HILOG_ERROR("ability manager service(abilityMs) is nullptr"); + } +} + +void AmsServiceAbilityTest::ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum) const +{ + std::vector dumpInfo; + if (abilityMs != nullptr) { + abilityMs->DumpState(DUMP_STACK + " 1", dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs) is nullptr"); + } +} + +void AmsServiceAbilityTest::CheckAbilityStateByName( + const std::string &abilityName, const std::vector &info, const std::string &state) const +{ + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", info, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + // ability exist + EXPECT_NE(pos, result.end()); + MTDumpUtil::GetInstance()->GetAll("State", info, result); + EXPECT_TRUE(pos < result.end()); + // ability state + EXPECT_EQ(Trim(*pos), state); +} + +AbilityInfo AmsServiceAbilityTest::MakeAbilityInfo( + const std::string &name, const std::string &appName, const std::string &bundleName) const +{ + AbilityInfo abilityInfo; + abilityInfo.name = name; + abilityInfo.applicationName = appName; + abilityInfo.bundleName = bundleName; + + return abilityInfo; +} + +/** + * @tc.number : AMS_Service_Ability_0100 + * @tc.name : AMS kit test + * @tc.desc : start a service ability + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0100 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + // start ability + MAP_STR_STR params; + Want want = STAbilityUtil::STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0200 + * @tc.name : AMS kit test + * @tc.desc : start multiple times the same service ability in the same app + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0200 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + // start ability + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + for (size_t i = 0; i < TIMES; i++) { + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + if (i == 0) { + EXPECT_EQ( + STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + } + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + } + + // stop ability + ErrCode eCode1 = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode1); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0300 + * @tc.name : AMS kit test + * @tc.desc : start service ability by another page ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0300 start"; + + std::string bundleName2 = BUNDLE_NAME_BASE + "B"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string bundleName3 = BUNDLE_NAME_BASE + "B"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName3; + params["targetAbility"] = abilityName3; + + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName2, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "B2" state ACTIVE + ExpectPageAbilityCurrentState(abilityName2, "ACTIVE"); + + // ability "B3" state ACTIVE + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_START_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability B2 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability B3 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B3, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0400 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then stop service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0400 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0500 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0500 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + EXPECT_GT(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)0); + + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0500 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0600 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0600 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + + usleep(WAIT_TIME); + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0600 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0700 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0700 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // check number of connections + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)1); + + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // check number of connections + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)0); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0700 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0800 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0800 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + + eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + usleep(WAIT_TIME); + // check number of connections + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)1); + + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // check number of connections + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)0); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_0900 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_0900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0900 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + + // connect service ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + ErrCode eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // check number of connections + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)1); + + RunningProcessInfo pInfo = STAbilityUtil::GetAppProcessInfoByName(bundleName, appMs); + EXPECT_TRUE(pInfo.pid_ > 0); + + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // check number of connections + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)0); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_0900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_1000 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1000 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + + for (size_t i = 0; i < TIMES; i++) { + ErrCode eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + if (i == 0) { + EXPECT_EQ( + STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ( + STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + } + } + usleep(WAIT_TIME); + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)1); + + ErrCode eCode1 = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(ERR_OK, eCode1); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // check number of connections + EXPECT_EQ(AbilityConnectCallback::onAbilityConnectDoneCount, (size_t)0); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_1100 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1100 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + + MAP_STR_STR params; + params["targetBundleConn"] = bundleName; + params["targetAbilityConn"] = abilityName3; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "B2" state ACTIVE + ExpectPageAbilityCurrentState(abilityName2, "ACTIVE"); + + // ability2 connect ability3 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + + // stop ability B3 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "DisConnectOtherAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability B2 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_1200 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1200 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + + // connect service ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + ErrCode eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + + usleep(WAIT_TIME); + eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + + usleep(WAIT_TIME); + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + + usleep(WAIT_TIME); + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1200 end"; +} + +/** + * @tc.number : AMS_Service_Ability_1300 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1300 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + + // connect service ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + ErrCode eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + + usleep(WAIT_TIME); + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1300 end"; +} + +/** + * @tc.number : AMS_Service_Ability_1400 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in the same app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1400 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + + // connect service ability + sptr stub(new (std::nothrow) AbilityConnectCallback()); + sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); + ErrCode eCode = STAbilityUtil::ConnectAbility(want, connCallback, stub->AsObject()); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_NE(ERR_OK, eCode); + + usleep(WAIT_TIME); + eCode = STAbilityUtil::DisconnectAbility(connCallback); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1400 end"; +} + +/** + * @tc.number : AMS_Service_Ability_1500 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in another app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1500 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "B"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + + MAP_STR_STR params; + params["targetBundleConn"] = bundleName; + params["targetAbilityConn"] = abilityName3; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName, params); + // start ability2 + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "B2" state ACTIVE + ExpectPageAbilityCurrentState(abilityName2, "ACTIVE"); + + // ability2 connect ability3 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability B3 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "DisConnectOtherAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability2 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1500 end"; +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest16001() const +{ + std::string bundleName1 = BUNDLE_NAME_BASE + "A"; + std::string bundleName2 = BUNDLE_NAME_BASE + "B"; + std::string abilityName1 = ABILITY_NAME_BASE + "A1"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName3; + params["nextTargetBundle"] = bundleName1; + params["nextTargetAbility"] = abilityName1; + params["nextTargetBundleConn"] = bundleName2; + params["nextTargetAbilityConn"] = abilityName3; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName2, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + // start page ability2 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "B2" state ACTIVE + ExpectPageAbilityCurrentState(abilityName2, "ACTIVE"); + + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_START_OTHER_ABILITY); + // page ability2 start service ability3 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest16002() const +{ + std::string bundleName1 = BUNDLE_NAME_BASE + "A"; + std::string bundleName2 = BUNDLE_NAME_BASE + "B"; + std::string abilityName1 = ABILITY_NAME_BASE + "A1"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName3; + params["nextTargetBundle"] = bundleName1; + params["nextTargetAbility"] = abilityName1; + params["nextTargetBundleConn"] = bundleName2; + params["nextTargetAbilityConn"] = abilityName3; + // service ability B3 start service ability A1 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B3, AbilityState_Test::USER_DEFINE, OPERATION_START_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // service ability A1 connect service ability B3 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_A1, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + Want want3 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName3, bundleName2, params); + ErrCode eCode = STAbilityUtil::StopServiceAbility(want3); + EXPECT_NE(ERR_OK, eCode); + + // service ability1 disconnect service ability3 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_A1, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop abiity B3 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B3, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop abiity A1 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_A1, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop abiity B2 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); +} + +/** + * @tc.number : AMS_Service_Ability_1600 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in another app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1600 start"; + + AmsServiceAbilityTest16001(); + AmsServiceAbilityTest16002(); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1600 end"; +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest17001() const +{ + std::string bundleName1 = BUNDLE_NAME_BASE + "A"; + std::string bundleName2 = BUNDLE_NAME_BASE + "B"; + std::string bundleName3 = BUNDLE_NAME_BASE + "C"; + std::string abilityName1 = ABILITY_NAME_BASE + "A1"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + std::string abilityName4 = ABILITY_NAME_BASE + "C4"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName1 + "," + bundleName2 + "," + bundleName3; + params["targetAbility"] = abilityName1 + "," + abilityName3 + "," + abilityName4; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName2, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + // start page ability2 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "B2" state ACTIVE + ExpectPageAbilityCurrentState(abilityName2, "ACTIVE"); + + // start service ability3 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_START_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest17002() const +{ + // start service ability4 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // start service ability1 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop abiity B3 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B3, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop abiity A1 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_A1, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop abiity C4 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_C4, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop page ability2 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ONINACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); +} + +/** + * @tc.number : AMS_Service_Ability_1700 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in another app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1700 start"; + + AmsServiceAbilityTest17001(); + AmsServiceAbilityTest17002(); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1700 end"; +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest18001() const +{ + std::string bundleName1 = BUNDLE_NAME_BASE + "A"; + std::string bundleName2 = BUNDLE_NAME_BASE + "B"; + std::string bundleName3 = BUNDLE_NAME_BASE + "C"; + std::string abilityName1 = ABILITY_NAME_BASE + "A1"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + std::string abilityName4 = ABILITY_NAME_BASE + "C4"; + + MAP_STR_STR params; + params["targetBundleConn"] = bundleName1 + "," + bundleName2 + "," + bundleName3; + params["targetAbilityConn"] = abilityName1 + "," + abilityName3 + "," + abilityName4; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName2, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + // start page ability2 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "B2" state ACTIVE + ExpectPageAbilityCurrentState(abilityName2, "ACTIVE"); + + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + // connect service ability3 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // connect service ability4 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest18002() const +{ + // connect service ability1 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop abiity A1 B3 C4 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "DisConnectOtherAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop page ability2 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); +} + +/** + * @tc.number : AMS_Service_Ability_1800 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in another app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1800 start"; + + AmsServiceAbilityTest18001(); + AmsServiceAbilityTest18002(); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1800 end"; +} + +/** + * @tc.number : AMS_Service_Ability_1900 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in another app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_1900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1900 start"; + + std::string bundleName1 = BUNDLE_NAME_BASE + "D"; + std::string bundleName2 = BUNDLE_NAME_BASE + "E"; + std::string bundleName3 = BUNDLE_NAME_BASE + "F"; + std::string abilityName1 = ABILITY_NAME_BASE + "D1"; + std::string abilityName2 = ABILITY_NAME_BASE + "E2"; + std::string abilityName3 = ABILITY_NAME_BASE + "F3"; + + MAP_STR_STR params; + params["targetBundleConn"] = bundleName2; + params["targetAbilityConn"] = abilityName2; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName1, bundleName1, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + // start page ability1 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "D1" state ACTIVE + ExpectPageAbilityCurrentState(abilityName1, "ACTIVE"); + usleep(WAIT_TIME); + + // page ability1 connect service ability2 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_D1, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // page ability1 access data ability3 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_D1, AbilityState_Test::USER_DEFINE, OPERATION_GET_DATA_BY_DATA_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, OPERATION_FROM_DATA_ABILITY, 1, DELAY_TIME), 0); + + // stop ability E2 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_D1, 0, "DisConnectOtherAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability D1 + ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_D1, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_1900 end"; +} + +/** + * @tc.number : AMS_Service_Ability_2000 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in another app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_2000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2000 start"; + + std::string bundleName1 = BUNDLE_NAME_BASE + "D"; + std::string bundleName2 = BUNDLE_NAME_BASE + "E"; + std::string bundleName3 = BUNDLE_NAME_BASE + "F"; + std::string abilityName1 = ABILITY_NAME_BASE + "D1"; + std::string abilityName2 = ABILITY_NAME_BASE + "E2"; + std::string abilityName3 = ABILITY_NAME_BASE + "F3"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant(DEVICE_ID, abilityName1, bundleName1, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + // start page ability1 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "D1" state ACTIVE + ExpectPageAbilityCurrentState(abilityName1, "ACTIVE"); + + // page ability1 access data ability3 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_D1, AbilityState_Test::USER_DEFINE, OPERATION_GET_DATA_BY_DATA_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, OPERATION_FROM_DATA_ABILITY, 1, DELAY_TIME), 0); + usleep(WAIT_TIME); + + // stop ability D1 + bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_D1, 0, "StopSelfAbility"); + EXPECT_TRUE(ret); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2000 end"; +} + +/** + * @tc.number : AMS_Service_Ability_2100 + * @tc.name : AMS kit test + * @tc.desc : In two different haps, ServiceAbility belongs to the same BundleName, and ServiceAbility belongs + * to the same process id. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_2100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2100 start"; + + std::string bundleName1 = BUNDLE_NAME_BASE + "G"; + std::string bundleName2 = BUNDLE_NAME_BASE + "G"; + std::string abilityName1 = ABILITY_NAME_BASE + "G1"; + std::string abilityName2 = ABILITY_NAME_BASE + "H1"; + + // start ability G1 + MAP_STR_STR params1; + Want want1 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName1, bundleName1, params1); + ErrCode eCode = STAbilityUtil::StartAbility(want1, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + RunningProcessInfo pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName1, appMs); + EXPECT_TRUE(pInfo1.pid_ > 0); + + // start ability H1 + MAP_STR_STR params2; + params2["targetBundleConn"] = bundleName1; + params2["targetAbilityConn"] = abilityName1; + Want want2 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName2, params2); + eCode = STAbilityUtil::StartAbility(want2, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_TRUE(pInfo1.pid_ == pInfo2.pid_); + + // stop ability G1 + eCode = STAbilityUtil::StopServiceAbility(want1); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability H1 + eCode = STAbilityUtil::StopServiceAbility(want2); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2100 end"; +} + +/** + * @tc.number : AMS_Service_Ability_2200 + * @tc.name : AMS kit test + * @tc.desc : In two different haps, ServiceAbility belongs to the same BundleName, and ServiceAbility starts + * each other. + * + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_2200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2200 start"; + + std::string bundleName1 = BUNDLE_NAME_BASE + "G"; + std::string bundleName2 = BUNDLE_NAME_BASE + "G"; + std::string abilityName1 = ABILITY_NAME_BASE + "G1"; + std::string abilityName2 = ABILITY_NAME_BASE + "H1"; + + MAP_STR_STR params1; + params1["targetBundleConn"] = bundleName2; + params1["targetAbilityConn"] = abilityName2; + Want want1 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName1, bundleName1, params1); + ErrCode eCode = STAbilityUtil::StartAbility(want1, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + // start page ability1 + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + RunningProcessInfo pInfo1 = STAbilityUtil::GetAppProcessInfoByName(bundleName1, appMs); + EXPECT_TRUE(pInfo1.pid_ > 0); + + // service ability G1 connect service ability H1 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_G1, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // start ability H1 + MAP_STR_STR params2; + params2["targetBundleConn"] = bundleName1; + params2["targetAbilityConn"] = abilityName1; + Want want2 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName2, params2); + eCode = STAbilityUtil::StartAbility(want2, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + -1); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + RunningProcessInfo pInfo2 = STAbilityUtil::GetAppProcessInfoByName(bundleName2, appMs); + EXPECT_TRUE(pInfo2.pid_ > 0); + EXPECT_TRUE(pInfo1.pid_ == pInfo2.pid_); + + // service ability H1 connect service ability G1 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_H1, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + -1); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // disconnect G1 from H1 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_H1, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability G1 + eCode = STAbilityUtil::StopServiceAbility(want1); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // disconnect H1 from G1 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_G1, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // stop ability H1 + eCode = STAbilityUtil::StopServiceAbility(want2); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2200 end"; +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest23001() const +{ + std::string bundleName1 = BUNDLE_NAME_BASE + "A"; + std::string bundleName2 = BUNDLE_NAME_BASE + "B"; + std::string bundleName3 = BUNDLE_NAME_BASE + "E"; + std::string abilityName1 = ABILITY_NAME_BASE + "A1"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + std::string abilityName4 = ABILITY_NAME_BASE + "E2"; + + // start page ability A1 + MAP_STR_STR params1; + params1["targetBundleConn"] = bundleName2; + params1["targetAbilityConn"] = abilityName3; + + Want want1 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName1, bundleName1, params1); + ErrCode eCode = STAbilityUtil::StartAbility(want1, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // service ability A1 connect service ability B3 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_A1, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // check B3 connect number + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME), 0); + + // start page ability B2 + MAP_STR_STR params2; + params2["targetBundleConn"] = bundleName2; + params2["targetAbilityConn"] = abilityName3; + + Want want2 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName2, bundleName2, params2); + eCode = STAbilityUtil::StartAbility(want2, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // ability "B2" state ACTIVE + ExpectPageAbilityCurrentState(abilityName2, "ACTIVE"); + + // service ability B2 connect service ability B3 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + usleep(WAIT_TIME); + // check B3 connect number + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME), 0); +} + +void AmsServiceAbilityTest::AmsServiceAbilityTest23002() const +{ + std::string bundleName1 = BUNDLE_NAME_BASE + "A"; + std::string bundleName2 = BUNDLE_NAME_BASE + "B"; + std::string bundleName3 = BUNDLE_NAME_BASE + "E"; + std::string abilityName1 = ABILITY_NAME_BASE + "A1"; + std::string abilityName2 = ABILITY_NAME_BASE + "B2"; + std::string abilityName3 = ABILITY_NAME_BASE + "B3"; + std::string abilityName4 = ABILITY_NAME_BASE + "E2"; + + // start page ability E2 + MAP_STR_STR params3; + params3["targetBundleConn"] = bundleName2; + params3["targetAbilityConn"] = abilityName3; + + Want want3 = STAbilityUtil::MakeWant(DEVICE_ID, abilityName4, bundleName3, params3); + ErrCode eCode = STAbilityUtil::StartAbility(want3, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // service ability E2 connect service ability B3 + STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_E2, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); + usleep(WAIT_TIME); + + // check B3 connect number + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, "OnAbilityConnectDone", 1, DELAY_TIME), 0); + + // Disconnect A1 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_A1, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); + usleep(WAIT_TIME); + // check B3 connect number + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 0, DELAY_TIME), 0); + + // Disconnect B2 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); + usleep(WAIT_TIME); + // check B3 connect number + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 0, DELAY_TIME), 0); + + // Disconnect E2 + STAbilityUtil::PublishEvent( + REQ_EVENT_NAME_APP_E2, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + usleep(WAIT_TIME); + // check B3 connect number + EXPECT_EQ(STAbilityUtil::WaitCompleted(event, "OnAbilityDisconnectDone", 0, DELAY_TIME), 0); +} + +/** + * @tc.number : AMS_Service_Ability_2300 + * @tc.name : AMS kit test + * @tc.desc : start service ability and then connect service ability in another app. + */ +HWTEST_F(AmsServiceAbilityTest, AMS_Service_Ability_2300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2300 start"; + + AmsServiceAbilityTest23001(); + AmsServiceAbilityTest23002(); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AMS_Service_Ability_2300 end"; +} + +/** + * @tc.number : AppSpawn_TEST_0100 + * @tc.name : Check appspawn process information + * @tc.desc : The system rc is started, and based on root privileges, the AppSpawn process is created, + * and related resources are loaded. + */ +HWTEST_F(AmsServiceAbilityTest, AppSpawn_TEST_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_TEST_0100 start"; + + std::string cmd = "ps -ef |grep appspawn |grep -v grep"; + std::string result; + ExecuteSystemForResult(cmd, result); + EXPECT_NE(result.find("root"), std::string::npos); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_TEST_0100 end"; +} + +/** + * @tc.number : AppSpawn_TEST_0200 + * @tc.name : The process starts message monitoring. + * @tc.desc : Monitor the message of creating an application process initiated by AMS. + */ +HWTEST_F(AmsServiceAbilityTest, AppSpawn_TEST_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_TEST_0200 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // check app process information + std::string cmd = "ps -ef |grep com.ohos.amsst.service.appA |grep -v grep"; + std::string result; + ExecuteSystemForResult(cmd, result); + EXPECT_FALSE(result.empty()); + usleep(WAIT_TIME); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_TEST_0200 end"; +} + +/** + * @tc.number : AppSpawn_0300 + * @tc.name : Destroy the process through AppSpawn. + * @tc.desc : By monitoring all process information, destroy the zombie process. + */ +HWTEST_F(AmsServiceAbilityTest, AppSpawn_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_0300 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + // start ability A1 + MAP_STR_STR params; + Want want = STAbilityUtil::STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + 0); + usleep(WAIT_TIME); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + 0); + + // check app process information + std::string cmd = "ps -ef |grep com.ohos.amsst.service.appA |grep -v grep"; + std::string result; + ExecuteSystemForResult(cmd, result); + EXPECT_TRUE(Trim(result).empty()); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_0300 end"; +} + +/** + * @tc.number : AppSpawn_0400 + * @tc.name : Recycle zombie processes. + * @tc.desc : 1.The application process is suspended. + * 2.The appSpawn listener process is suspended and the process is + * recycled. + */ +HWTEST_F(AmsServiceAbilityTest, AppSpawn_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_0400 start"; + + std::string bundleName = BUNDLE_NAME_BASE + "A"; + std::string abilityName = ABILITY_NAME_BASE + "A1"; + + // start ability A1. make zombie process + MAP_STR_STR params; + params["zombie"] = "zombie"; + Want want = STAbilityUtil::STAbilityUtil::MakeWant(DEVICE_ID, abilityName, bundleName, params); + ErrCode eCode = STAbilityUtil::StartAbility(want, abilityMs); + EXPECT_EQ(ERR_OK, eCode); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted( + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + -1); + + usleep(WAIT_TIME * 5); + // check app process information + std::string cmd = "ps -ef |grep com.ohos.amsst.service.appA |grep -v grep"; + std::string result; + ExecuteSystemForResult(cmd, result); + EXPECT_TRUE(Trim(result).empty()); + + // stop ability + eCode = STAbilityUtil::StopServiceAbility(want); + EXPECT_NE(ERR_OK, eCode); + usleep(WAIT_TIME); + + GTEST_LOG_(INFO) << "AmsServiceAbilityTest AppSpawn_0400 end"; +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test_def.h b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test_def.h new file mode 100644 index 0000000000000000000000000000000000000000..52b91eb28685d8ab6945f92a028c1d8a8deda9fc --- /dev/null +++ b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test_def.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 AMS_SERVICE_ABILITY_TEST_DEF_H_ +#define AMS_SERVICE_ABILITY_TEST_DEF_H_ +#include +#include + +namespace OHOS { +namespace AppExecFwk { +using MAP_STR_STR = std::map; + +const std::string BUNDLE_NAME_BASE = "com.ohos.amsst.service.app"; +const std::string ABILITY_NAME_BASE = "AmsStServiceAbility"; +const std::string HAP_NAME_BASE = "amsSystemTestService"; +const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher"; +const std::string DUMP_STACK_LIST = "--stack-list"; +const std::string DUMP_STACK = "--stack"; +const std::string DUMP_SERVICE = "--serv"; +const std::string DUMP_DATA = "--data"; + +const std::string DUMP_MISSION = "--mission"; +const std::string DUMP_TOP = "--top"; +const std::string DUMP_ALL = "-a"; +constexpr int WAIT_TIME = 5 * 1000 * 1000; +constexpr int WAIT_LAUNCHER_OK = 5 * 1000 * 1000; +constexpr size_t TIMES = 3; +constexpr int DELAY_TIME = 10; +constexpr int BUFFER_SIZE = 1024; + +enum AbilityState_Test { + INITIAL = 0, + INACTIVE, + ACTIVE, + BACKGROUND, + SUSPENDED, + INACTIVATING, + ACTIVATING, + MOVING_BACKGROUND, + TERMINATING, + USER_DEFINE, +}; +const std::string PAGE_STATE_ON_START = "OnStart"; +const std::string PAGE_STATE_ON_STOP = "OnStop"; +const std::string PAGE_STATE_ON_ACTIVE = "OnActive"; +const std::string PAGE_STATE_ON_INACTIVE = "OnInactive"; +const std::string PAGE_STATE_ON_BACKGROUND = "OnBackground"; + +const std::string SERVICE_STATE_ON_START = "OnStart"; +const std::string SERVICE_STATE_ON_STOP = "OnStop"; +const std::string SERVICE_STATE_ON_COMMAND = "OnCommand"; +const std::string SERVICE_STATE_ON_CONNECT = "OnConnect"; +const std::string SERVICE_STATE_ON_DISCONNECT = "OnDisconnect"; +const std::string SERVICE_STATE_ONINACTIVE = "OnInactive"; +const std::string SERVICE_STATE_ON_BACKGROUND = "OnBackground"; + +const std::string DATA_STATE_ON_START = "OnStart"; +const std::string DATA_STATE_INSERT = "Insert"; +const std::string DATA_STATE_DELETE = "Delete"; +const std::string DATA_STATE_UPDATE = "Update"; + +const std::string OPERATION_START_OTHER_ABILITY = "StartOtherAbility"; +const std::string OPERATION_CONNECT_OTHER_ABILITY = "ConnectOtherAbility"; +const std::string OPERATION_DISCONNECT_OTHER_ABILITY = "DisConnectOtherAbility"; +const std::string OPERATION_GET_DATA_BY_DATA_ABILITY = "GetDataByDataAbility"; +const std::string OPERATION_FROM_DATA_ABILITY = "GetDataByDataAbility"; +const std::string REQ_EVENT_NAME_APP_A1 = "req_com_ohos_amsst_service_app_a1"; +const std::string REQ_EVENT_NAME_APP_B2 = "req_com_ohos_amsst_service_app_b2"; +const std::string REQ_EVENT_NAME_APP_B3 = "req_com_ohos_amsst_service_app_b3"; +const std::string REQ_EVENT_NAME_APP_C4 = "req_com_ohos_amsst_service_app_c4"; +const std::string REQ_EVENT_NAME_APP_D1 = "req_com_ohos_amsst_service_app_d1"; +const std::string REQ_EVENT_NAME_APP_E2 = "req_com_ohos_amsst_service_app_e2"; +const std::string REQ_EVENT_NAME_APP_G1 = "req_com_ohos_amsst_service_app_g1"; +const std::string REQ_EVENT_NAME_APP_H1 = "req_com_ohos_amsst_service_app_h1"; + +const std::string DEVICE_ID = "device"; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_SERVICE_ABILITY_TEST_DEF_H_ \ No newline at end of file diff --git a/test/systemtest/common/ams/tool/BUILD.gn b/test/systemtest/common/ams/tool/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..7eaac1b9cb3ef38f5ec0cd95d0b9cf0693a8c376 --- /dev/null +++ b/test/systemtest/common/ams/tool/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("system_test_ability_util_config") { + include_dirs = [ + "//third_party/jsoncpp/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_shared_library("system_test_ability_util_lib") { + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + ] + + configs = [ + ":system_test_ability_util_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "//foundation/aafwk/standard/services/test/moduletest/module_test_dump_util:module_test_dump_util_config", + "//foundation/aafwk/standard/services/appmgr:appmgr_config", + ] + + deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/aafwk/standard/services/test/moduletest/module_test_dump_util:module_test_dump_util_lib", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} + +group("system_test_ability_util") { + deps = [ ":system_test_ability_util_lib" ] +} diff --git a/test/systemtest/common/ams/tool/include/event.h b/test/systemtest/common/ams/tool/include/event.h new file mode 100644 index 0000000000000000000000000000000000000000..418a425aebf5dac358b30faa060628685e755057 --- /dev/null +++ b/test/systemtest/common/ams/tool/include/event.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_SYSTEM_TEST_STEVENT_H +#define OHOS_SYSTEM_TEST_STEVENT_H + +#include +#include +#include +#include +#include +#include +#include "hilog_wrapper.h" +namespace OHOS { +namespace STtools { +class Event { +public: + Event(); + ~Event(); + bool Compare(); + int WaitingMessage(const std::string &message, int timeout_ms, bool locked); + void CompleteMessage(const std::string &message); + void Clean(); + std::string GetData(const std::string &message); + void CompleteMessage(const std::string &message, const std::string &data); + +private: + std::mutex mutex_; + std::condition_variable cv_; + std::string waiting_message_; + std::vector complete_message_; + std::unordered_map message_data_; +}; +} // namespace STtools +} // namespace OHOS +#endif // OHOS_SYSTEM_TEST_STEVENT_H \ No newline at end of file diff --git a/test/systemtest/common/ams/tool/include/module_test_dump_util.h b/test/systemtest/common/ams/tool/include/module_test_dump_util.h new file mode 100644 index 0000000000000000000000000000000000000000..8fb77bf90bc4fb2a3af191479a154f80731d4ddf --- /dev/null +++ b/test/systemtest/common/ams/tool/include/module_test_dump_util.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_MODULE_TEST_DUMP_UTIL_H +#define OHOS_MODULE_TEST_DUMP_UTIL_H + +#include +#include +#include +#include +#include +#include +#include + +namespace OHOS { +namespace MTUtil { +using str_vec = std::vector; +using str_iter = std::vector::iterator; +using dump_info_map = std::unordered_map; +using std::regex; +using std::string; + +class MTDumpUtil { +public: + virtual ~MTDumpUtil(); + static std::shared_ptr GetInstance(); + + /** + * + * @param {string} args : type to find + * @param {std::vector} dumpInfo : dump info + * @param {std::vector} results : all strings found that include @args + * @return {int} : size of @results + * @Introduction: Find all strings specified by @args in @dumpInfo and store them in @results. + */ + size_t GetAll(const string &args, const str_vec &dumpInfo, str_vec &results); + + /** + * + * @param {string} args : type to find + * @param {std::vector} dumpInfo : dump info + * @param {string} result : the first string found that includes @args + * @return {str_iter} : find or not + * @Introduction: Find the first string specified by @args in @dumpInfo and store it in @result. + */ + str_iter GetFirst(const string &args, const str_vec &dumpInfo, const str_iter &begin, string &result); + + /** + * + * @param {string} args : specific string to find + * @param {std::vector} dumpInfo : dump info + * @param {str_iter} begin : where to start searching + * @return {str_iter} : iter pointing to string containing @args + * @Introduction: Match the first @matchStr in @dumpInfo from @begin and return the iter. + */ + str_iter GetSpecific(const string &args, const str_vec &dumpInfo, const str_iter &begin); + + /** + * + * @param {str_vec} strVec_1 : the first vector of string + * @param {str_vec} strVec_2 : the second vector of string + * @return {bool} : the comparison result of the the params + * @Introduction: Return true if each item in @strVec_1 equals the corresponding one in @strVec_2. + */ + bool CompStrVec(const str_vec &strVec_1, const str_vec &strVec_2); + + /** + * + * @param {string} key : known type used to find info + * @param {string} value : value of the {key} + * @param {string} args : type to find + * @param {str_vec} dumpInfo : dump info + * @return {string} : string found in dumpInfo + * @Introduction: Return the value specified by @args with @key and @value in @dumpInfo. + */ + string GetBy(const string &key, const string &value, const string &args, const str_vec &dumpInfo); + + size_t GetBindingsByUri(const string &uri, const str_vec &dumpInfo, str_vec &result); + +private: + MTDumpUtil(); + static std::mutex mutex_; + static std::shared_ptr instance_; + std::unordered_map findRgx_; + + inline bool MatchRegex(const regex ®ex, const string &str, string &result); +}; +} // namespace MTUtil +} // namespace OHOS +#endif // OHOS_MODULE_TEST_DUMP_UTIL_H diff --git a/test/systemtest/common/ams/tool/include/st_ability_util.h b/test/systemtest/common/ams/tool/include/st_ability_util.h new file mode 100644 index 0000000000000000000000000000000000000000..f76e49f317abc0e790c81740d5f687f74c962de7 --- /dev/null +++ b/test/systemtest/common/ams/tool/include/st_ability_util.h @@ -0,0 +1,351 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_SYSTEM_TEST_ABILITY_UTIL_H +#define OHOS_SYSTEM_TEST_ABILITY_UTIL_H +#include "event.h" +#include "stoperator.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "bundle_installer_interface.h" +#include "bundle_mgr_interface.h" +#include "hilog_wrapper.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "status_receiver_host.h" +#include "iservice_registry.h" +#include +#include +#include +#include +#include + +namespace OHOS { +namespace STABUtil { +namespace { +using vector_str = std::vector; +using MAP_STR_STR = std::map; +} // namespace +class STAbilityUtil { +public: + static std::shared_ptr GetInstance(); + static void DestroyInstance(); + ~STAbilityUtil() = default; + + /** + * + * @param {string} eventName : Sent Event Name + * @param {int} code : Sent Code + * @param {string} data : Sent Data + * @Introduction: Sent Event + */ + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + + /** + * + * @param {vector} hapNames : container containing multiple hap names + * @Introduction: use bm install multiple hap + */ + static void InstallHaps(vector_str &hapNames); + + /** + * + * @param {vector} bundleNames : container containing multiple bundle names + * @Introduction: use bm install multiple bundle + */ + static void UninstallBundle(vector_str &bundleNames); + + /** + * + * @param {string} serviceName : process name + * @Introduction: kill process + */ + static void KillService(const std::string &serviceName); + + /** + * + * @param {string} serviceName : executable file name + * @param {time_t} delay : Waiting time for executable to start(milliseconds) + * @Introduction: start executable file + */ + static void StartService(const std::string &serviceName, const time_t &delay = 0); + + /** + * + * @param {vector} bundleNames : Container Containing Multiple Bundle Names + * @Introduction: start executable file + */ + static void KillBundleProcess(vector_str &bundleNames); + + /** + * + * @Introduction: Get Ability manager Service. + */ + static sptr GetAbilityManagerService(); + + /** + * + * @Introduction: Get App manager Service. + */ + static sptr GetAppMgrService(); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {sptr} abilityMs : Ability Manager Service ptr + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: start ability + */ + static ErrCode StartAbility( + const AAFwk::Want &want, sptr &abilityMs, const time_t &delay = 0); + + /** + * + * @param {string} eventName : Sent Event Name + * @param {int} code : Sent Code + * @param {string} data : Sent Data + * @Introduction: Sent Event to terminate app + */ + static bool StopAbility(const std::string &eventName, const int &code, const std::string &data); + /** + * + * @param {string} deviceId : Device ID + * @param {string} abilityName : Ability Name + * @param {string} bundleName : Bundle Name + * @param {MAP_STR_STR} params : Params (SetParam) + * @Introduction: Great Want + */ + static AAFwk::Want MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, MAP_STR_STR params = {}); + + /** + * + * @param {string} deviceId : Device ID + * @param {string} abilityName : Ability Name + * @param {string} bundleName : Bundle Name + * @param {vector_str} params : Params (SetParam) + * @Introduction: Great Want + */ + static AAFwk::Want MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, vector_str params = {}); + + /** + * + * @param {int64_t} id : Ability Record ID + * @param {sptr} abilityMs : Ability Manager Service ptr + * @Introduction: Get Top AbilityRecord ID + */ + static ErrCode GetTopAbilityRecordId(int64_t &id, sptr &abilityMs); + + /** + * + * @param {shared_ptr} runningProcessInfo : Process Info + * @param {sptr} appMs : App Manager ptr + * @param {time_t} delay : Waiting time for ability to Get Process Info (milliseconds) + * @Introduction: Get Top AbilityRecord ID + */ + static ErrCode GetRunningProcessInfo(std::vector &runningProcessInfo, + sptr &appMs, const time_t &delay = 0); + + /** + * + * @param {string} appName : app Name + * @param {sptr} appMs : App Manager ptr + * @param {time_t} delay : Waiting time for ability to KillApplication (milliseconds) + * @Introduction: Get Top AbilityRecord ID + */ + static ErrCode KillApplication( + const std::string &appName, sptr &appMs, const time_t &delay = 0); + + /** + * + * @param {string} processName : processName + * @param {sptr} appMs : App Manager ptr + * @param {time_t} delay : Waiting time for ability to GetAppProcessInfo (milliseconds) + * @Introduction: Get Top AbilityRecord ID + */ + static AppExecFwk::RunningProcessInfo GetAppProcessInfoByName( + const std::string &processName, sptr &appMs, const time_t &delay = 0); + + /** + * + * @param {Event} event : Event Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @param {int} timeout : Time of wait (seconds) + * @Introduction: Judge whether the event is received in the event queue, if not, wait + */ + static int WaitCompleted( + STtools::Event &event, const std::string &eventName, const int code, const int timeout = 15); + + /** + * + * @param {Event} event : Event Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @Introduction: Compare the received events, if not, join the event queue. + */ + static void Completed(STtools::Event &event, const std::string &eventName, const int code); + + /** + * + * @param {Event} event : Event Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @param {string} data : The data of the event to wait for. + * @Introduction: Compare the received events, if not, join the event queue. + */ + static void Completed(STtools::Event &event, const std::string &eventName, const int code, const std::string &data); + + /** + * + * @param {Event} event : Event Class Object + * @Introduction: Clean wait event. + */ + static void CleanMsg(STtools::Event &event); + + /** + * + * @param {Event} event : Event Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @Introduction: get the event data. + */ + static std::string GetData(STtools::Event &event, const std::string &eventName, const int code); + + /** + * + * @param {StOperator} ParentOperator : StOperator Class Object + * @Introduction: Serialization StOperator Class Object To Vector + */ + static std::vector SerializationStOperatorToVector(STtools::StOperator &ParentOperator); + + /** + * + * @param {StOperator} ParentOperator : StOperator Class Object + * @param {vector} vectorOperator : Data Source Resolved Into StOperator Class Object + * @Introduction: Deserialization StOperator Class Object From Vector + */ + static void DeserializationStOperatorFromVector( + STtools::StOperator &ParentOperator, std::vector &vectorOperator); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {sptr} connect : Callback + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: connect ability + */ + static ErrCode ConnectAbility(const AAFwk::Want &want, const sptr &connect, + const sptr &callerToken, unsigned int usec = 0); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {sptr} connect : Callback + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: disconnect ability + */ + static ErrCode DisconnectAbility(const sptr &connect, unsigned int usec = 0); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: stop service ability + */ + static ErrCode StopServiceAbility(const AAFwk::Want &want, unsigned int usec = 0); + + /** + * Remove the specified mission stack by stack id + * + * @param id. + * @param {sptr} abilityMs : Ability Manager Service ptr + * @param {time_t} delay : Waiting time for ability to GetAppProcessInfo (milliseconds) + * @return Returns ERR_OK on success, others on failure. + */ + static int RemoveStack(int id, sptr &abilityMs, const time_t &backHmoeDelay = 0, + const time_t &removeDelay = 0); + + /** + * + * @param {string} bundleFilePath : Hap File Name + * @param {AppExecFwk::InstallFlag} installFlag : install flag + * @Introduction: use bms install + */ + static void Install( + const std::string &bundleFilePath, const AppExecFwk::InstallFlag installFlag = AppExecFwk::InstallFlag::NORMAL); + + /** + * + * @param {string} bundleName : bundleName + * @Introduction: use bm uninstall bundleName + */ + static void Uninstall(const std::string &bundleName); + +private: + /** + * + * @Introduction: get bundleManger object + */ + static sptr GetBundleMgrProxy(); + + /** + * + * @Introduction: get bundleInstaller object + */ + static sptr GetInstallerProxy(); + /** + * + * @param {vector} vectorOperator : StOperator Class Object Info Save in vectorOperator + * @param {StOperator} ParentOperator : StOperator Class Object + * @Introduction: push StOperator Class Object In Vector + */ + static void PushOperatorInVector(std::vector &vectorOperator, STtools::StOperator &ParentOperator); + + /** + * + * @param {StOperator} ParentOperator : StOperator Class Object + * @param {vector} vectorOperator : Data Source Resolved Into StOperator Class Object + * @Introduction: Pull StOperator Class Object From Vector + */ + STAbilityUtil() = default; + static void PullOperatorFromVector(STtools::StOperator &ParentOperator, std::vector &vectorOperator); + static std::shared_ptr instance_; + static std::mutex mutex_; +}; + +class InstallToolStatusReceiver : public AppExecFwk::StatusReceiverHost { +public: + InstallToolStatusReceiver(); + virtual ~InstallToolStatusReceiver() override; + virtual void OnStatusNotify(const int progress) override; + virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override; + static int TestWaitCompleted(STtools::Event &event, const std::string eventName, const int code, + const int timeout = 10); + static void TestCompleted(STtools::Event &event, const std::string &eventName, const int code); + STtools::Event event_ = STtools::Event(); + +private: + int iProgress_ = 0; + DISALLOW_COPY_AND_MOVE(InstallToolStatusReceiver); +}; +} // namespace STABUtil +} // namespace OHOS +#endif // OHOS_SYSTEM_TEST_ABILITY_UTIL_H diff --git a/test/systemtest/common/ams/tool/include/stoperator.h b/test/systemtest/common/ams/tool/include/stoperator.h new file mode 100644 index 0000000000000000000000000000000000000000..3cf9b14874c7d78fea0a1b95fcaf6b1c4cdd6ef5 --- /dev/null +++ b/test/systemtest/common/ams/tool/include/stoperator.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_SYSTEM_TEST_STOPERATORTREE_H +#define OHOS_SYSTEM_TEST_STOPERATORTREE_H + +#include +#include +#include +#include + +namespace OHOS { +namespace STtools { +using std::string; + +class StOperator { +private: + std::vector> g_childOperator; + std::shared_ptr g_parentOperator; + string g_abilityType; + string g_bundleName; + string g_abilityName; + string g_operatorName; // data ability + string g_message; + /* data */ + static int countChild; + +public: + StOperator(); + StOperator(const string &type, const string &bundle, const string &ability, const string &operatorName = "", + const string &message = "r"); + ~StOperator(); + static int GetCountChild(); + string GetAbilityType(); + StOperator &SetAbilityType(const string &type); + string GetBundleName(); + StOperator &SetBundleName(const string &bundleName); + string GetAbilityName(); + StOperator &SetAbilityName(const string &abilityName); + string GetOperatorName(); + StOperator &SetOperatorName(const string &operatorName); + string GetMessage(); + StOperator &SetMessage(const string &message); + StOperator &AddChildOperator(std::shared_ptr childOperator); + std::vector> GetChildOperator(); +}; +} // namespace STtools +} // namespace OHOS +#endif // OHOS_SYSTEM_TEST_STOPERATORTREE_H \ No newline at end of file diff --git a/test/systemtest/common/ams/tool/src/event.cpp b/test/systemtest/common/ams/tool/src/event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93b6cf8b74fc3cb4fecf5f6beaeb70ed77d35de2 --- /dev/null +++ b/test/systemtest/common/ams/tool/src/event.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "event.h" + +namespace OHOS { +namespace STtools { +Event::Event() +{ + waiting_message_ = ""; + complete_message_.clear(); +} + +Event::~Event() +{ + waiting_message_ = ""; + std::vector tmp_vector; + tmp_vector.swap(complete_message_); + complete_message_.clear(); +} + +bool Event::Compare() +{ + if (!waiting_message_.empty()) { + for (size_t i = 0; i < complete_message_.size(); i++) { + if (waiting_message_.compare(complete_message_.at(i)) == 0) { + complete_message_.erase(std::begin(complete_message_) + i, std::begin(complete_message_) + i + 1); + waiting_message_ = ""; + return true; + } + } + } + return false; +} + +int Event::WaitingMessage(const std::string &message, int timeout_ms, bool locked) +{ + std::unique_lock lock(mutex_); + HILOG_INFO(" WaitingMessage: [%{public}s]", message.c_str()); + waiting_message_ = message; + if (Compare()) { + HILOG_INFO(" WaitingMessage: unlock [%{public}s]", message.c_str()); + return 0; + } + + if (locked) { + HILOG_INFO(" WaitingMessage: locked [%{public}s]", message.c_str()); + cv_.wait(lock); + return 0; + } + + if (cv_.wait_for(lock, std::chrono::seconds(timeout_ms)) == std::cv_status::timeout) { + HILOG_INFO("[%{public}s] waiting timeout", waiting_message_.c_str()); + waiting_message_ = ""; + return -1; + } + return 0; +} + +void Event::CompleteMessage(const std::string &message) +{ + std::unique_lock lock(mutex_); + HILOG_INFO("CompleteMessage [%{public}s]", message.c_str()); + if (waiting_message_.compare(message) == 0) { + HILOG_INFO("Completed unlocked: [%{public}s]", message.c_str()); + waiting_message_ = ""; + cv_.notify_all(); + return; + } + HILOG_INFO("completed message: [%{public}s] does not equal waiting message", message.c_str()); + + complete_message_.push_back(message); + return; +} + +void Event::CompleteMessage(const std::string &message, const std::string &data) +{ + std::unique_lock lock(mutex_); + HILOG_INFO("CompleteMessage [%{public}s]", message.c_str()); + message_data_[message] = data; + if (waiting_message_.compare(message) == 0) { + HILOG_INFO("Completed unlocked: [%{public}s]", message.c_str()); + waiting_message_ = ""; + cv_.notify_all(); + return; + } + HILOG_INFO("completed message: [%{public}s] does not equal waiting message", message.c_str()); + + complete_message_.push_back(message); + return; +} + +std::string Event::GetData(const std::string &message) +{ + std::string data; + std::unique_lock lock(mutex_); + if (message_data_.find(message) != message_data_.end()) { + data = message_data_.at(message); + message_data_.erase(message); + } + return data; +} + +void Event::Clean() +{ + HILOG_INFO("Event::Clean()"); + std::unique_lock lock(mutex_); + waiting_message_ = ""; + complete_message_.clear(); + message_data_.clear(); +} +} // namespace STtools +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp b/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7dfa0a4cb83ec08fe0a942210949d5eb0c219df3 --- /dev/null +++ b/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ + +#define private public +#include "module_test_dump_util.h" +#undef private + +namespace OHOS { +namespace MTUtil { +std::mutex MTDumpUtil::mutex_; +std::shared_ptr MTDumpUtil::instance_ = nullptr; +std::size_t matchSize = 2; +std::shared_ptr MTDumpUtil::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (instance_ == nullptr) { + instance_ = std::make_shared(); + } + } + return instance_; +} + +MTDumpUtil::MTDumpUtil() +{ + findRgx_["Intent"] = regex(".*intent\\[(.+)\\].*"); + findRgx_["AbilityName"] = regex(".*main name \\[(.+)\\].*"); + findRgx_["AppName"] = regex(".*app name \\[(.+)\\].*"); + findRgx_["BundleName"] = regex(".*bundle name \\[(.+)\\].*"); + findRgx_["AbilityType"] = regex(".*ability type \\[(.+)\\].*"); + findRgx_["PreAbilityName"] = regex(".*previous ability app name \\[(.+)\\].*"); + findRgx_["PreAppName"] = regex(".*previous ability file name \\[(.+)\\].*"); + findRgx_["NextAbilityName"] = regex(".*next ability app name \\[(.+)\\].*"); + findRgx_["NextAppName"] = regex(".*next ability file name \\[(.+)\\].*"); + findRgx_["State"] = regex(".*state #(.+) .*"); + findRgx_["StartTime"] = regex(".*start time \\[(.+)\\].*"); + findRgx_["MissionRecordID"] = regex(".*MissionRecord ID #(.+) bottom app.*"); + findRgx_["MissionBottomApp"] = regex(".*bottom app \\[(.+)\\].*"); + findRgx_["UserID"] = regex(".*User ID #(.+)\\].*"); + findRgx_["MissionStackID"] = regex(".*MissionStack ID #(.+) \\[.*"); + findRgx_["Uri"] = regex(".*uri \\[(.+)\\].*"); + findRgx_["AbilityRecordID"] = regex(".*AbilityRecord ID #(.+) state.*"); + findRgx_["Bindings"] = regex(".+s: (\\d+).*"); + findRgx_["Component"] = regex(".*> (.+) .+#.+"); + findRgx_["BindState"] = regex(".*> .+/.+ #(.+)"); +} + +MTDumpUtil::~MTDumpUtil() +{ + instance_ = nullptr; + instance_.reset(); +} + +bool MTDumpUtil::CompStrVec(const str_vec &strVec_1, const str_vec &strVec_2) +{ + if (strVec_1.size() != strVec_2.size()) { + return false; + } + for (unsigned int i = 0; i < strVec_1.size(); ++i) { + if (strVec_1[i].compare(strVec_2[i]) != 0) { + return false; + } + } + return true; +} + +str_iter MTDumpUtil::GetSpecific(const string &matchStr, const str_vec &dumpInfo, const str_iter &begin) +{ + auto checkCondition = [&matchStr](const str_vec::value_type &value) -> bool { + return string::npos != value.find(matchStr); + }; + str_iter end; + std::advance(end, dumpInfo.size()); + return std::find_if(begin, end, checkCondition); +} + +bool MTDumpUtil::MatchRegex(const regex &rgx, const string &text, string &result) +{ + std::smatch baseMatch; + if (std::regex_match(text, baseMatch, rgx)) { + if (baseMatch.size() == matchSize) { + result = baseMatch[1].str(); + return true; + } + } + return false; +} + +size_t MTDumpUtil::GetAll(const string &args, const str_vec &dumpInfo, str_vec &results) +{ + results.clear(); + // args not exist + if (findRgx_.find(args) == findRgx_.end()) { + return 0; + } + string findResult; + for (const auto &info : dumpInfo) { + if (MatchRegex(findRgx_[args], info, findResult)) { + results.emplace_back(findResult); + } + } + return results.size(); +} + +str_iter MTDumpUtil::GetFirst(const string &args, const str_vec &dumpInfo, const str_iter &begin, string &result) +{ + result.clear(); + str_iter end; + std::advance(end, dumpInfo.size()); + // args not exist + if (findRgx_.find(args) == findRgx_.end()) { + return end; + } + string findResult; + for (auto it = begin; it != dumpInfo.end(); ++it) { + if (MatchRegex(findRgx_[args], *it, findResult)) { + result = std::move(findResult); + return it; + } + } + return end; +} + +string MTDumpUtil::GetBy(const string &key, const string &value, const string &args, const str_vec &dumpInfo) +{ + str_vec items; + size_t preSize = GetAll(key, dumpInfo, items); + auto iter = GetSpecific(value, items, items.begin()); + if (iter != items.end() && preSize == GetAll(args, dumpInfo, items)) { + return *iter; + } + return ""; +} + +size_t MTDumpUtil::GetBindingsByUri(const string &uri, const str_vec &dumpInfo, str_vec &result) +{ + result.clear(); + str_vec dump(dumpInfo); + string bindings; + auto uriBegin = GetSpecific("uri [" + uri + "]", dump, dump.begin()); + auto bindingsBegin = GetFirst("Bindings", dump, uriBegin, bindings) + 1; + size_t ret = std::stoul("0" + bindings); + std::for_each(bindingsBegin, + (((bindingsBegin + ret) > dump.end()) ? (dump.end()) : (bindingsBegin + ret)), + [&result](auto &&it) { result.push_back(it); }); + return ret; +} +} // namespace MTUtil +} // namespace OHOS diff --git a/test/systemtest/common/ams/tool/src/st_ability_util.cpp b/test/systemtest/common/ams/tool/src/st_ability_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06c7694f6e585d52bda984a0528084ae3b435342 --- /dev/null +++ b/test/systemtest/common/ams/tool/src/st_ability_util.cpp @@ -0,0 +1,523 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "st_ability_util.h" +#include "status_receiver_host.h" +#include "iservice_registry.h" +namespace OHOS { +namespace STABUtil { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::EventFwk; + +std::mutex STAbilityUtil::mutex_; +std::shared_ptr STAbilityUtil::instance_ = nullptr; + +bool STAbilityUtil::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void STAbilityUtil::InstallHaps(vector_str &hapNames) +{ + for (auto hapName : hapNames) { + Install(hapName); + } +} + +void STAbilityUtil::UninstallBundle(vector_str &bundleNames) +{ + for (auto bundleName : bundleNames) { + Uninstall(bundleName); + } +} + +void STAbilityUtil::KillService(const std::string &serviceName) +{ + system(("kill -9 $(pidof " + serviceName + ") > /dev/null 2>&1").c_str()); +} + +void STAbilityUtil::StartService(const std::string &serviceName, const time_t &delay) +{ + system(("/system/bin/" + serviceName + "& > /dev/null 2>&1").c_str()); + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); +} + +void STAbilityUtil::KillBundleProcess(vector_str &bundleNames) +{ + for (std::string bundleName : bundleNames) { + KillService(bundleName); + } +} + +sptr STAbilityUtil::GetAbilityManagerService() +{ + sptr abilityMsObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (abilityMsObj == nullptr) { + HILOG_ERROR("failed to get ability manager service"); + return nullptr; + } + return iface_cast(abilityMsObj); +} + +sptr STAbilityUtil::GetAppMgrService() +{ + sptr appMsObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); + if (appMsObj == nullptr) { + HILOG_ERROR("failed to get app manager service"); + return nullptr; + } + return iface_cast(appMsObj); +} + +ErrCode STAbilityUtil::StartAbility(const Want &want, sptr &abilityMs, const time_t &delay) +{ + ErrCode result = OHOS::ERR_OK; + abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->StartAbility(want); + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + if (result == OHOS::ERR_OK) { + HILOG_INFO("start ability successfully."); + } else { + HILOG_INFO("failed to start ability."); + } + + return result; +} + +bool STAbilityUtil::StopAbility(const std::string &eventName, const int &code, const std::string &data) +{ + return PublishEvent(eventName, code, data); +} + +ErrCode STAbilityUtil::StopServiceAbility(const Want &want, unsigned int usec) +{ + ErrCode result = OHOS::ERR_OK; + + sptr abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->StopServiceAbility(want); + if (result == OHOS::ERR_OK) { + HILOG_INFO("stop service ability successfully."); + } else { + HILOG_INFO("failed to stop service ability."); + } + + return result; +} + +ErrCode STAbilityUtil::ConnectAbility(const Want &want, const sptr &connect, + const sptr &callerToken, unsigned int usec) +{ + ErrCode result = OHOS::ERR_OK; + + sptr abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->ConnectAbility(want, connect, callerToken); + if (result == OHOS::ERR_OK) { + HILOG_INFO("connect ability successfully."); + } else { + HILOG_INFO("failed to connect ability."); + } + + return result; +} + +ErrCode STAbilityUtil::DisconnectAbility(const sptr &connect, unsigned int usec) +{ + ErrCode result = OHOS::ERR_OK; + + sptr abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->DisconnectAbility(connect); + if (result == OHOS::ERR_OK) { + HILOG_INFO("StopServiceAbility successfully."); + } else { + HILOG_INFO("failed to StopServiceAbility."); + } + + return result; +} + +Want STAbilityUtil::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, MAP_STR_STR params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +Want STAbilityUtil::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, vector_str params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + want.SetParam("operator", params); + return want; +} + +ErrCode STAbilityUtil::GetTopAbilityRecordId(int64_t &id, sptr &abilityMs) +{ + ErrCode result = OHOS::ERR_OK; + id = -1; + abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + StackInfo stackInfo; + abilityMs->GetAllStackInfo(stackInfo); + MissionStackInfo defaultMissionStack; + for (const auto &stackInfo : stackInfo.missionStackInfos) { + if (stackInfo.id == 1) { // DEFAULT_MISSION_STACK_ID = 1 + defaultMissionStack = stackInfo; + break; + } + } + if (!defaultMissionStack.missionRecords.empty() && + !defaultMissionStack.missionRecords.begin()->abilityRecordInfos.empty()) { + id = defaultMissionStack.missionRecords.begin()->abilityRecordInfos.begin()->id; + } + return result; +} + +ErrCode STAbilityUtil::GetRunningProcessInfo( + std::vector &runningProcessInfo, sptr &appMs, const time_t &delay) +{ + ErrCode result = ERR_OK; + appMs = GetAppMgrService(); + if (appMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get app manager service"); + return result; + } + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + result = appMs->GetAllRunningProcesses(runningProcessInfo); + if (result == ERR_OK) { + HILOG_INFO("get running process info successfully."); + } else { + HILOG_INFO("failed to get running process info."); + } + return result; +} + +ErrCode STAbilityUtil::KillApplication(const std::string &appName, sptr &appMs, const time_t &delay) +{ + ErrCode result = ERR_OK; + appMs = GetAppMgrService(); + if (appMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get app manager service"); + return result; + } + result = appMs->GetAmsMgr()->KillApplication(appName); + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + if (result == ERR_OK) { + HILOG_INFO("kill application:%{public}s successfully.", appName.c_str()); + } else { + HILOG_INFO("failed to kill application:%{public}s.", appName.c_str()); + } + return result; +} + +RunningProcessInfo STAbilityUtil::GetAppProcessInfoByName( + const std::string &processName, sptr &appMs, const time_t &delay) +{ + RunningProcessInfo appProcessInfo; + appProcessInfo.pid_ = 0; + std::vector runningProcessInfo; + if (ERR_OK == GetRunningProcessInfo(runningProcessInfo, appMs, delay)) { + for (const auto &info : runningProcessInfo) { + if (processName == info.processName_) { + appProcessInfo = info; + } + } + } + return appProcessInfo; +} + +int STAbilityUtil::WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) +{ + HILOG_INFO("WaitCompleted"); + return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); +} + +void STAbilityUtil::Completed(Event &event, const std::string &eventName, const int code) +{ + HILOG_INFO("Completed"); + return event.CompleteMessage(std::to_string(code) + eventName); +} + +void STAbilityUtil::Completed(Event &event, const std::string &eventName, const int code, const std::string &data) +{ + HILOG_INFO("STAbilityUtil::Completed"); + return event.CompleteMessage(std::to_string(code) + eventName, data); +} + +std::string STAbilityUtil::GetData(Event &event, const std::string &eventName, const int code) +{ + HILOG_INFO("STAbilityUtil::GetData"); + return event.GetData(std::to_string(code) + eventName); +} + +void STAbilityUtil::CleanMsg(Event &event) +{ + HILOG_INFO("CleanMsg"); + return event.Clean(); +} + +std::vector STAbilityUtil::SerializationStOperatorToVector(StOperator &ParentOperator) +{ + std::vector vectorOperator; + PushOperatorInVector(vectorOperator, ParentOperator); + return vectorOperator; +} + +void STAbilityUtil::DeserializationStOperatorFromVector( + StOperator &ParentOperator, std::vector &vectorOperator) +{ + PullOperatorFromVector(ParentOperator, vectorOperator); +} + +void STAbilityUtil::PushOperatorInVector(std::vector &vectorOperator, StOperator &ParentOperator) +{ + vectorOperator.emplace_back(std::to_string(ParentOperator.GetChildOperator().size())); + vectorOperator.emplace_back(ParentOperator.GetAbilityType()); + vectorOperator.emplace_back(ParentOperator.GetBundleName()); + vectorOperator.emplace_back(ParentOperator.GetAbilityName()); + vectorOperator.emplace_back(ParentOperator.GetOperatorName()); + vectorOperator.emplace_back(ParentOperator.GetMessage()); + for (auto child : ParentOperator.GetChildOperator()) { + PushOperatorInVector(vectorOperator, *child); + } +} + +void STAbilityUtil::PullOperatorFromVector(StOperator &ParentOperator, std::vector &vectorOperator) +{ + int childnum = std::stoi(vectorOperator.front()); + vectorOperator.erase(vectorOperator.begin()); + std::string abilityType = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + std::string bundleName = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + std::string abilityName = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + std::string operatorName = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + std::string message = vectorOperator.front(); + vectorOperator.erase(vectorOperator.begin()); + ParentOperator.SetAbilityType(abilityType) + .SetBundleName(bundleName) + .SetAbilityName(abilityName) + .SetOperatorName(operatorName) + .SetMessage(message); + for (int i = 0; i < childnum; i++) { + auto child = std::make_shared(); + if (child == nullptr) { + return; + } + ParentOperator.AddChildOperator(child); + PullOperatorFromVector(*(child.get()), vectorOperator); + } +} + +int STAbilityUtil::RemoveStack( + int id, sptr &abilityMs, const time_t &backHmoeDelay, const time_t &removeDelay) +{ + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + StartAbility(wantEntity, abilityMs); + std::this_thread::sleep_for(std::chrono::milliseconds(backHmoeDelay)); + if (!abilityMs) { + HILOG_INFO("RemoveStack abilityMs nullptr"); + return OHOS::ERR_INVALID_VALUE; + } + int result = abilityMs->RemoveStack(id); + std::this_thread::sleep_for(std::chrono::milliseconds(removeDelay)); + return result; +} + +InstallToolStatusReceiver::InstallToolStatusReceiver() +{ + std::cout << "create status receiver instance" << std::endl; +} + +InstallToolStatusReceiver::~InstallToolStatusReceiver() +{ + std::cout << "destroy status receiver instance" << std::endl; +} + +void InstallToolStatusReceiver::OnStatusNotify(const int progress) +{ + iProgress_ = progress; + std::cout << "destroy status receiver instance" << progress << std::endl; +} + +void InstallToolStatusReceiver::OnFinished(const int32_t resultCode, const std::string &resultMsg) +{ + std::cout << "on finished result is " << resultCode << " " << resultMsg << std::endl; + TestCompleted(event_, resultMsg, resultCode); +} + +int InstallToolStatusReceiver::TestWaitCompleted( + Event &event, const std::string eventName, const int code, const int timeout) +{ + std::cout << "TestWaitCompleted " << eventName << std::endl; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} +void InstallToolStatusReceiver::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + std::cout << "TestCompleted " << eventName << std::endl; + STAbilityUtil::Completed(event, eventName, code); + return; +} + +const std::string MSG_SUCCESS = "[SUCCESS]"; +void STAbilityUtil::Install(const std::string &bundleFilePath, const InstallFlag installFlag) +{ + std::string bundlePath = "/system/vendor/" + bundleFilePath + ".hap"; + std::string installMsg = ""; + sptr installerProxy = GetInstallerProxy(); + if (!installerProxy) { + std::cout << "get bundle installer Failure." << std::endl; + installMsg = "Failure"; + return; + } + + InstallParam installParam; + installParam.installFlag = installFlag; + sptr statusReceiver(new (std::nothrow) InstallToolStatusReceiver()); + if (statusReceiver == nullptr) { + std::cout << "get statusReceiver Failure." << std::endl; + return; + } + bool installResult = installerProxy->Install(bundlePath, installParam, statusReceiver); + if (!installResult) { + installMsg = "Failure"; + return; + } + if (InstallToolStatusReceiver::TestWaitCompleted(statusReceiver->event_, MSG_SUCCESS, 0) == 0) { + installMsg = "Success"; + } else { + installMsg = "Failure"; + } +} + +void STAbilityUtil::Uninstall(const std::string &bundleName) +{ + std::string uninstallMsg = ""; + sptr installerProxy = GetInstallerProxy(); + if (!installerProxy) { + std::cout << "get bundle installer Failure." << std::endl; + uninstallMsg = "Failure"; + return; + } + if (bundleName.empty()) { + std::cout << "bundelname is null." << std::endl; + uninstallMsg = "Failure"; + } else { + sptr statusReceiver(new (std::nothrow) InstallToolStatusReceiver()); + if (statusReceiver == nullptr) { + std::cout << "get statusReceiver Failure." << std::endl; + uninstallMsg = "Failure"; + return; + } + InstallParam installParam; + bool uninstallResult = installerProxy->Uninstall(bundleName, installParam, statusReceiver); + if (!uninstallResult) { + std::cout << "Uninstall Failure." << std::endl; + uninstallMsg = "Failure"; + return; + } + if (InstallToolStatusReceiver::TestWaitCompleted(statusReceiver->event_, MSG_SUCCESS, 0) == 0) { + uninstallMsg = "Success"; + } else { + uninstallMsg = "Failure"; + } + } +} + +sptr STAbilityUtil::GetInstallerProxy() +{ + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + std::cout << "bundle mgr proxy is nullptr." << std::endl; + return nullptr; + } + + sptr installerProxy = bundleMgrProxy->GetBundleInstaller(); + if (!installerProxy) { + std::cout << "fail to get bundle installer proxy" << std::endl; + return nullptr; + } + std::cout << "get bundle installer proxy success." << std::endl; + return installerProxy; +} + +sptr STAbilityUtil::GetBundleMgrProxy() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + std::cout << "fail to get system ability mgr." << std::endl; + return nullptr; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + std::cout << "fail to get bundle manager proxy." << std::endl; + return nullptr; + } + + std::cout << "get bundle manager proxy success." << std::endl; + return iface_cast(remoteObject); +} +} // namespace STABUtil +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/ams/tool/src/stoperator.cpp b/test/systemtest/common/ams/tool/src/stoperator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4fb9e63d4c54173e224d4c8b930b1882e7a6acd --- /dev/null +++ b/test/systemtest/common/ams/tool/src/stoperator.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "stoperator.h" + +namespace OHOS { +namespace STtools { +using std::string; + +int StOperator::countChild = 0; + +StOperator::StOperator() + : g_parentOperator(nullptr), g_abilityType("0"), g_bundleName(""), + g_abilityName(""), g_operatorName(""), g_message("") +{ + g_childOperator.clear(); + StOperator::countChild++; +} + +StOperator::StOperator( + const string &type, const string &bundle, const string &ability, const string &operatorName, const string &message) + : g_parentOperator(nullptr), + g_abilityType(type), + g_bundleName(bundle), + g_abilityName(ability), + g_operatorName(operatorName), + g_message(message) +{ + g_childOperator.clear(); + StOperator::countChild++; +} + +StOperator::~StOperator() +{ + g_childOperator.clear(); + StOperator::countChild--; +} + +int StOperator::GetCountChild() +{ + return StOperator::countChild; +} + +string StOperator::GetAbilityType() +{ + return g_abilityType; +} + +StOperator &StOperator::SetAbilityType(const string &type) +{ + g_abilityType = type; + return *this; +} + +string StOperator::GetBundleName() +{ + return g_bundleName; +} + +StOperator &StOperator::SetBundleName(const string &bundleName) +{ + g_bundleName = bundleName; + return *this; +} + +string StOperator::GetAbilityName() +{ + return g_abilityName; +} + +StOperator &StOperator::SetAbilityName(const string &abilityName) +{ + g_abilityName = abilityName; + return *this; +} + +string StOperator::GetOperatorName() +{ + return g_operatorName; +} + +StOperator &StOperator::SetOperatorName(const string &operatorName) +{ + g_operatorName = operatorName; + return *this; +} + +string StOperator::GetMessage() +{ + return g_message; +} + +StOperator &StOperator::SetMessage(const string &message) +{ + g_message = message; + return *this; +} + +StOperator &StOperator::AddChildOperator(std::shared_ptr childOperator) +{ + if (childOperator == nullptr) { + return *this; + } + childOperator->g_parentOperator = std::make_shared(*this); + g_childOperator.emplace_back(childOperator); + return *this; +} + +std::vector> StOperator::GetChildOperator() +{ + return g_childOperator; +} +} // namespace STtools +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/BUILD.gn b/test/systemtest/common/fms/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..2c34894a86178c9ed67a41a562a589cc87f124e6 --- /dev/null +++ b/test/systemtest/common/fms/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("form_manager_test_config") { + defines = [ + "APP_LOG_TAG = \"FormManagerTest\"", + "LOG_DOMAIN = 0xD00666F", + ] + + configs = [ + "${aafwk_path}/frameworks/kits/ability/native:ability_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base_sdk_config", + ] +} + +public_configs = [ ":form_manager_test_config" ] + +group("systemtest") { + testonly = true + + deps = [ + "fms_acquire_form_test:systemtest", + "fms_acquire_form_test_max:systemtest", + "fms_delete_form_test:systemtest", + "fms_fuzz_test:systemtest", + "fms_performance_test:systemtest", + "fms_release_form_test:systemtest", + "fms_self_starting_test:systemtest", + "fms_stress_test:systemtest", + ] +} diff --git a/test/systemtest/common/fms/common/include/form_event.h b/test/systemtest/common/fms/common/include/form_event.h new file mode 100644 index 0000000000000000000000000000000000000000..56091491156754ec890e8d4c8240a620e8e59b55 --- /dev/null +++ b/test/systemtest/common/fms/common/include/form_event.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_SYSTEM_TEST_FMS_STEVENT_H +#define OHOS_SYSTEM_TEST_FMS_STEVENT_H + +#include +#include +#include +#include +#include +#include +#include "hilog_wrapper.h" +namespace OHOS { +namespace STtools { +class FormEvent { +public: + FormEvent(); + ~FormEvent(); + bool Compare(); + int WaitingMessage(const std::string &message, int timeout_ms, bool locked); + void CompleteMessage(const std::string &message); + void Clean(); + std::string GetData(const std::string &message); + void CompleteMessage(const std::string &message, const std::string &data); + +private: + std::mutex mutex_; + std::condition_variable cv_; + std::string waiting_message_; + std::vector complete_message_; + std::unordered_map message_data_; +}; +} // namespace STtools +} // namespace OHOS +#endif // OHOS_SYSTEM_TEST_FMS_STEVENT_H \ No newline at end of file diff --git a/test/systemtest/common/fms/common/include/form_st_common_info.h b/test/systemtest/common/fms/common/include/form_st_common_info.h new file mode 100755 index 0000000000000000000000000000000000000000..122acb5cb523547f8b1006c2830b0ba772583ba1 --- /dev/null +++ b/test/systemtest/common/fms/common/include/form_st_common_info.h @@ -0,0 +1,420 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FORM_ST_COMMON_INFO_H +#define FORM_ST_COMMON_INFO_H + +namespace OHOS { +namespace AppExecFwk { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_TEST_DEVICEID = "0"; + +const std::string FORM_ABILITY_STATE_ONACTIVE = ":OnActive"; +const std::string FORM_EVENT_ABILITY_ONACTIVED = "fms_req_acquireForm_ability_actived"; + +const int FORM_DIMENSION_1 = 1; +const bool FORM_TEMP_FORM_FLAG_FALSE = false; +const bool FORM_TEMP_FORM_FLAG_TRUE = true; + +// provider ability +const std::string FORM_PROVIDER_BUNDLE_NAME1 = "com.form.formsystemtestservicea"; +const std::string FORM_PROVIDER_BUNDLE_NAME2 = "com.form.formsystemtestserviceb"; +const std::string FORM_PROVIDER_BUNDLE_NAME3 = "com.form.formsystemtestservicec"; +const std::string FORM_PROVIDER_BUNDLE_NAME4 = "com.form.formsystemtestserviced"; +const std::string FORM_PROVIDER_BUNDLE_NAME5 = "com.form.formsystemtestservicee"; +const std::string FORM_PROVIDER_ABILITY_NAME1 = "FormStServiceAbilityA"; +const std::string FORM_PROVIDER_ABILITY_NAME2 = "FormStServiceAbilityB"; +const std::string FORM_PROVIDER_ABILITY_NAME3 = "FormStServiceAbilityC"; +const std::string FORM_PROVIDER_ABILITY_NAME4 = "FormStServiceAbilityD"; +const std::string FORM_PROVIDER_ABILITY_NAME5 = "FormStServiceAbilityE"; +const std::string PARAM_PROVIDER_MODULE_NAME1 = "formmodule001"; +const std::string PARAM_PROVIDER_MODULE_NAME2 = "formmodule001"; +const std::string PARAM_FORM_NAME1 = "Form_Js001"; +const std::string PARAM_FORM_NAME2 = "Form_Js002"; + +// add Form +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_TEMP = "fms_req_acquireForm_temp"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_TEMP = "fms_recv_acquireForm_temp"; +const std::string FORM_EVENT_REQ_DELETE_FORM_COMMON = "fms_req_deleteForm_common"; +const std::string FORM_EVENT_RECV_DELETE_FORM_COMMON = "fms_recv_deleteForm_common"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_0100 = "fms_req_acquireForm_0100"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_0100 = "fms_recv_acquireForm_0100"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_0200 = "fms_req_acquireForm_0200"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_0200 = "fms_recv_acquireForm_0200"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_0300 = "fms_req_acquireForm_0300"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_0300 = "fms_recv_acquireForm_0300"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_0400 = "fms_req_acquireForm_0400"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_0400 = "fms_recv_acquireForm_0400"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_0500 = "fms_req_acquireForm_0500"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_0500 = "fms_recv_acquireForm_0500"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_0600 = "fms_req_acquireForm_0600"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_0600 = "fms_recv_acquireForm_0600"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_0700 = "fms_req_acquireForm_0700"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_0700 = "fms_recv_acquireForm_0700"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1000 = "fms_req_acquireForm_1000"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1000 = "fms_recv_acquireForm_1000"; + +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1100 = "fms_req_acquireForm_1100"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1100 = "fms_recv_acquireForm_1100"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1200 = "fms_req_acquireForm_1200"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1200 = "fms_recv_acquireForm_1200"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1400 = "fms_req_acquireForm_1400"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1400 = "fms_recv_acquireForm_1400"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1400_1 = "fms_req_acquireForm_1400_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1400_1 = "fms_recv_acquireForm_1400_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1500 = "fms_req_acquireForm_1500"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1500 = "fms_recv_acquireForm_1500"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1500_1 = "fms_req_acquireForm_1500_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1500_1 = "fms_recv_acquireForm_1500_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1600 = "fms_req_acquireForm_1600"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1600 = "fms_recv_acquireForm_1600"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1600_1 = "fms_req_acquireForm_1600_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1600_1 = "fms_recv_acquireForm_1600_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1800 = "fms_req_acquireForm_1800"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1800 = "fms_recv_acquireForm_1800"; + + +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1800_1 = "fms_req_acquireForm_1800_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1800_1 = "fms_recv_acquireForm_1800_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1800_2 = "fms_req_acquireForm_1800_2"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1800_2 = "fms_recv_acquireForm_1800_2"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1800_3 = "fms_req_acquireForm_1800_3"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1800_3 = "fms_recv_acquireForm_1800_3"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_1900 = "fms_req_acquireForm_1900"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_1900 = "fms_recv_acquireForm_1900"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2100 = "fms_req_acquireForm_2100"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2100 = "fms_recv_acquireForm_2100"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2100_1 = "fms_req_acquireForm_2100_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2100_1 = "fms_recv_acquireForm_2100_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2200 = "fms_req_acquireForm_2200"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2200 = "fms_recv_acquireForm_2200"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2300 = "fms_req_acquireForm_2300"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2300 = "fms_recv_acquireForm_2300"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2400 = "fms_req_acquireForm_2400"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2400 = "fms_recv_acquireForm_2400"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2400_1 = "fms_req_acquireForm_2400_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2400_1 = "fms_recv_acquireForm_2400_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2500 = "fms_req_acquireForm_2500"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2500 = "fms_recv_acquireForm_2500"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2600 = "fms_req_acquireForm_2600"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2600 = "fms_recv_acquireForm_2600"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2600_1 = "fms_req_acquireForm_2600_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2600_1 = "fms_recv_acquireForm_2600_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2700 = "fms_req_acquireForm_2700"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2700 = "fms_recv_acquireForm_2700"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2800 = "fms_req_acquireForm_2800"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2800 = "fms_recv_acquireForm_2800"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2900 = "fms_req_acquireForm_2900"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2900 = "fms_recv_acquireForm_2900"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_2900_1 = "fms_req_acquireForm_2900_1"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_2900_1 = "fms_recv_acquireForm_2900_1"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_3000 = "fms_req_acquireForm_3000"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_3000 = "fms_recv_acquireForm_3000"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_3100 = "fms_req_acquireForm_3100"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_3100 = "fms_recv_acquireForm_3100"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_3200 = "fms_req_acquireForm_3200"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_3200 = "fms_recv_acquireForm_3200"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_3300 = "fms_req_acquireForm_3300"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_3300 = "fms_recv_acquireForm_3300"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_BATCH = "fms_req_acquireForm_batch"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_BATCH = "fms_recv_acquireForm_batch"; +const std::string FORM_EVENT_REQ_ACQUIRE_FORM_BATCH_B = "fms_req_acquireForm_batch_b"; +const std::string FORM_EVENT_RECV_ACQUIRE_FORM_BATCH_B = "fms_recv_acquireForm_batch_b"; +const std::string FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH = "fms_req_acquireFormTemp_batch"; +const std::string FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH = "fms_recv_acquireFormTemp_batch"; +const std::string FORM_EVENT_REQ_CLEAR_FORM_BATCH = "fms_req_clearForm_batch"; +const std::string FORM_EVENT_RECV_CLEAR_FORM_BATCH = "fms_recv_clearForm_batch"; + + +// Delete Form +const std::string FORM_EVENT_REQ_DELETE_FORM_0100 = "fms_req_deleteForm_0100"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0100 = "fms_recv_deleteForm_0100"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0200 = "fms_req_deleteForm_0200"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0200 = "fms_recv_deleteForm_0200"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0300 = "fms_req_deleteForm_0300"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0300 = "fms_recv_deleteForm_0300"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0400 = "fms_req_deleteForm_0400"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0400 = "fms_recv_deleteForm_0400"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0500 = "fms_req_deleteForm_0500"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0500 = "fms_recv_deleteForm_0500"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0600 = "fms_req_deleteForm_0600"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0600 = "fms_recv_deleteForm_0600"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0700 = "fms_req_deleteForm_0700"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0700 = "fms_recv_deleteForm_0700"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0800 = "fms_req_deleteForm_0800"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0800 = "fms_recv_deleteForm_0800"; +const std::string FORM_EVENT_REQ_DELETE_FORM_0900 = "fms_req_deleteForm_0900"; +const std::string FORM_EVENT_RECV_DELETE_FORM_0900 = "fms_recv_deleteForm_0900"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1000 = "fms_req_deleteForm_1000"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1000 = "fms_recv_deleteForm_1000"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1100 = "fms_req_deleteForm_1100"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1100 = "fms_recv_deleteForm_1100"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1200 = "fms_req_deleteForm_1200"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1200 = "fms_recv_deleteForm_1200"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1201 = "fms_req_deleteForm_1201"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1201 = "fms_recv_deleteForm_1201"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1400 = "fms_req_deleteForm_1400"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1400 = "fms_recv_deleteForm_1400"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1401 = "fms_req_deleteForm_1401"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1401 = "fms_recv_deleteForm_1401"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1500 = "fms_req_deleteForm_1500"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1500 = "fms_recv_deleteForm_1500"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1501 = "fms_req_deleteForm_1501"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1501 = "fms_recv_deleteForm_1501"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1502 = "fms_req_deleteForm_1502"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1502 = "fms_recv_deleteForm_1502"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1600 = "fms_req_deleteForm_1600"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1600 = "fms_recv_deleteForm_1600"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1601 = "fms_req_deleteForm_1601"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1601 = "fms_recv_deleteForm_1601"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1602 = "fms_req_deleteForm_1602"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1602 = "fms_recv_deleteForm_1602"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1700 = "fms_req_deleteForm_1700"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1700 = "fms_recv_deleteForm_1700"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1701 = "fms_req_deleteForm_1701"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1701 = "fms_recv_deleteForm_1701"; +const std::string FORM_EVENT_REQ_DELETE_FORM_1702 = "fms_req_deleteForm_1702"; +const std::string FORM_EVENT_RECV_DELETE_FORM_1702 = "fms_recv_deleteForm_1702"; +// OnDelete +const std::string COMMON_EVENT_ON_DELETE = "usual.event.ondelete"; +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +// Release Form +const std::string FORM_EVENT_REQ_RELEASE_FORM_0100 = "fms_req_releaseForm_0100"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0100 = "fms_recv_releaseForm_0100"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0200 = "fms_req_releaseForm_0200"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0200 = "fms_recv_releaseForm_0200"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0300 = "fms_req_releaseForm_0300"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0300 = "fms_recv_releaseForm_0300"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0400 = "fms_req_releaseForm_0400"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0400 = "fms_recv_releaseForm_0400"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0500 = "fms_req_releaseForm_0500"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0500 = "fms_recv_releaseForm_0500"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0600 = "fms_req_releaseForm_0600"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0600 = "fms_recv_releaseForm_0600"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0700 = "fms_req_releaseForm_0700"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0700 = "fms_recv_releaseForm_0700"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0800 = "fms_req_releaseForm_0800"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0800 = "fms_recv_releaseForm_0800"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_0900 = "fms_req_releaseForm_0900"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_0900 = "fms_recv_releaseForm_0900"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_1000 = "fms_req_releaseForm_1000"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_1000 = "fms_recv_releaseForm_1000"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_1100 = "fms_req_releaseForm_1100"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_1100 = "fms_recv_releaseForm_1100"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_1200 = "fms_req_releaseForm_1200"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_1200 = "fms_recv_releaseForm_1200"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_1300 = "fms_req_releaseForm_1300"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_1300 = "fms_recv_releaseForm_1300"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_1400 = "fms_req_releaseForm_1400"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_1400 = "fms_recv_releaseForm_1400"; +const std::string FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL = "fms_req_releaseForm_common_del"; +const std::string FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL = "fms_recv_releaseForm_common_del"; + +// Stress Test +const std::string FORM_EVENT_REQ_STRESS_TEST_0100 = "fms_req_stressTest_0100"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0100 = "fms_recv_stressTest_0100"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0100_01 = "fms_req_stressTest_0100_01"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0100_01 = "fms_recv_stressTest_0100_01"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0200 = "fms_req_stressTest_0200"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0200 = "fms_recv_stressTest_0200"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0200_01 = "fms_req_stressTest_0200_01"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0200_01 = "fms_recv_stressTest_0200_01"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0200_02 = "fms_req_stressTest_0200_02"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0200_02 = "fms_recv_stressTest_0200_02"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0200_03 = "fms_req_stressTest_0200_03"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0200_03 = "fms_recv_stressTest_0200_03"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0300 = "fms_req_stressTest_0300"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0300 = "fms_recv_stressTest_0300"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0300_01 = "fms_req_stressTest_0300_01"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0300_01 = "fms_recv_stressTest_0300_01"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0300_02 = "fms_req_stressTest_0300_02"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0300_02 = "fms_recv_stressTest_0300_02"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0400 = "fms_req_stressTest_0400"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0400 = "fms_recv_stressTest_0400"; +const std::string FORM_EVENT_REQ_STRESS_TEST_0500 = "fms_req_stressTest_0500"; +const std::string FORM_EVENT_RECV_STRESS_TEST_0500 = "fms_recv_stressTest_0500"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1100 = "fms_req_stressTest_1100"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1100 = "fms_recv_stressTest_1100"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1100_01 = "fms_req_stressTest_1100_01"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1100_01 = "fms_recv_stressTest_1100_01"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1100_02 = "fms_req_stressTest_1100_02"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1100_02 = "fms_recv_stressTest_1100_02"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1100_03 = "fms_req_stressTest_1100_03"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1100_03 = "fms_recv_stressTest_1100_03"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1300 = "fms_req_stressTest_1300"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1300 = "fms_recv_stressTest_1300"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1300_01 = "fms_req_stressTest_1300_01"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1300_01 = "fms_recv_stressTest_1300_01"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1300_02 = "fms_req_stressTest_1300_02"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1300_02 = "fms_recv_stressTest_1300_02"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1300_03 = "fms_req_stressTest_1300_03"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1300_03 = "fms_recv_stressTest_1300_03"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1700 = "fms_req_stressTest_1700"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1700 = "fms_recv_stressTest_1700"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1700_01 = "fms_req_stressTest_1700_01"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1700_01 = "fms_recv_stressTest_1700_01"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1700_02 = "fms_req_stressTest_1700_02"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1700_02 = "fms_recv_stressTest_1700_02"; +const std::string FORM_EVENT_REQ_STRESS_TEST_1800 = "fms_req_stressTest_1800"; +const std::string FORM_EVENT_RECV_STRESS_TEST_1800 = "fms_recv_stressTest_1800"; + +// CommonA(acquire one normal form) +const std::string FORM_EVENT_REQ_ONE_NORMAL_FORM = "fms_req_one_normal_form"; +const std::string FORM_EVENT_RECV_ONE_NORMAL_FORM = "fms_recv_one_normal_form"; +const std::string FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL = "fms_req_one_normal_form_del"; +const std::string FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL = "fms_recv_one_normal_form_del"; + +// CommonB(acquire one normal form) +const std::string FORM_EVENT_REQ_ONE_NORMAL_FORM_B = "fms_req_one_normal_form_b"; +const std::string FORM_EVENT_RECV_ONE_NORMAL_FORM_B = "fms_recv_one_normal_form_b"; +const std::string FORM_EVENT_REQ_ONE_NORMAL_FORM_B_DEL = "fms_req_one_normal_form_b_del"; +const std::string FORM_EVENT_RECV_ONE_NORMAL_FORM_B_DEL = "fms_recv_one_normal_form_b_del"; + +// Performance Test +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_0100 = "fms_req_performanceTest_0100"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_0100 = "fms_recv_performanceTest_0100"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_0200 = "fms_req_performanceTest_0200"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_0200 = "fms_recv_performanceTest_0200"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_0300 = "fms_req_performanceTest_0300"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_0300 = "fms_recv_performanceTest_0300"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_0400 = "fms_req_performanceTest_0400"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_0400 = "fms_recv_performanceTest_0400"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_0500 = "fms_req_performanceTest_0500"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_0500 = "fms_recv_performanceTest_0500"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_0600 = "fms_req_performanceTest_0600"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_0600 = "fms_recv_performanceTest_0600"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_0700 = "fms_req_performanceTest_0700"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_0700 = "fms_recv_performanceTest_0700"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_1300 = "fms_req_performanceTest_1300"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_1300 = "fms_recv_performanceTest_1300"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_1400 = "fms_req_performanceTest_1400"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_1400 = "fms_recv_performanceTest_1400"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_1500 = "fms_req_performanceTest_1500"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_1500 = "fms_recv_performanceTest_1500"; +const std::string FORM_EVENT_REQ_PERFORMANCE_TEST_1600 = "fms_req_performanceTest_1600"; +const std::string FORM_EVENT_RECV_PERFORMANCE_TEST_1600 = "fms_recv_performanceTest_1600"; + +// Self-Starting Test +const std::string FORM_EVENT_REQ_SELF_STARTING_TEST_0100 = "fms_req_selfStartingTest_0100"; +const std::string FORM_EVENT_RECV_SELF_STARTING_TEST_0100 = "fms_recv_selfStartingTest_0100"; +const std::string FORM_EVENT_REQ_SELF_STARTING_TEST_0200 = "fms_req_selfStartingTest_0200"; +const std::string FORM_EVENT_RECV_SELF_STARTING_TEST_0200 = "fms_recv_selfStartingTest_0200"; +const std::string FORM_EVENT_REQ_SELF_STARTING_TEST_0300 = "fms_req_selfStartingTest_0300"; +const std::string FORM_EVENT_RECV_SELF_STARTING_TEST_0300 = "fms_recv_selfStartingTest_0300"; + +// common event data code +const int EVENT_CODE_100 = 100; +const int EVENT_CODE_101 = 101; +const int EVENT_CODE_102 = 102; +const int EVENT_CODE_103 = 103; +const int EVENT_CODE_200 = 200; +const int EVENT_CODE_201 = 201; +const int EVENT_CODE_202 = 202; +const int EVENT_CODE_203 = 203; +const int EVENT_CODE_204 = 204; +const int EVENT_CODE_205 = 205; +const int EVENT_CODE_300 = 300; +const int EVENT_CODE_301 = 301; +const int EVENT_CODE_302 = 302; +const int EVENT_CODE_303 = 303; +const int EVENT_CODE_304 = 304; +const int EVENT_CODE_400 = 400; +const int EVENT_CODE_401 = 401; +const int EVENT_CODE_402 = 402; +const int EVENT_CODE_500 = 500; +const int EVENT_CODE_501 = 501; +const int EVENT_CODE_502 = 502; +const int EVENT_CODE_600 = 600; +const int EVENT_CODE_700 = 700; +const int EVENT_CODE_800 = 800; +const int EVENT_CODE_900 = 900; +const int EVENT_CODE_999 = 999; +const int EVENT_CODE_1000 = 1000; +const int EVENT_CODE_1100 = 1100; +const int EVENT_CODE_1101 = 1101; +const int EVENT_CODE_1102 = 1102; +const int EVENT_CODE_1103 = 1103; +const int EVENT_CODE_1104 = 1104; +const int EVENT_CODE_1105 = 1105; +const int EVENT_CODE_1200 = 1200; +const int EVENT_CODE_1201 = 1201; +const int EVENT_CODE_1234 = 1234; +const int EVENT_CODE_1300 = 1300; +const int EVENT_CODE_1301 = 1301; +const int EVENT_CODE_1302 = 1302; +const int EVENT_CODE_1303 = 1303; +const int EVENT_CODE_1304 = 1304; +const int EVENT_CODE_1305 = 1305; +const int EVENT_CODE_1400 = 1400; +const int EVENT_CODE_1401 = 1401; +const int EVENT_CODE_1500 = 1500; +const int EVENT_CODE_1510 = 1510; +const int EVENT_CODE_1511 = 1511; +const int EVENT_CODE_1600 = 1600; +const int EVENT_CODE_1601 = 1601; +const int EVENT_CODE_1610 = 1610; +const int EVENT_CODE_1611 = 1611; +const int EVENT_CODE_1700 = 1700; +const int EVENT_CODE_1701 = 1701; +const int EVENT_CODE_1702 = 1702; +const int EVENT_CODE_1800 = 1800; +const int EVENT_CODE_1801 = 1801; +const int EVENT_CODE_1802 = 1802; +const int EVENT_CODE_1810 = 1810; +const int EVENT_CODE_1811 = 1811; +const int EVENT_CODE_1820 = 1820; +const int EVENT_CODE_1821 = 1821; +const int EVENT_CODE_1830 = 1830; +const int EVENT_CODE_1831 = 1831; +const int EVENT_CODE_1900 = 1900; +const int EVENT_CODE_1901 = 1901; +const int EVENT_CODE_2000 = 2000; +const int EVENT_CODE_2100 = 2100; +const int EVENT_CODE_2200 = 2200; +const int EVENT_CODE_2300 = 2300; +const int EVENT_CODE_2400 = 2400; +const int EVENT_CODE_2401 = 2401; +const int EVENT_CODE_2410 = 2410; +const int EVENT_CODE_2500 = 2500; +const int EVENT_CODE_2600 = 2600; +const int EVENT_CODE_2610 = 2610; +const int EVENT_CODE_2611 = 2611; +const int EVENT_CODE_2700 = 2700; +const int EVENT_CODE_2800 = 2800; +const int EVENT_CODE_2900 = 2900; +const int EVENT_CODE_2901 = 2901; +const int EVENT_CODE_2910 = 2910; +const int EVENT_CODE_2911 = 2911; +const int EVENT_CODE_3000 = 3000; +const int EVENT_CODE_3100 = 3100; +const int EVENT_CODE_3101 = 3101; +const int EVENT_CODE_3200 = 3200; +const int EVENT_CODE_3300 = 3300; +const int EVENT_CODE_3301 = 3301; + +const int EVENT_CODE_BATCH = 9000; +const int EVENT_CODE_BATCH_B = 9010; +const int EVENT_CODE_TEMP_BATCH = 9020; +const int EVENT_CODE_CLEAR_BATCH = 9030; + +const int EVENT_CODE_TEMP = 9900; +const int EVENT_CODE_TEMP_1 = 9901; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_COMMON_INFO_H \ No newline at end of file diff --git a/test/systemtest/common/fms/common/include/install_tool_status_receiver.h b/test/systemtest/common/fms/common/include/install_tool_status_receiver.h new file mode 100644 index 0000000000000000000000000000000000000000..549613b3d6ece3e7ed8bed23b822c016cc990b8c --- /dev/null +++ b/test/systemtest/common/fms/common/include/install_tool_status_receiver.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 INSTALL_TOOL_STATUS_RECEIVER_H +#define INSTALL_TOOL_STATUS_RECEIVER_H + +#include "form_event.h" + +namespace OHOS { +namespace STtools { +using namespace OHOS::AppExecFwk; +class InstallToolStatusReceiver : public StatusReceiverHost { +public: + InstallToolStatusReceiver(); + virtual ~InstallToolStatusReceiver() override; + virtual void OnStatusNotify(const int progress) override; + virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override; + static int TestWaitCompleted(FormEvent &event, const std::string eventName, const int code, const int timeout = 10); + static void TestCompleted(FormEvent &event, const std::string &eventName, const int code); + FormEvent event_ = STtools::FormEvent(); + +private: + int iProgress_ = 0; + DISALLOW_COPY_AND_MOVE(InstallToolStatusReceiver); +}; +InstallToolStatusReceiver::InstallToolStatusReceiver() +{ + std::cout << "create status receiver instance" << std::endl; +} + +InstallToolStatusReceiver::~InstallToolStatusReceiver() +{ + std::cout << "destroy status receiver instance" << std::endl; +} + +void InstallToolStatusReceiver::OnStatusNotify(const int progress) +{ + iProgress_ = progress; + std::cout << "destroy status receiver instance" << progress << std::endl; +} + +void InstallToolStatusReceiver::OnFinished(const int32_t resultCode, const std::string &resultMsg) +{ + std::cout << "on finished result is " << resultCode << " " << resultMsg << std::endl; + TestCompleted(event_, resultMsg, resultCode); +} + +int InstallToolStatusReceiver::TestWaitCompleted( + FormEvent &event, const std::string eventName, const int code, const int timeout) +{ + std::cout << "TestWaitCompleted " << eventName << std::endl; + return SystemTestFormUtil::WaitCompleted(event, eventName, code, timeout); +} +void InstallToolStatusReceiver::TestCompleted(FormEvent &event, const std::string &eventName, const int code) +{ + std::cout << "TestCompleted " << eventName << std::endl; + SystemTestFormUtil::Completed(event, eventName, code); + return; +} +} // namespace AppExecFwk +} // namespace OHOS +#endif // INSTALL_TOOL_STATUS_RECEIVER_H \ No newline at end of file diff --git a/test/systemtest/common/fms/common/include/system_test_form_util.h b/test/systemtest/common/fms/common/include/system_test_form_util.h new file mode 100644 index 0000000000000000000000000000000000000000..2e4f801581eb130a7a32053550d293d204accfe5 --- /dev/null +++ b/test/systemtest/common/fms/common/include/system_test_form_util.h @@ -0,0 +1,350 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 SYSTEM_TEST_FORM_UTIL_H +#define SYSTEM_TEST_FORM_UTIL_H + +#include +#include +#include +#include + +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "bundle_installer_interface.h" +#include "bundle_mgr_interface.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_event.h" +#include "form_mgr_interface.h" +#include "hilog_wrapper.h" +#include "iremote_proxy.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace STtools { +namespace { +using vector_str = std::vector; +using MAP_STR_STR = std::map; +} // namespace +class SystemTestFormUtil { +public: + SystemTestFormUtil() = default; + ~SystemTestFormUtil() = default; + + static std::shared_ptr GetInstance(); + static void DestroyInstance(); + + /** + * + * @param {string} eventName : Sent FormEvent Name + * @param {int} code : Sent Code + * @param {string} data : Sent Data + * @Introduction: Sent FormEvent + */ + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + + /** + * + * @param {vector} hapNames : container containing multiple hap names + * @Introduction: use bm install multiple hap + */ + static void InstallHaps(vector_str &hapNames); + + /** + * + * @param {vector} bundleNames : container containing multiple bundle names + * @Introduction: use bm install multiple bundle + */ + static void UninstallBundle(vector_str &bundleNames); + + /** + * + * @param {string} serviceName : process name + * @Introduction: kill process + */ + static void KillService(const std::string &serviceName); + + /** + * + * @param {string} serviceName : executable file name + * @param {time_t} delay : Waiting time for executable to start(milliseconds) + * @Introduction: start executable file + */ + static void StartService(const std::string &serviceName, const time_t &delay = 0); + + /** + * + * @param {vector} bundleNames : Container Containing Multiple Bundle Names + * @Introduction: start executable file + */ + static void KillBundleProcess(vector_str &bundleNames); + + /** + * + * @Introduction: Get Ability manager Service. + */ + static sptr GetAbilityManagerService(); + + /** + * + * @Introduction: Get App manager Service. + */ + static sptr GetAppMgrService(); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {sptr} abilityMs : Ability Manager Service ptr + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: start ability + */ + static ErrCode StartAbility( + const AAFwk::Want &want, sptr &abilityMs, const time_t &delay = 0); + + /** + * + * @param {string} eventName : Sent FormEvent Name + * @param {int} code : Sent Code + * @param {string} data : Sent Data + * @Introduction: Sent FormEvent to terminate app + */ + static bool StopAbility(const std::string &eventName, const int &code, const std::string &data); + /** + * + * @param {string} deviceId : Device ID + * @param {string} abilityName : Ability Name + * @param {string} bundleName : Bundle Name + * @param {MAP_STR_STR} params : Params (SetParam) + * @Introduction: Great Want + */ + static AAFwk::Want MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, MAP_STR_STR params = {}); + + /** + * + * @param {string} deviceId : Device ID + * @param {string} abilityName : Ability Name + * @param {string} bundleName : Bundle Name + * @param {vector_str} params : Params (SetParam) + * @Introduction: Great Want + */ + static AAFwk::Want MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, vector_str params = {}); + + /** + * + * @param {int64_t} id : Ability Record ID + * @param {sptr} abilityMs : Ability Manager Service ptr + * @Introduction: Get Top AbilityRecord ID + */ + static ErrCode GetTopAbilityRecordId(int64_t &id, sptr &abilityMs); + + /** + * + * @param {shared_ptr} runningProcessInfo : Process Info + * @param {sptr} appMs : App Manager ptr + * @param {time_t} delay : Waiting time for ability to Get Process Info (milliseconds) + * @Introduction: Get Top AbilityRecord ID + */ + static ErrCode GetRunningProcessInfo(std::vector &runningProcessInfo, + sptr &appMs, const time_t &delay = 0); + + /** + * + * @param {string} appName : app Name + * @param {sptr} appMs : App Manager ptr + * @param {time_t} delay : Waiting time for ability to KillApplication (milliseconds) + * @Introduction: Get Top AbilityRecord ID + */ + static ErrCode KillApplication( + const std::string &appName, sptr &appMs, const time_t &delay = 0); + + /** + * + * @param {string} processName : processName + * @param {sptr} appMs : App Manager ptr + * @param {time_t} delay : Waiting time for ability to GetAppProcessInfo (milliseconds) + * @Introduction: Get Top AbilityRecord ID + */ + static AppExecFwk::RunningProcessInfo GetAppProcessInfoByName( + const std::string &processName, sptr &appMs, const time_t &delay = 0); + + /** + * + * @param {FormEvent} event : FormEvent Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @param {int} timeout : Time of wait (seconds) + * @Introduction: Judge whether the event is received in the event queue, if not, wait + */ + static int WaitCompleted( + STtools::FormEvent &event, const std::string &eventName, const int code, const int timeout = 15); + + /** + * + * @param {FormEvent} event : FormEvent Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @Introduction: Compare the received events, if not, join the event queue. + */ + static void Completed(STtools::FormEvent &event, const std::string &eventName, const int code); + + /** + * + * @param {FormEvent} event : FormEvent Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @param {string} data : The data of the event to wait for. + * @Introduction: Compare the received events, if not, join the event queue. + */ + static void Completed(STtools::FormEvent &event, const std::string &eventName, const int code, + const std::string &data); + + /** + * + * @param {FormEvent} event : FormEvent Class Object + * @Introduction: Clean wait event. + */ + static void CleanMsg(STtools::FormEvent &event); + + /** + * + * @param {FormEvent} event : FormEvent Class Object + * @param {string} eventName : The name of the event to wait for. + * @param {int} code : The code of the event to wait for. + * @Introduction: get the event data. + */ + static std::string GetData(STtools::FormEvent &event, const std::string &eventName, const int code); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {sptr} connect : Callback + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: connect ability + */ + static ErrCode ConnectAbility(const AAFwk::Want &want, const sptr &connect, + const sptr &callerToken, unsigned int usec = 0); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {sptr} connect : Callback + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: disconnect ability + */ + static ErrCode DisconnectAbility(const sptr &connect, unsigned int usec = 0); + + /** + * + * @param {Want} want : The want of the ability to start. + * @param {time_t} delay : Waiting time for ability to start (milliseconds) + * @Introduction: stop service ability + */ + static ErrCode StopServiceAbility(const AAFwk::Want &want, unsigned int usec = 0); + + /** + * Remove the specified mission stack by stack id + * + * @param id. + * @param {sptr} abilityMs : Ability Manager Service ptr + * @param {time_t} delay : Waiting time for ability to GetAppProcessInfo (milliseconds) + * @return Returns ERR_OK on success, others on failure. + */ + static int RemoveStack(int id, sptr &abilityMs, const time_t &backHmoeDelay = 0, + const time_t &removeDelay = 0); + + /** + * + * @param {string} bundleFilePath : Hap File Name + * @param {AppExecFwk::InstallFlag} installFlag : install flag + * @Introduction: use bms install + */ + static void Install( + const std::string &bundleFilePath, const AppExecFwk::InstallFlag installFlag = AppExecFwk::InstallFlag::NORMAL); + + /** + * + * @param {string} bundleName : bundleName + * @Introduction: use bm uninstall bundleName + */ + static void Uninstall(const std::string &bundleName); + + /** + * @brief Query all of form storage infos. + * @return Returns all of form storage infos. + */ + static std::string QueryStorageFormInfos(); + /** + * @brief Query form infos by bundleName. + * @param bundleName BundleName. + * @return Returns form infos. + */ + static std::string QueryFormInfoByBundleName(const std::string& bundleName); + /** + * @brief Query form infos by form id. + * @param formId The id of the form. + * @return form infos. + */ + static std::string QueryFormInfoByFormId(const std::int64_t formId); + /** + * @brief Query form timer service by form id. + * @param formId The id of the form. + * @return Returns form timer service. + */ + static std::string QueryFormTimerByFormId(const std::int64_t formId); + + /** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns forms count to add. + */ + static int BatchAddFormRecords(const AAFwk::Want &want); + /** + * @brief Clear form records for st limit value test. + * @return Returns forms count to delete. + */ + static int ClearFormRecords(); +private: + /** + * + * @Introduction: get bundleManger object + */ + static sptr GetBundleMgrProxy(); + + /** + * + * @Introduction: get bundleInstaller object + */ + static sptr GetInstallerProxy(); + + /** + * @brief Get form manager service. + * @return Returns form manager servic remoteObject. + */ + static sptr GetFmsService(); + + static bool WriteInterfaceToken(MessageParcel &data); + static int GetStringInfo(AppExecFwk::IFormMgr::Message code, MessageParcel &data, std::string &stringInfo); + static int SendTransactCmd(AppExecFwk::IFormMgr::Message code, MessageParcel &data, MessageParcel &reply); + + static std::shared_ptr instance_; +}; +} // namespace STtools +} // namespace OHOS +#endif // SYSTEM_TEST_FORM_UTIL_H diff --git a/test/systemtest/common/fms/common/src/form_event.cpp b/test/systemtest/common/fms/common/src/form_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..082058567e050079e709fb7567c17129ad6fb667 --- /dev/null +++ b/test/systemtest/common/fms/common/src/form_event.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "form_event.h" + +namespace OHOS { +namespace STtools { +FormEvent::FormEvent() +{ + waiting_message_ = ""; + complete_message_.clear(); +} + +FormEvent::~FormEvent() +{ + waiting_message_ = ""; + std::vector tmp_vector; + tmp_vector.swap(complete_message_); + complete_message_.clear(); +} + +bool FormEvent::Compare() +{ + if (!waiting_message_.empty()) { + for (size_t i = 0; i < complete_message_.size(); i++) { + if (waiting_message_.compare(complete_message_.at(i)) == 0) { + complete_message_.erase(std::begin(complete_message_) + i, std::begin(complete_message_) + i + 1); + waiting_message_ = ""; + return true; + } + } + } + return false; +} + +int FormEvent::WaitingMessage(const std::string &message, int timeout_ms, bool locked) +{ + std::unique_lock lock(mutex_); + HILOG_INFO(" WaitingMessage: [%{public}s]", message.c_str()); + waiting_message_ = message; + if (Compare()) { + HILOG_INFO(" WaitingMessage: unlock [%{public}s]", message.c_str()); + return 0; + } + + if (locked) { + HILOG_INFO(" WaitingMessage: locked [%{public}s]", message.c_str()); + cv_.wait(lock); + return 0; + } + + if (cv_.wait_for(lock, std::chrono::seconds(timeout_ms)) == std::cv_status::timeout) { + HILOG_INFO("[%{public}s] waiting timeout", waiting_message_.c_str()); + waiting_message_ = ""; + return -1; + } + return 0; +} + +void FormEvent::CompleteMessage(const std::string &message) +{ + std::unique_lock lock(mutex_); + HILOG_INFO("CompleteMessage [%{public}s]", message.c_str()); + if (waiting_message_.compare(message) == 0) { + HILOG_INFO("Completed unlocked: [%{public}s]", message.c_str()); + waiting_message_ = ""; + cv_.notify_all(); + return; + } + HILOG_INFO("completed message: [%{public}s] does not equal waiting message", message.c_str()); + + complete_message_.push_back(message); + return; +} + +void FormEvent::CompleteMessage(const std::string &message, const std::string &data) +{ + std::unique_lock lock(mutex_); + HILOG_INFO("CompleteMessage [%{public}s]", message.c_str()); + message_data_[message] = data; + if (waiting_message_.compare(message) == 0) { + HILOG_INFO("Completed unlocked: [%{public}s]", message.c_str()); + waiting_message_ = ""; + cv_.notify_all(); + return; + } + HILOG_INFO("completed message: [%{public}s] does not equal waiting message", message.c_str()); + + complete_message_.push_back(message); + return; +} + +std::string FormEvent::GetData(const std::string &message) +{ + std::string data; + std::unique_lock lock(mutex_); + if (message_data_.find(message) != message_data_.end()) { + data = message_data_.at(message); + message_data_.erase(message); + } + return data; +} + +void FormEvent::Clean() +{ + HILOG_INFO("FormEvent::Clean()"); + std::unique_lock lock(mutex_); + waiting_message_ = ""; + complete_message_.clear(); + message_data_.clear(); +} +} // namespace STtools +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/common/src/system_test_form_util.cpp b/test/systemtest/common/fms/common/src/system_test_form_util.cpp new file mode 100755 index 0000000000000000000000000000000000000000..dd641b8f4d44e171c18700c83a8dd614544c0fc0 --- /dev/null +++ b/test/systemtest/common/fms/common/src/system_test_form_util.cpp @@ -0,0 +1,686 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "system_test_form_util.h" +#include "iservice_registry.h" +#include "status_receiver_host.h" +#include "install_tool_status_receiver.h" + +namespace OHOS { +namespace STtools { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; + +std::shared_ptr SystemTestFormUtil::instance_ = nullptr; + +bool SystemTestFormUtil::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +void SystemTestFormUtil::InstallHaps(vector_str &hapNames) +{ + for (auto hapName : hapNames) { + Install(hapName); + } +} + +void SystemTestFormUtil::UninstallBundle(vector_str &bundleNames) +{ + for (auto bundleName : bundleNames) { + Uninstall(bundleName); + } +} + +void SystemTestFormUtil::KillService(const std::string &serviceName) +{ + system(("kill -9 $(pidof " + serviceName + ") > /dev/null 2>&1").c_str()); +} + +void SystemTestFormUtil::StartService(const std::string &serviceName, const time_t &delay) +{ + system(("/system/bin/" + serviceName + "& > /dev/null 2>&1").c_str()); + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); +} + +void SystemTestFormUtil::KillBundleProcess(vector_str &bundleNames) +{ + for (std::string bundleName : bundleNames) { + KillService(bundleName); + } +} + +sptr SystemTestFormUtil::GetAbilityManagerService() +{ + sptr abilityMsObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (abilityMsObj == nullptr) { + HILOG_ERROR("failed to get ability manager service"); + return nullptr; + } + return iface_cast(abilityMsObj); +} + +sptr SystemTestFormUtil::GetAppMgrService() +{ + sptr appMsObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); + if (appMsObj == nullptr) { + HILOG_ERROR("failed to get app manager service"); + return nullptr; + } + return iface_cast(appMsObj); +} + +ErrCode SystemTestFormUtil::StartAbility(const Want &want, sptr &abilityMs, const time_t &delay) +{ + ErrCode result = OHOS::ERR_OK; + abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->StartAbility(want); + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + if (result == OHOS::ERR_OK) { + HILOG_INFO("start ability successfully."); + } else { + HILOG_INFO("failed to start ability."); + } + + return result; +} + +bool SystemTestFormUtil::StopAbility(const std::string &eventName, const int &code, const std::string &data) +{ + return PublishEvent(eventName, code, data); +} + +ErrCode SystemTestFormUtil::StopServiceAbility(const Want &want, unsigned int usec) +{ + ErrCode result = OHOS::ERR_OK; + + sptr abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->StopServiceAbility(want); + if (result == OHOS::ERR_OK) { + HILOG_INFO("stop service ability successfully."); + } else { + HILOG_INFO("failed to stop service ability."); + } + + return result; +} + +ErrCode SystemTestFormUtil::ConnectAbility(const Want &want, const sptr &connect, + const sptr &callerToken, unsigned int usec) +{ + ErrCode result = OHOS::ERR_OK; + + sptr abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->ConnectAbility(want, connect, callerToken); + if (result == OHOS::ERR_OK) { + HILOG_INFO("connect ability successfully."); + } else { + HILOG_INFO("failed to connect ability."); + } + + return result; +} + +ErrCode SystemTestFormUtil::DisconnectAbility(const sptr &connect, unsigned int usec) +{ + ErrCode result = OHOS::ERR_OK; + + sptr abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + + result = abilityMs->DisconnectAbility(connect); + if (result == OHOS::ERR_OK) { + HILOG_INFO("StopServiceAbility successfully."); + } else { + HILOG_INFO("failed to StopServiceAbility."); + } + + return result; +} + +Want SystemTestFormUtil::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + MAP_STR_STR params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +Want SystemTestFormUtil::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + vector_str params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + want.SetParam("operator", params); + return want; +} + +ErrCode SystemTestFormUtil::GetTopAbilityRecordId(int64_t &id, sptr &abilityMs) +{ + ErrCode result = OHOS::ERR_OK; + id = -1; + abilityMs = GetAbilityManagerService(); + if (abilityMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get ability manager service"); + return result; + } + StackInfo stackInfo; + abilityMs->GetAllStackInfo(stackInfo); + MissionStackInfo defaultMissionStack; + for (const auto &stackInfo : stackInfo.missionStackInfos) { + if (stackInfo.id == 1) { // DEFAULT_MISSION_STACK_ID = 1 + defaultMissionStack = stackInfo; + break; + } + } + if (!defaultMissionStack.missionRecords.empty() && + !defaultMissionStack.missionRecords.begin()->abilityRecordInfos.empty()) { + id = defaultMissionStack.missionRecords.begin()->abilityRecordInfos.begin()->id; + } + return result; +} + +ErrCode SystemTestFormUtil::GetRunningProcessInfo( + std::vector &runningProcessInfo, sptr &appMs, const time_t &delay) +{ + ErrCode result = ERR_OK; + appMs = GetAppMgrService(); + if (appMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get app manager service"); + return result; + } + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + result = appMs->GetAllRunningProcesses(runningProcessInfo); + if (result == ERR_OK) { + HILOG_INFO("get running process info successfully."); + } else { + HILOG_INFO("failed to get running process info."); + } + return result; +} + +ErrCode SystemTestFormUtil::KillApplication(const std::string &appName, sptr &appMs, const time_t &delay) +{ + ErrCode result = ERR_OK; + appMs = GetAppMgrService(); + if (appMs == nullptr) { + result = OHOS::ERR_INVALID_VALUE; + HILOG_ERROR("failed to get app manager service"); + return result; + } + result = appMs->GetAmsMgr()->KillApplication(appName); + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + if (result == ERR_OK) { + HILOG_INFO("kill application:%{public}s successfully.", appName.c_str()); + } else { + HILOG_INFO("failed to kill application:%{public}s.", appName.c_str()); + } + return result; +} + +RunningProcessInfo SystemTestFormUtil::GetAppProcessInfoByName( + const std::string &processName, sptr &appMs, const time_t &delay) +{ + RunningProcessInfo appProcessInfo; + appProcessInfo.pid_ = 0; + std::vector runningProcessInfo; + if (ERR_OK == GetRunningProcessInfo(runningProcessInfo, appMs, delay)) { + for (const auto &info : runningProcessInfo) { + if (processName == info.processName_) { + appProcessInfo = info; + } + } + } + return appProcessInfo; +} + +int SystemTestFormUtil::WaitCompleted(FormEvent &event, const std::string &eventName, const int code, const int timeout) +{ + HILOG_INFO("WaitCompleted"); + return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); +} + +void SystemTestFormUtil::Completed(FormEvent &event, const std::string &eventName, const int code) +{ + HILOG_INFO("Completed"); + return event.CompleteMessage(std::to_string(code) + eventName); +} + +void SystemTestFormUtil::Completed(FormEvent &event, const std::string &eventName, const int code, + const std::string &data) +{ + HILOG_INFO("SystemTestFormUtil::Completed"); + return event.CompleteMessage(std::to_string(code) + eventName, data); +} + +std::string SystemTestFormUtil::GetData(FormEvent &event, const std::string &eventName, const int code) +{ + HILOG_INFO("SystemTestFormUtil::GetData"); + return event.GetData(std::to_string(code) + eventName); +} + +void SystemTestFormUtil::CleanMsg(FormEvent &event) +{ + HILOG_INFO("CleanMsg"); + return event.Clean(); +} + +int SystemTestFormUtil::RemoveStack( + int id, sptr &abilityMs, const time_t &backHmoeDelay, const time_t &removeDelay) +{ + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + StartAbility(wantEntity, abilityMs); + std::this_thread::sleep_for(std::chrono::milliseconds(backHmoeDelay)); + if (!abilityMs) { + HILOG_INFO("RemoveStack abilityMs nullptr"); + return OHOS::ERR_INVALID_VALUE; + } + int result = abilityMs->RemoveStack(id); + std::this_thread::sleep_for(std::chrono::milliseconds(removeDelay)); + return result; +} + +const std::string MSG_SUCCESS = "[SUCCESS]"; +void SystemTestFormUtil::Install(const std::string &bundleFilePath, const InstallFlag installFlag) +{ + std::string bundlePath = "/data/vendor/" + bundleFilePath + ".hap"; + std::string installMsg = ""; + sptr installerProxy = GetInstallerProxy(); + if (!installerProxy) { + std::cout << "get bundle installer Failure." << std::endl; + installMsg = "Failure"; + return; + } + + InstallParam installParam; + installParam.installFlag = installFlag; + sptr statusReceiver(new (std::nothrow) InstallToolStatusReceiver()); + if (statusReceiver == nullptr) { + std::cout << "get statusReceiver Failure." << std::endl; + return; + } + bool installResult = installerProxy->Install(bundlePath, installParam, statusReceiver); + if (!installResult) { + installMsg = "Failure"; + return; + } + if (InstallToolStatusReceiver::TestWaitCompleted(statusReceiver->event_, MSG_SUCCESS, 0) == 0) { + installMsg = "Success"; + } else { + installMsg = "Failure"; + } +} + +void SystemTestFormUtil::Uninstall(const std::string &bundleName) +{ + std::string uninstallMsg = ""; + sptr installerProxy = GetInstallerProxy(); + if (!installerProxy) { + std::cout << "get bundle installer Failure." << std::endl; + uninstallMsg = "Failure"; + return; + } + if (bundleName.empty()) { + std::cout << "bundelname is null." << std::endl; + uninstallMsg = "Failure"; + } else { + sptr statusReceiver(new (std::nothrow) InstallToolStatusReceiver()); + if (statusReceiver == nullptr) { + std::cout << "get statusReceiver Failure." << std::endl; + uninstallMsg = "Failure"; + return; + } + InstallParam installParam; + bool uninstallResult = installerProxy->Uninstall(bundleName, installParam, statusReceiver); + if (!uninstallResult) { + std::cout << "Uninstall Failure." << std::endl; + uninstallMsg = "Failure"; + return; + } + if (InstallToolStatusReceiver::TestWaitCompleted(statusReceiver->event_, MSG_SUCCESS, 0) == 0) { + uninstallMsg = "Success"; + } else { + uninstallMsg = "Failure"; + } + } +} + +sptr SystemTestFormUtil::GetInstallerProxy() +{ + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + std::cout << "bundle mgr proxy is nullptr." << std::endl; + return nullptr; + } + + sptr installerProxy = bundleMgrProxy->GetBundleInstaller(); + if (!installerProxy) { + std::cout << "fail to get bundle installer proxy" << std::endl; + return nullptr; + } + std::cout << "get bundle installer proxy success." << std::endl; + return installerProxy; +} + +sptr SystemTestFormUtil::GetBundleMgrProxy() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + std::cout << "fail to get system ability mgr." << std::endl; + return nullptr; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + std::cout << "fail to get bundle manager proxy." << std::endl; + return nullptr; + } + + std::cout << "get bundle manager proxy success." << std::endl; + return iface_cast(remoteObject); +} + +/** + * @brief Query all of form storage infos. + * @return Returns all of form storage infos. + */ +std::string SystemTestFormUtil::QueryStorageFormInfos() +{ + std::cout << "QueryStorageFormInfos called." << std::endl; + + std::string formInfos = ""; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + std::cout << "QueryStorageFormInfos, failed to write interface token." << std::endl; + return "QueryStorageFormInfos, failed to write interface token."; + } + + int result = GetStringInfo(AppExecFwk::IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS, data, formInfos); + if (result != ERR_OK) { + std::cout << "QueryStorageFormInfos, failed to query form info." << std::endl; + } + + std::cout << "QueryStorageFormInfos end." << std::endl; + + return formInfos; +} +/** + * @brief Query form infos by bundleName. + * @param bundleName BundleName. + * @return Returns form infos. + */ +std::string SystemTestFormUtil::QueryFormInfoByBundleName(const std::string& bundleName) +{ + std::cout << "QueryFormInfoByBundleName called." << std::endl; + + std::string formInfos = ""; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + std::cout << "QueryFormInfoByBundleName, failed to write interface token." << std::endl; + return "QueryFormInfoByBundleName, failed to write interface token."; + } + + if (!data.WriteString(bundleName)) { + std::cout << "QueryFormInfoByBundleName, failed to write bundleName." << std::endl; + return "QueryFormInfoByBundleName, failed to write bundleName."; + } + + int result = GetStringInfo(AppExecFwk::IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME, data, formInfos); + if (result != ERR_OK) { + std::cout << "QueryFormInfoByBundleName, failed to query form info." << std::endl; + } + + std::cout << "QueryFormInfoByBundleName end." << std::endl; + + return formInfos; +} +/** + * @brief Query form infos by form id. + * @param formId The id of the form. + * @return Returns form infos. + */ +std::string SystemTestFormUtil::QueryFormInfoByFormId(const std::int64_t formId) +{ + std::cout << "QueryFormInfoByFormId called." << std::endl; + + std::string formInfo = ""; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + std::cout << "QueryFormInfoByFormId, failed to write interface token." << std::endl; + return "QueryFormInfoByFormId, failed to write interface token."; + } + if (!data.WriteInt64(formId)) { + std::cout << "QueryFormInfoByFormId, failed to write formId." << std::endl; + return "QueryFormInfoByFormId, failed to write formId."; + } + + int result = GetStringInfo(AppExecFwk::IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo); + if (result != ERR_OK) { + std::cout << "QueryFormInfoByFormId, failed to query form info." << std::endl; + } + + std::cout << "QueryFormInfoByFormId end." << std::endl; + + return formInfo; +} +/** + * @brief Query form timer service by form id. + * @param formId The id of the form. + * @return Returns form timer service. + */ +std::string SystemTestFormUtil::QueryFormTimerByFormId(const std::int64_t formId) +{ + std::cout << "QueryFormTimerByFormId called." << std::endl; + + std::string isTimingService; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + std::cout << "QueryFormTimerByFormId, failed to write interface token." << std::endl; + return "QueryFormTimerByFormId, failed to write interface token."; + } + if (!data.WriteInt64(formId)) { + std::cout << "QueryFormTimerByFormId, failed to write formId." << std::endl; + return "QueryFormTimerByFormId, failed to write formId."; + } + + int result = GetStringInfo(AppExecFwk::IFormMgr::Message::FORM_MGR_FORM_TIMER_INFO_BY_ID, data, isTimingService); + if (result != ERR_OK) { + std::cout << "QueryFormTimerByFormId, failed to query timer info." << std::endl; + } + + std::cout << "QueryFormTimerByFormId end." << std::endl; + + return isTimingService; +} + +/** + * @brief Batch add forms to form records for st limit value test. + * @param want The want of the form to add. + * @return Returns forms count to add. + */ +int SystemTestFormUtil::BatchAddFormRecords(const AAFwk::Want &want) +{ + sptr remoteObject = GetFmsService(); + if (!remoteObject) { + std::cout << "SendTransactCmd, failed to get remote object." << std::endl; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + + MessageParcel data; + if (!WriteInterfaceToken(data)) { + std::cout << "BatchAddFormRecords, failed to write interface token." << std::endl; + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + std::cout << "BatchAddFormRecords, failed to write want." << std::endl; + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = remoteObject->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_BATCH_ADD_FORM_RECORDS_ST), + data, + reply, + option); + if (error != ERR_OK) { + std::cout << "BatchAddFormRecords, failed to SendRequest." << std::endl; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} + +/** + * @brief Clear form records for st limit value test. + * @return Returns forms count to delete. + */ +int SystemTestFormUtil::ClearFormRecords() +{ + sptr remoteObject = GetFmsService(); + if (!remoteObject) { + std::cout << "SendTransactCmd, failed to get remote object." << std::endl; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + + MessageParcel data; + if (!WriteInterfaceToken(data)) { + std::cout << "BatchAddFormRecords, failed to write interface token." << std::endl; + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = remoteObject->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_CLEAR_FORM_RECORDS_ST), + data, + reply, + option); + if (error != ERR_OK) { + std::cout << "ClearFormRecords, failed to SendRequest." << std::endl; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + return reply.ReadInt32(); +} +bool SystemTestFormUtil::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(AppExecFwk::IFormMgr::GetDescriptor())) { + std::cout << "WriteInterfaceToken, failed to write interface token." << std::endl; + return false; + } + return true; +} +int SystemTestFormUtil::GetStringInfo(AppExecFwk::IFormMgr::Message code, MessageParcel &data, std::string &stringInfo) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + std::cout << "GetStringInfo, failed to read reply result." << std::endl; + return error; + } + std::vector stringInfoList; + if (!reply.ReadStringVector(&stringInfoList)) { + std::cout << "GetStringInfo, failed to read string vector from reply." << std::endl; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + if (stringInfoList.empty()) { + std::cout << "GetStringInfo, No string info." << std::endl; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + for (auto &info : stringInfoList) { + stringInfo += info; + } + std::cout << "GetStringInfo end." << std::endl; + return ERR_OK; +} +int SystemTestFormUtil::SendTransactCmd(AppExecFwk::IFormMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + sptr remoteObject = GetFmsService(); + if (!remoteObject) { + std::cout << "SendTransactCmd, failed to get remote object." << std::endl; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + + MessageOption option(MessageOption::TF_SYNC); + int32_t result = remoteObject->SendRequest(static_cast(code), data, reply, option); + if (result != ERR_OK) { + std::cout << "SendTransactCmd, failed to SendRequest." << std::endl; + return result; + } + return ERR_OK; +} +/** + * @brief Get form manager service. + * @return Returns form manager servic remoteObject. + */ +sptr SystemTestFormUtil::GetFmsService() +{ + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + std::cout << "SendTransactCmd, failed to get system ability manager." << std::endl; + return nullptr; + } + sptr remoteObject = systemManager->GetSystemAbility(FORM_MGR_SERVICE_ID); + + std::cout << "SendTransactCmd end." << std::endl; + return remoteObject; +} +} // namespace STtools +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_acquire_form_test/BUILD.gn b/test/systemtest/common/fms/fms_acquire_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..24a3f045b536ad28894ae36a27656cec0ab2adac --- /dev/null +++ b/test/systemtest/common/fms/fms_acquire_form_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("FmsAcquireFormTest") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "fms_acquire_form_test.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"FMSAcquireFormTest\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":FmsAcquireFormTest" ] +} diff --git a/test/systemtest/common/fms/fms_acquire_form_test/fms_acquire_form_test.cpp b/test/systemtest/common/fms/fms_acquire_form_test/fms_acquire_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6ec766758dacb7a444c2d2d51e4ecd4a3618f94 --- /dev/null +++ b/test/systemtest/common/fms/fms_acquire_form_test/fms_acquire_form_test.cpp @@ -0,0 +1,1199 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "system_ability_definition.h" +#include "system_test_form_util.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace { +std::vector bundleNameList = { + "com.ohos.form.manager.notsystemapp", + "com.form.formsystemtestservicea", + "com.form.formsystemtestserviceb", +}; +std::vector hapNameList = { + "fmsSystemTestHostNotSys-signed", + "formSystemTestServiceA-signed", + "formSystemTestServiceB-signed", +}; + +std::string catchFormId; // FormId when creating a cached form +} // namespace + +namespace OHOS { +namespace AppExecFwk { +class FmsAcquireFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + + static bool SubscribeEvent(); + + void SetUp(); + void TearDown(); + + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityMs; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber; + + void FmsAcquireFormCatched1500(std::string strFormId); + void FmsAcquireForm1600(); + void FmsAcquireForm1600A(); + void FmsAcquireForm1800(); + void FmsAcquireForm1800A(); + void FmsAcquireForm1800B(); + void FmsAcquireForm1800C(); + std::string FmsAcquireForm2400(); + void FmsAcquireForm2400_1(std::string strFormId); + void FmsAcquireFormDeleteA(std::string strFormId); +}; + +std::vector FmsAcquireFormTest::eventList = { + FORM_EVENT_RECV_DELETE_FORM_COMMON, + FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_ACQUIRE_FORM_0100, FORM_EVENT_RECV_ACQUIRE_FORM_0200, + FORM_EVENT_RECV_ACQUIRE_FORM_0300, FORM_EVENT_RECV_ACQUIRE_FORM_0400, FORM_EVENT_RECV_ACQUIRE_FORM_0500, + FORM_EVENT_RECV_ACQUIRE_FORM_0600, FORM_EVENT_RECV_ACQUIRE_FORM_0700, FORM_EVENT_RECV_ACQUIRE_FORM_1000, + FORM_EVENT_RECV_ACQUIRE_FORM_1100, FORM_EVENT_RECV_ACQUIRE_FORM_1200, FORM_EVENT_RECV_ACQUIRE_FORM_1400, + FORM_EVENT_RECV_ACQUIRE_FORM_1500, FORM_EVENT_RECV_ACQUIRE_FORM_1600, FORM_EVENT_RECV_ACQUIRE_FORM_1600_1, + FORM_EVENT_RECV_ACQUIRE_FORM_1800, FORM_EVENT_RECV_ACQUIRE_FORM_1800_1, FORM_EVENT_RECV_ACQUIRE_FORM_1800_2, + FORM_EVENT_RECV_ACQUIRE_FORM_1800_3, FORM_EVENT_RECV_ACQUIRE_FORM_1900, FORM_EVENT_RECV_ACQUIRE_FORM_2100, + FORM_EVENT_RECV_ACQUIRE_FORM_2200, FORM_EVENT_RECV_ACQUIRE_FORM_2300, FORM_EVENT_RECV_ACQUIRE_FORM_2500, + FORM_EVENT_RECV_ACQUIRE_FORM_1500_1, FORM_EVENT_RECV_ACQUIRE_FORM_2600, FORM_EVENT_RECV_ACQUIRE_FORM_2600_1, + FORM_EVENT_RECV_ACQUIRE_FORM_2400, FORM_EVENT_RECV_ACQUIRE_FORM_2400_1, +}; + + +FormEvent FmsAcquireFormTest::event = FormEvent(); +sptr FmsAcquireFormTest::abilityMs = nullptr; +std::shared_ptr FmsAcquireFormTest::subscriber = nullptr; +void FmsAcquireFormTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void FmsAcquireFormTest::SetUpTestCase() +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void FmsAcquireFormTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; + CommonEventManager::UnSubscribeCommonEvent(subscriber); +} + +void FmsAcquireFormTest::SetUp() +{ +} + +void FmsAcquireFormTest::TearDown() +{ + GTEST_LOG_(INFO) << "CleanMsg calld"; + SystemTestFormUtil::CleanMsg(event); +} +bool FmsAcquireFormTest::SubscribeEvent() +{ + GTEST_LOG_(INFO) << "SubscribeEvent calld"; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +/** + * @tc.number: FMS_acquireForm_1100 + * @tc.name: When the formId is set to 0, a non cached form is added. + * @tc.desc: Verify that the non cache form can be successfully created. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1100, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_1100" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1100, EVENT_CODE_1100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1100, EVENT_CODE_1100)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1100, EVENT_CODE_1100); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1100, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1100, formId:" << strFormId; + } + + catchFormId = strFormId; + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1100, EVENT_CODE_1101)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1100, EVENT_CODE_1101); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1100, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1100, formData:" << data2; + } + int64_t formId = std::stoll(strFormId); + std::string cachedData = SystemTestFormUtil::QueryFormInfoByFormId(formId); + GTEST_LOG_(INFO) << "FMS_acquireForm_1100, cachedData:" << cachedData; + + std::cout << "END FMS_acquireForm_1100" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_1200 + * @tc.name: When the formId is set to 0, a non cached form is added. + * @tc.desc: Verify that the non cache form can be successfully created. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1200, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_1200" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1200, EVENT_CODE_1200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1200, EVENT_CODE_1200)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1200, EVENT_CODE_1200); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1200, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1200, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1200, EVENT_CODE_1201)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1200, EVENT_CODE_1201); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1200, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1200, formData:" << data2; + } + + int64_t formId = std::stoll(strFormId); + std::string cachedData = SystemTestFormUtil::QueryFormInfoByFormId(formId); + GTEST_LOG_(INFO) << "FMS_acquireForm_1200, cachedData:" << cachedData; + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result3 = data3 == "true"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FMS_acquireForm_1200, delete form, result:" << result3; + + std::cout << "END FMS_acquireForm_1200" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_1500 + * @tc.name: Add a cached form. + * @tc.desc: Verify that the cached form can be successfully created. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1500, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_1500" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, add no catch form start"; + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1500_1; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1500_1, EVENT_CODE_1510, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1500_1, EVENT_CODE_1510)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1500_1, EVENT_CODE_1510); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, formId:" << strFormId; + } + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1500_1, EVENT_CODE_1511)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1500_1, EVENT_CODE_1511); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, formData:" << data2; + } + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, add no catch form end"; + + sleep(1); + FmsAcquireFormCatched1500(strFormId); + + sleep(1); + FmsAcquireFormDeleteA(strFormId); + std::cout << "END FMS_acquireForm_1500" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_1600 + * @tc.name: A single form host (using a single thread) continuously creates 2 normal and 2 temporary forms. + * @tc.desc: Verify that a single host (using a single thread) can successfully create multiple normal + * and temporary forms continuously. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1600, Function | MediumTest | Level1) +{ + sleep(1); + int normalCount = 0; + int tempCount = 0; + for (int iCount = 0; iCount < 2; iCount++) { + sleep(1); + FmsAcquireForm1600(); + normalCount++; + std::cout << "END FMS_acquireForm_1600, normal form end, count:" << normalCount << std::endl; + sleep(1); + FmsAcquireForm1600A(); + tempCount++; + std::cout << "END FMS_acquireForm_1600_1, temp form end, count:" << tempCount << std::endl; + } +} + +/** + * @tc.number: FMS_acquireForm_1800 + * @tc.name: Multiple form hosts create one normal form and one temporary form respectively. + * @tc.desc: Verify that multiple hosts can successfully create multiple normal and temporary forms respectively. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1800, Function | MediumTest | Level1) +{ + sleep(1); + FmsAcquireForm1800(); + sleep(1); + FmsAcquireForm1800A(); + sleep(1); + FmsAcquireForm1800B(); + sleep(1); + FmsAcquireForm1800C(); +} + +/** + * @tc.number: FMS_acquireForm_1900 + * @tc.name: Add a temporary form when the formId is set to 0. + * @tc.desc: When the verification formId is set to 0, the temporary form is created successfully. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1900, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_1900" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1900; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1900, EVENT_CODE_1900, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1900, EVENT_CODE_1900)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1900, EVENT_CODE_1900); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1900, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1900, normal, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1900, EVENT_CODE_1901)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1900, EVENT_CODE_1901); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1900, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1900, normal, formData:" << data2; + } + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result3 = data3 == "true"; + EXPECT_TRUE(result3); + if (!result3) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1900, delete form, result:" << result3; + } + + std::cout << "END FMS_acquireForm_1900" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2400 + * @tc.name: FormId does not match other parameters when adding a cached form. + * @tc.desc: Failed to create a cached form when verifying that FormId does not match other parameters. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_2400, Function | MediumTest | Level1) +{ + sleep(1); + std::string strFormId = FmsAcquireForm2400(); + sleep(1); + FmsAcquireForm2400_1(strFormId); + sleep(1); + FmsAcquireFormDeleteA(strFormId); +} + +/** + * @tc.number: FMS_acquireForm_2600 + * @tc.name: When the normal form does not reach the maximum value created by the form + * (the single host is 256 and the FMS is 512), the temporary form changes to the normal form. + * @tc.desc: Verify that when the normal form does not reach the maximum value created by the form. + * (the single host is 256 and the FMS is 512), the temporary form can be successfully + * casted to the normal form. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_2600, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_2600" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2600_1; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2600_1, EVENT_CODE_2610, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2600_1, EVENT_CODE_2610)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2600_1, EVENT_CODE_2610); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_2600, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_2600, formId:" << strFormId; + } + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2600_1, EVENT_CODE_2611)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2600_1, EVENT_CODE_2611); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_2600, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_2600, formData:" << data2; + } + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData1 = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2600, EVENT_CODE_2600, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2600, EVENT_CODE_2600)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2600, EVENT_CODE_2600); + bool result3 = data3 == "true"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FMS_acquireForm_2600, result:" << result3; + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result4 = data4 == "true"; + EXPECT_TRUE(result4); + GTEST_LOG_(INFO) << "FMS_acquireForm_2600, delete form, result:" << result4; + std::cout << "END FMS_acquireForm_2600" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_0100 + * @tc.name: Form host is not a system application + * @tc.desc: Failed to create form when verifying that the form host is not a system application. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_0100, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_0100" << std::endl; + + std::string bundleName = "com.ohos.form.manager.notsystemapp"; + std::string abilityName = "FormAbilityNotSys"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_0100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_0100, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_0100, EVENT_CODE_100)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_0100, EVENT_CODE_100); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_0100, result:" << result; + + std::cout << "END FMS_acquireForm_0100" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_0200 + * @tc.name: The form host does not have permission to use the form + * @tc.desc: Failed to create a form when verifying that the form host does not have form permission. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_0200, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_0200" << std::endl; + + std::string bundleName = "com.ohos.form.manager.nopermission"; + std::string abilityName = "FormAbilityNoPerm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_0200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_0200, EVENT_CODE_200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_0200, EVENT_CODE_200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_0200, EVENT_CODE_200); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_0200, result:" << result; + + std::cout << "END FMS_acquireForm_0200" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_0300 + * @tc.name: Failed to add form when parameter formId is wrong. + * @tc.desc: Failed to create form when verifying that the parameter (formId) of creating form is wrong. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_0300, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_0300" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_0300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_0300, EVENT_CODE_300, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_0300, EVENT_CODE_300)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_0300, EVENT_CODE_300); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_0300, result:" << result; + std::cout << "END FMS_acquireForm_0300" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_0400 + * @tc.name: Failed to add form when parameter bundlename is wrong. + * @tc.desc: Form creation failed when verifying the wrong parameter (bundlename) of form creation. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_0400, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_0400" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_0400; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_0400, EVENT_CODE_400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_0400, EVENT_CODE_400)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_0400, EVENT_CODE_400); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_0400, result:" << result; + std::cout << "END FMS_acquireForm_0400" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_0500 + * @tc.name: Failed to add form when parameter moduleName is wrong. + * @tc.desc: Form creation failed when verifying the wrong parameter (moduleName) of form creation. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_0500, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_0500" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_0500; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_0500, EVENT_CODE_500, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_0500, EVENT_CODE_500)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_0500, EVENT_CODE_500); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_0500, result:" << result; + std::cout << "END FMS_acquireForm_0500" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_0600 + * @tc.name: Failed to add form when parameter formName is wrong. + * @tc.desc: Form creation failed when verifying the wrong parameter (formName) of form creation. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_0600, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_0600" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_0600; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_0600, EVENT_CODE_600, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_0600, EVENT_CODE_600)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_0600, EVENT_CODE_600); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_0600, result:" << result; + + std::cout << "END FMS_acquireForm_0600" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_0700 + * @tc.name: Failed to add form when parameter abilityName is wrong. + * @tc.desc: Form creation failed when verifying the wrong parameter (abilityName) of form creation. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_0700, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_0700" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_0700; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_0700, EVENT_CODE_700, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_0700, EVENT_CODE_700)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_0700, EVENT_CODE_700); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_0700, result:" << result; + } + std::cout << "END FMS_acquireForm_0700" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_1000 + * @tc.name: Failed to add form when parameter form dimension is wrong. + * @tc.desc: Form creation failed when verifying the wrong parameter (form dimension) of form creation. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1000, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_1000" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1000; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1000, EVENT_CODE_1000, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1000, EVENT_CODE_1000)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1000, EVENT_CODE_1000); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_1000, result:" << result; + + std::cout << "END FMS_acquireForm_1000" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_1400 + * @tc.name: FormId does not match other parameters when adding a cached form. + * @tc.desc: Failed to create a cached form when verifying that FormId does not match other parameters. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1400, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_1400" << std::endl; + std::string bundleName = "com.ohos.form.manager.normalb"; + std::string abilityName = "FormAbilityB"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = catchFormId; + GTEST_LOG_(INFO) << "FMS_acquireForm_1400, formId:" << eventData; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1400, EVENT_CODE_1400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1400, EVENT_CODE_1400)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1400, EVENT_CODE_1400); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_1400, result:" << result; + + std::cout << "END FMS_acquireForm_1400" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2100 + * @tc.name: When creating a temporary form, the formId is specified as the created normal formId. + * @tc.desc: Failed to create a temporary form when verifying that the formId is set to create a normal formId. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_2100, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_2100" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = catchFormId; + GTEST_LOG_(INFO) << "FMS_acquireForm_2100, formId:" << eventData; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2100, EVENT_CODE_2100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2100, EVENT_CODE_2100)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2100, EVENT_CODE_2100); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_2100, result:" << result; + sleep(1); + FmsAcquireFormDeleteA(catchFormId); + std::cout << "END FMS_acquireForm_2100" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2200 + * @tc.name: Cast to normal form when the temporary formId is set to negative. + * @tc.desc: Failed to Cast to normal form when the temporary formId is set to negative + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_2200, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_2200" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2200, EVENT_CODE_2200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2200, EVENT_CODE_2200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2200, EVENT_CODE_2200); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_2200, result:" << result; + + std::cout << "END FMS_acquireForm_2200" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2300 + * @tc.name: Cast to normal form when the temporary formIdis set to 0. + * @tc.desc: Failed to convert to normal form when verifying that the temporary formIdis set to 0 + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_2300, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_2300" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2300, EVENT_CODE_2300, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2300, EVENT_CODE_2300)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2300, EVENT_CODE_2300); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_2300, result:" << result; + + std::cout << "END FMS_acquireForm_2300" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2500 + * @tc.name: cast non-existent temporary formId to normal form. + * @tc.desc: Failed to verify that the temporary formId that does not exist is casted to normal form. + */ +HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_2500, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_2500" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2500; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2500, EVENT_CODE_2500, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2500, EVENT_CODE_2500)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2500, EVENT_CODE_2500); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_acquireForm_2500, result:" << result; + + std::cout << "END FMS_acquireForm_2500" << std::endl; +} + +void FmsAcquireFormTest::FmsAcquireFormCatched1500(std::string strFormId) +{ + std::string bundleName1 = "com.ohos.form.manager.normalb"; + std::string abilityName1 = "FormAbilityB"; + MAP_STR_STR params1; + Want want1 = SystemTestFormUtil::MakeWant("device", abilityName1, bundleName1, params1); + SystemTestFormUtil::StartAbility(want1, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, add catched form start"; + std::string eventData2 = strFormId; + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, formId:" << eventData2; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1500, EVENT_CODE_1500, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1500, EVENT_CODE_1500)); + std::string strFormId2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1500, EVENT_CODE_1500); + bool result3 = !strFormId2.empty(); + EXPECT_TRUE(result3); + if (!result3) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, result:" << result3; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, formId:" << strFormId2; + } + + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, add catched form end"; + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data5 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result5 = data5 == "true"; + EXPECT_TRUE(result5); + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, delete form, result:" << result5; +} + +void FmsAcquireFormTest::FmsAcquireForm1600() +{ + std::cout << "START FMS_acquireForm_1600, normal form start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1600; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1600, EVENT_CODE_1600, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600, EVENT_CODE_1600)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600, EVENT_CODE_1600); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600, EVENT_CODE_1601)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600, EVENT_CODE_1601); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600, formData:" << data2; + } + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result3 = data3 == "true"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FMS_acquireForm_1600, delete form, result:" << result3; +} + +void FmsAcquireFormTest::FmsAcquireForm1600A() +{ + std::cout << "START FMS_acquireForm_1600_1, temp form start." << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData1 = FORM_EVENT_REQ_ACQUIRE_FORM_1600_1; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1600_1, EVENT_CODE_1610, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600_1, EVENT_CODE_1610)); + std::string strFormId1 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600_1, EVENT_CODE_1610); + bool result4 = !strFormId1.empty(); + EXPECT_TRUE(result4); + if (!result4) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600_1, result:" << result4; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600_1 formId:" << strFormId1; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600_1, EVENT_CODE_1611)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1600_1, EVENT_CODE_1611); + bool result5 = !data4.empty(); + EXPECT_TRUE(result5); + if (!result5) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600_1, result:" << result5; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1600_1, formData:" << data4; + } + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data5 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result6 = data5 == "true"; + EXPECT_TRUE(result6); + GTEST_LOG_(INFO) << "FMS_acquireForm_1600_1, delete form, result:" << result6; +} +void FmsAcquireFormTest::FmsAcquireForm1800() +{ + int normalCount = 0; + std::cout << "START FMS_acquireForm_1800, normal form start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + std::cout << "START FMS_acquireForm_1800, bundleName: "<< bundleName << std::endl; + std::cout << "START FMS_acquireForm_1800, abilityName: "<< abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1800; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1800, EVENT_CODE_1800, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800, EVENT_CODE_1800)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800, EVENT_CODE_1800); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800, EVENT_CODE_1801)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800, EVENT_CODE_1801); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800, formData:" << data2; + } + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result3 = data3 == "true"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FMS_acquireForm_1800, delete form, result:" << result3; + + normalCount++; + std::cout << "END FMS_acquireForm_1800, normal form end, count:" << normalCount << std::endl; +} +void FmsAcquireFormTest::FmsAcquireForm1800A() +{ + int tempCount = 0; + std::cout << "START FMS_acquireForm_1800_1, temp form start." << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + std::cout << "START FMS_acquireForm_1800_1, bundleName: "<< bundleName << std::endl; + std::cout << "START FMS_acquireForm_1800_1, abilityName: "<< abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData1 = FORM_EVENT_REQ_ACQUIRE_FORM_1800_1; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1800_1, EVENT_CODE_1810, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_1, EVENT_CODE_1810)); + std::string strFormId1 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_1, EVENT_CODE_1810); + bool result4 = !strFormId1.empty(); + EXPECT_TRUE(result4); + if (!result4) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_1, result:" << result4; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_1 formId:" << strFormId1; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_1, EVENT_CODE_1811)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_1, EVENT_CODE_1811); + bool result5 = !data4.empty(); + EXPECT_TRUE(result5); + if (!result5) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_1, result:" << result5; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_1, formData:" << data4; + } + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data5 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result6 = data5 == "true"; + EXPECT_TRUE(result6); + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_1, delete form, result:" << result6; + + tempCount++; + std::cout << "END FMS_acquireForm_1800_1, temp form end, count:" << tempCount << std::endl; +} +void FmsAcquireFormTest::FmsAcquireForm1800B() +{ + int normalCount = 0; + std::cout << "START FMS_acquireForm_1800_2, normal form start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normalb"; + std::string abilityName = "FormAbilityB"; + std::cout << "START FMS_acquireForm_1800_2, bundleName: "<< bundleName << std::endl; + std::cout << "START FMS_acquireForm_1800_2, abilityName: "<< abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_1800_2; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1800_2, EVENT_CODE_1820, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_2, EVENT_CODE_1820)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_2, EVENT_CODE_1820); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_2, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_2, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_2, EVENT_CODE_1821)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_2, EVENT_CODE_1821); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_2, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_2, formData:" << data2; + } + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result3 = data3 == "true"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_2, delete form, result:" << result3; + + normalCount++; + std::cout << "END FMS_acquireForm_1800_2, normal form end, count:" << normalCount << std::endl; +} +void FmsAcquireFormTest::FmsAcquireForm1800C() +{ + int tempCount = 0; + std::cout << "START FMS_acquireForm_1800_3, temp form start." << std::endl; + + std::string bundleName = "com.ohos.form.manager.normalb"; + std::string abilityName = "FormAbilityB"; + std::cout << "START FMS_acquireForm_1800_3, bundleName: "<< bundleName << std::endl; + std::cout << "START FMS_acquireForm_1800_3, abilityName: "<< abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData1 = FORM_EVENT_REQ_ACQUIRE_FORM_1800_3; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_1800_3, EVENT_CODE_1830, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_3, EVENT_CODE_1830)); + std::string strFormId1 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_3, EVENT_CODE_1830); + bool result4 = !strFormId1.empty(); + EXPECT_TRUE(result4); + if (!result4) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_3, result:" << result4; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_3 formId:" << strFormId1; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_3, EVENT_CODE_1831)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_1800_3, EVENT_CODE_1831); + bool result5 = !data4.empty(); + EXPECT_TRUE(result5); + if (!result5) { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_3, result:" << result5; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_3, formData:" << data4; + } + + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data5 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result6 = data5 == "true"; + EXPECT_TRUE(result6); + GTEST_LOG_(INFO) << "FMS_acquireForm_1800_3, delete form, result:" << result6; + + tempCount++; + std::cout << "END FMS_acquireForm_1800_3, temp form end, count:" << tempCount << std::endl; +} + +std::string FmsAcquireFormTest::FmsAcquireForm2400() +{ + int normalCount = 0; + std::cout << "START FMS_acquireForm_2400, temp form start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + std::cout << "START FMS_acquireForm_2400, bundleName: "<< bundleName << std::endl; + std::cout << "START FMS_acquireForm_2400, abilityName: "<< abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2400; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2400, EVENT_CODE_2400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2400, EVENT_CODE_2400)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2400, EVENT_CODE_2400); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_acquireForm_2400, result:" << result; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_2400, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2400, EVENT_CODE_2401)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2400, EVENT_CODE_2401); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_acquireForm_2400, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FMS_acquireForm_2400, formData:" << data2; + } + + normalCount++; + std::cout << "END FMS_acquireForm_2400, temp form end, count:" << normalCount << std::endl; + + return strFormId; +} + +void FmsAcquireFormTest::FmsAcquireForm2400_1(std::string strFormId) +{ + std::cout << "START FMS_acquireForm_2400_1, cast temp start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normalb"; + std::string abilityName = "FormAbilityB"; + std::cout << "START FmsAcquireForm2400_1, bundleName: "<< bundleName << std::endl; + std::cout << "START FmsAcquireForm2400_1, abilityName: "<< abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData1 = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2400_1, EVENT_CODE_2410, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2400_1, EVENT_CODE_2410)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2400_1, EVENT_CODE_2410); + bool result3 = data3 == "false"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FmsAcquireForm2400_1, result:" << result3; + + std::cout << "END FmsAcquireForm2400_1 cast temp end" << std::endl; +} + +void FmsAcquireFormTest::FmsAcquireFormDeleteA(std::string strFormId) +{ + std::cout << "START FmsAcquireFormDeleteA, start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + std::cout << "START FmsAcquireFormDeleteA, bundleName: " << bundleName << std::endl; + std::cout << "START FmsAcquireFormDeleteA, abilityName: " << abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormDeleteA, delete form, result:" << result; + + std::cout << "END FmsAcquireFormDeleteA end" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_acquire_form_test_max/BUILD.gn b/test/systemtest/common/fms/fms_acquire_form_test_max/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d84cbfb4cd58a3cbd21430316344bfa8c138d3ab --- /dev/null +++ b/test/systemtest/common/fms/fms_acquire_form_test_max/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("FmsAcquireFormTestMax") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "fms_acquire_form_test_batch.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"FMSAcquireFormTestMax\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":FmsAcquireFormTestMax" ] +} diff --git a/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_batch.cpp b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_batch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..197ced8c1365ef859a7edc8858a071f434d53da7 --- /dev/null +++ b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_batch.cpp @@ -0,0 +1,813 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "system_ability_definition.h" +#include "system_test_form_util.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace { +const int FORM_COUNT_200 = 200; +const int FORM_COUNT_111 = 111; +const int FORM_COUNT_112 = 112; +const int TEMP_FORM_COUNT_256 = 256; +const int TEMP_FORM_COUNT_128 = 128; + +std::vector bundleNameList = { + "com.form.formsystemtestservicea", + "com.form.formsystemtestserviceb", +}; +std::vector hapNameList = { + "formSystemTestServiceA-signed", + "formSystemTestServiceB-signed", +}; + +std::vector normalFormsMaxA; +std::vector normalFormsMaxB; +std::vector normalFormsMaxC; + +std::vector tempFormsMaxA; +std::vector tempFormsMaxB; +} // namespace + +namespace OHOS { +namespace AppExecFwk { +class FmsAcquireFormTestBatch : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + + static bool SubscribeEvent(); + + void SetUp(); + void TearDown(); + + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityMs; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber; + + void FmsAcquireForm2700(std::string strFormId); + std::string FmsAcquireForm2900A(); + std::string FmsAcquireForm2900B(); + void FmsAcquireForm3000(); + std::string FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName); + void FmsAcquireForm2800(std::string strFormId); + void FmsAcquireForm3200(); + + void FmsAcquireFormDeleteA(const std::string &strFormId); + void FmsAcquireFormDeleteB(const std::string &strFormId); + void FmsAcquireFormDeleteC(const std::string &strFormId); + std::string FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName); + bool FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName); + + void FMS_acquireFormBatchA(const std::string &bundleName, const std::string &abilityName, const int count); + void FMS_acquireFormBatchB(const std::string &bundleName, const std::string &abilityName, const int count); + + void FMS_acquireTempFormBatch(const std::string &bundleName, const std::string &abilityName, const int count); + void FMS_deleteFormBatch(); +}; +std::vector FmsAcquireFormTestBatch::eventList = { + FORM_EVENT_RECV_DELETE_FORM_COMMON, FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, + FORM_EVENT_RECV_ACQUIRE_FORM_2700, FORM_EVENT_RECV_ACQUIRE_FORM_2800, FORM_EVENT_RECV_ACQUIRE_FORM_2900, + FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, FORM_EVENT_RECV_ACQUIRE_FORM_3000, FORM_EVENT_RECV_ACQUIRE_FORM_3100, + FORM_EVENT_RECV_ACQUIRE_FORM_3200, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH_B, + FORM_EVENT_RECV_CLEAR_FORM_BATCH, FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, +}; + + +FormEvent FmsAcquireFormTestBatch::event = FormEvent(); +sptr FmsAcquireFormTestBatch::abilityMs = nullptr; +std::shared_ptr FmsAcquireFormTestBatch::subscriber = nullptr; +void FmsAcquireFormTestBatch::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void FmsAcquireFormTestBatch::SetUpTestCase() +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void FmsAcquireFormTestBatch::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; + CommonEventManager::UnSubscribeCommonEvent(subscriber); +} + +void FmsAcquireFormTestBatch::SetUp() +{ +} + +void FmsAcquireFormTestBatch::TearDown() +{ + GTEST_LOG_(INFO) << "CleanMsg calld"; + SystemTestFormUtil::CleanMsg(event); +} +bool FmsAcquireFormTestBatch::SubscribeEvent() +{ + GTEST_LOG_(INFO) << "SubscribeEvent calld"; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +/** + * @tc.number: FMS_acquireForm_2900 + * @tc.name: A single host creates 256 different provider forms. + * @tc.desc: The single host can successfully create 256 different provider forms. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_2900, Function | MediumTest | Level1) +{ + std::cout << "START FMS_acquireForm_2900" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + int countA = Constants::MAX_RECORD_PER_APP/2; + int countB = Constants::MAX_RECORD_PER_APP/2 - 1; + sleep(1); + FMS_acquireFormBatchA(bundleName, abilityName, countA); + sleep(1); + FMS_acquireFormBatchB(bundleName, abilityName, countB); + int count = Constants::MAX_RECORD_PER_APP - 1; + std::cout << "FMS_acquireForm_2900, form size of the host A:" << count << std::endl; + + sleep(1); + std::string strFormId = FmsAcquireForm2900A(); + normalFormsMaxA.emplace_back(strFormId); + std::cout << "END FMS_acquireForm_2900" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_3000 + * @tc.name: Create limit value verification using single party form. + * @tc.desc: Failed to create the 257th host form. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_3000, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_3000" << std::endl; + std::cout << "FMS_acquireForm_3000, form size of the host A:" << normalFormsMaxA.size() << std::endl; + FmsAcquireForm3000(); + std::cout << "END FMS_acquireForm_3000" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2700 + * @tc.name: When the normal form reaches the maximum value (256) created by the host, + * the temporary form is transferred to the normal form. + * @tc.desc: Verify that when the normal form reaches the maximum value (256) created by the single host, + * the conversion of the temporary form to the normal form fails. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_2700, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_2700" << std::endl; + std::cout << "FMS_acquireForm_2700, form size of the host A:" << normalFormsMaxA.size() << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); + + sleep(1); + FmsAcquireForm2700(strFormId); + std::cout << "END FMS_acquireForm_2700" << std::endl; + + std::cout << "the host A, delete form start" << std::endl; + if (normalFormsMaxA.size() > 0) { + for (int count = 0; count < normalFormsMaxA.size(); count++) { + FmsAcquireFormDeleteA(normalFormsMaxA[count]); + } + } + sleep(1); + FMS_deleteFormBatch(); + std::cout << "the host A, delete form end" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_3100 + * @tc.name: Multiple hosts create 512 forms respectively. + * @tc.desc: Verify that multiple hosts can create 512 forms. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_3100, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_3100" << std::endl; + + std::cout << "START add form to the host A" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::cout << "bundleName: " << bundleNameA << std::endl; + std::cout << "abilityName: " << abilityNameA << std::endl; + FMS_acquireFormBatchA(bundleNameA, abilityNameA, FORM_COUNT_200); + std::cout << "count:" << FORM_COUNT_200 << std::endl; + std::cout << "END add form to the host A" << std::endl; + + sleep(1); + std::cout << "START add form to the host B" << std::endl; + std::string bundleNameB = "com.ohos.form.manager.normalb"; + std::string abilityNameB = "FormAbilityB"; + std::cout << "bundleName: " << bundleNameB << std::endl; + std::cout << "abilityName: " << abilityNameB << std::endl; + FMS_acquireFormBatchA(bundleNameB, abilityNameB, FORM_COUNT_200); + std::cout << "count:" << FORM_COUNT_200 << std::endl; + std::cout << "END add form to the host B" << std::endl; + + sleep(1); + std::cout << "START add form to the host C" << std::endl; + std::string bundleNameC = "com.ohos.form.manager.normalc"; + std::string abilityNameC = "FormAbilityC"; + std::cout << "bundleName: " << bundleNameC << std::endl; + std::cout << "abilityName: " << abilityNameC << std::endl; + FMS_acquireFormBatchA(bundleNameC, abilityNameC, FORM_COUNT_111); + std::cout << "count:" << FORM_COUNT_111 << std::endl; + std::cout << "END add form to the host C" << std::endl; + + sleep(1); + std::string formId = FmsAcquireForm3100(bundleNameC, abilityNameC); + normalFormsMaxC.emplace_back(formId); + std::cout << "END FMS_acquireForm_3100" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2800 + * @tc.name: When the normal form reaches the maximum value (512) of the form created by FMS, + * the temporary form will be transferred to the normal form. + * @tc.desc: When the normal form reaches the maximum value (512) created by FMS, + * the conversion of temporary form to normal form fails. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_2800, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_2800" << std::endl; + std::cout << "FMS_acquireForm_2800, form size of the host A:" << FORM_COUNT_200 << std::endl; + std::cout << "FMS_acquireForm_2800, form size of the host B:" << FORM_COUNT_200 << std::endl; + std::cout << "FMS_acquireForm_2800, form size of the host C:" << FORM_COUNT_112 << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + + std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); + + sleep(1); + FmsAcquireForm2800(strFormId); + + std::cout << "END FMS_acquireForm_2800" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_3200 + * @tc.name: FMS create form limit value (512) verification. + * @tc.desc: Verify that 512 forms can be successfully created by creating forms with different users + * (the number of single user forms is less than 256), and the 513rd form fails to be created. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_3200, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_3200" << std::endl; + std::cout << "FMS_acquireForm_3200, form size of the host A:" << FORM_COUNT_200 << std::endl; + std::cout << "FMS_acquireForm_3200, form size of the host B:" << FORM_COUNT_200 << std::endl; + std::cout << "FMS_acquireForm_3200, form size of the host C:" << FORM_COUNT_112 << std::endl; + FmsAcquireForm3200(); + std::cout << "END FMS_acquireForm_3200" << std::endl; + + std::cout << "dlete form start" << std::endl; + if (normalFormsMaxC.size() > 0) { + for (int count = 0; count < normalFormsMaxC.size(); count++) { + sleep(1); + FmsAcquireFormDeleteC(normalFormsMaxC[count]); + } + } + sleep(1); + FMS_deleteFormBatch(); + std::cout << "dlete form end" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_3300 + * @tc.name: A single host can create 256 temporary forms. + * @tc.desc: The host of the verification form can successfully create 256 temporary forms. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_3300, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_3300" << std::endl; + + std::cout << "START add temp form to the host A" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::cout << "bundleName: " << bundleNameA << std::endl; + std::cout << "abilityName: " << abilityNameA << std::endl; + FMS_acquireTempFormBatch(bundleNameA, abilityNameA, TEMP_FORM_COUNT_256 - 1); + std::cout << "FMS_acquireForm_3300, temp form size of the host A:" << (TEMP_FORM_COUNT_256 - 1)<< std::endl; + + sleep(1); + std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); + std::cout << "FMS_acquireForm_3300, temp form size of the host A:" << TEMP_FORM_COUNT_256 << std::endl; + std::cout << "END add temp form to the host A" << std::endl; + std::cout << "END FMS_acquireForm_3300" << std::endl; + + sleep(1); + std::cout << "the host A, dlete temp form start" << std::endl; + FmsAcquireFormDeleteA(strFormId); + sleep(1); + FMS_deleteFormBatch(); + std::cout << "the host A, dlete temp form end" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_3400 + * @tc.name: 256 temporary forms can be created by multiple hosts. + * @tc.desc: Verify that multiple hosts can successfully create 256 temporary forms. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_3400, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_3400" << std::endl; + + std::cout << "START add temp form to the host A" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::cout << "bundleName: " << bundleNameA << std::endl; + std::cout << "abilityName: " << abilityNameA << std::endl; + FMS_acquireTempFormBatch(bundleNameA, abilityNameA, TEMP_FORM_COUNT_128); + std::cout << "FMS_acquireForm_3400, temp form size:" << TEMP_FORM_COUNT_128 << std::endl; + std::cout << "END add temp form to the host A" << std::endl; + + sleep(1); + std::cout << "START add temp form to the host B" << std::endl; + std::string bundleNameB = "com.ohos.form.manager.normalb"; + std::string abilityNameB = "FormAbilityB"; + std::cout << "bundleName: " << bundleNameB << std::endl; + std::cout << "abilityName: " << abilityNameB << std::endl; + FMS_acquireTempFormBatch(bundleNameB, abilityNameB, TEMP_FORM_COUNT_128 - 1); + std::cout << "FMS_acquireForm_3400, temp form size:" << (TEMP_FORM_COUNT_128 - 1) << std::endl; + sleep(1); + std::string strFormId = FmsAcquireFormTemp(bundleNameB, abilityNameB); + std::cout << "FMS_acquireForm_3400, temp form size:" << TEMP_FORM_COUNT_128 << std::endl; + std::cout << "END add temp form to the host B" << std::endl; + + sleep(1); + std::cout << "FMS_acquireForm_3400, dlete temp form start" << std::endl; + FmsAcquireFormDeleteB(strFormId); + sleep(1); + FMS_deleteFormBatch(); + std::cout << "FMS_acquireForm_3400, dlete temp form end" << std::endl; + + std::cout << "END FMS_acquireForm_3400" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_3500 + * @tc.name: Create temporary form limit value (256) verification. + * @tc.desc: Failed to create the 257th temporary form for multiple users. + */ +HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_3500, Function | MediumTest | Level1) +{ + sleep(1); + std::cout << "START FMS_acquireForm_3500" << std::endl; + std::cout << "START add temp form to the host A" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::cout << "bundleName: " << bundleNameA << std::endl; + std::cout << "abilityName: " << abilityNameA << std::endl; + FMS_acquireTempFormBatch(bundleNameA, abilityNameA, TEMP_FORM_COUNT_128); + std::cout << "FMS_acquireForm_3500, temp form size:" << TEMP_FORM_COUNT_128 << std::endl; + std::cout << "END add temp form to the host A" << std::endl; + sleep(1); + std::cout << "START add temp form to the host B" << std::endl; + std::string bundleNameB = "com.ohos.form.manager.normalb"; + std::string abilityNameB = "FormAbilityB"; + std::cout << "bundleName: " << bundleNameB << std::endl; + std::cout << "abilityName: " << abilityNameB << std::endl; + FMS_acquireTempFormBatch(bundleNameB, abilityNameB, TEMP_FORM_COUNT_128); + std::cout << "FMS_acquireForm_3500, temp form size:" << TEMP_FORM_COUNT_128 << std::endl; + std::cout << "END add temp form to the host B" << std::endl; + sleep(1); + bool result = FmsAcquireFormTempForFailed(bundleNameB, abilityNameB); + EXPECT_TRUE(result); + if (result) { + std::cout << "END add temp form to the host B, Failed to create the 257th temporary form." << std::endl; + } + sleep(1); + std::cout << "FMS_acquireForm_3500, dlete temp form start" << std::endl; + FMS_deleteFormBatch(); + std::cout << "FMS_acquireForm_3500, dlete temp form end" << std::endl; + + std::cout << "END FMS_acquireForm_3500" << std::endl; +} + +std::string FmsAcquireFormTestBatch::FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3100, EVENT_CODE_3100, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result; + } else { + GTEST_LOG_(INFO) << "FmsAcquireForm3100, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result2; + + return strFormId; +} + +void FmsAcquireFormTestBatch::FmsAcquireForm2700(std::string strFormId) +{ + std::cout << "START FmsAcquireForm2700, cast temp form" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData1 = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2700, EVENT_CODE_2700, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700); + bool result3 = data3 == "false"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FmsAcquireForm2700, result:" << result3; + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result4 = data4 == "true"; + EXPECT_TRUE(result4); + GTEST_LOG_(INFO) << "FmsAcquireForm2700, delete form, result:" << result4; + std::cout << "END FmsAcquireForm2700, cast temp form" << std::endl; +} +void FmsAcquireFormTestBatch::FmsAcquireForm3200() +{ + std::cout << "START FmsAcquireForm3200" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normalc"; + std::string abilityName = "FormAbilityC"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3200, EVENT_CODE_3200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireForm3200, result:" << result; + + std::cout << "END FmsAcquireForm3200" << std::endl; +} +void FmsAcquireFormTestBatch::FmsAcquireForm2800(std::string strFormId) +{ + std::cout << "START FmsAcquireForm2800, cast temp form" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData1 = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2800, EVENT_CODE_2800, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800); + bool result3 = data3 == "false"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FmsAcquireForm2800, result:" << result3; + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result4 = data4 == "true"; + EXPECT_TRUE(result4); + GTEST_LOG_(INFO) << "FmsAcquireForm2800, delete form, result:" << result4; + std::cout << "END FmsAcquireForm2800, cast temp form" << std::endl; +} + +std::string FmsAcquireFormTestBatch::FmsAcquireForm2900A() +{ + std::cout << "START FmsAcquireForm2900A, Provider A" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2900; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2900, EVENT_CODE_2900, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result; + } else { + GTEST_LOG_(INFO) << "FmsAcquireForm2900A, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result2; + + std::cout << "END FmsAcquireForm2900A, Provider A" << std::endl; + return strFormId; +} +void FmsAcquireFormTestBatch::FmsAcquireForm3000() +{ + std::cout << "START FmsAcquireForm3000" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3000; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3000, EVENT_CODE_3000, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireForm3000, result:" << result; + + std::cout << "END FmsAcquireForm3000" << std::endl; +} + +void FmsAcquireFormTestBatch::FMS_acquireFormBatchA(const std::string &bundleName, const std::string &abilityName, + const int count) +{ + std::cout << "START FMS_acquireFormBatchA" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = std::to_string(count); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_acquireFormBatchA, for provider A, count: " << eventData; + } else { + GTEST_LOG_(INFO) << "FMS_acquireFormBatchA, result:" << result; + } + std::cout << "END FMS_acquireFormBatchA" << std::endl; +} + +void FmsAcquireFormTestBatch::FMS_acquireFormBatchB(const std::string &bundleName, const std::string &abilityName, + const int count) +{ + std::cout << "START FMS_acquireFormBatchB" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = std::to_string(count); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_BATCH_B, EVENT_CODE_BATCH_B, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH_B, EVENT_CODE_BATCH_B)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH_B, EVENT_CODE_BATCH_B); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_acquireFormBatchB, for provider B, count: " << eventData; + } else { + GTEST_LOG_(INFO) << "FMS_acquireFormBatchB, result:" << result; + } + + std::cout << "END FMS_acquireFormBatchB" << std::endl; +} +void FmsAcquireFormTestBatch::FMS_acquireTempFormBatch(const std::string &bundleName, const std::string &abilityName, + const int count) +{ + std::cout << "START FMS_acquireTempFormBatch" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = std::to_string(count); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, + EVENT_CODE_TEMP_BATCH)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, + EVENT_CODE_TEMP_BATCH); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_acquireTempFormBatch, count: " << eventData; + } else { + GTEST_LOG_(INFO) << "FMS_acquireTempFormBatch, result:" << result; + } + + std::cout << "END FMS_acquireTempFormBatch" << std::endl; +} + +std::string FmsAcquireFormTestBatch::FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName) +{ + std::cout << "START FmsAcquireFormTemp, add temp form" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result; + } else { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formId:" << strFormId; + } + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formData:" << data2; + } + std::cout << "END FmsAcquireFormTemp, add temp form" << std::endl; + + return strFormId; +} +bool FmsAcquireFormTestBatch::FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName) +{ + std::cout << "START FmsAcquireFormTempForFailed, add temp form" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); + bool result = strFormId.empty(); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormTempForFailed, result:" << result; + + std::cout << "END FmsAcquireFormTempForFailed, add temp form" << std::endl; + + return result; +} + +void FmsAcquireFormTestBatch::FmsAcquireFormDeleteA(const std::string &strFormId) +{ + std::cout << "START FmsAcquireFormDeleteA, start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + std::cout << "START FmsAcquireFormDeleteA, bundleName: " << bundleName << std::endl; + std::cout << "START FmsAcquireFormDeleteA, abilityName: " << abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormDeleteA, delete form, result:" << result; + + std::cout << "END FmsAcquireFormDeleteA end" << std::endl; +} + +void FmsAcquireFormTestBatch::FmsAcquireFormDeleteB(const std::string &strFormId) +{ + std::cout << "START FmsAcquireFormDeleteB, start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normalb"; + std::string abilityName = "FormAbilityB"; + std::cout << "START FmsAcquireFormDeleteB, bundleName: " << bundleName << std::endl; + std::cout << "START FmsAcquireFormDeleteB, abilityName: " << abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormDeleteB, delete form, result:" << result; + + std::cout << "END FmsAcquireFormDeleteB end" << std::endl; +} +void FmsAcquireFormTestBatch::FmsAcquireFormDeleteC(const std::string &strFormId) +{ + std::cout << "START FmsAcquireFormDeleteC, start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normalc"; + std::string abilityName = "FormAbilityC"; + std::cout << "START FmsAcquireFormDeleteC, bundleName: " << bundleName << std::endl; + std::cout << "START FmsAcquireFormDeleteC, abilityName: " << abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormDeleteC, delete form, result:" << result; + + std::cout << "END FmsAcquireFormDeleteC end" << std::endl; +} + +void FmsAcquireFormTestBatch::FMS_deleteFormBatch() +{ + std::cout << "START FMS_deleteFormBatch, delete forms" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_CLEAR_FORM_BATCH; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_CLEAR_FORM_BATCH, EVENT_CODE_TEMP, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_deleteFormBatch, result:" << result; + + std::cout << "END FMS_deleteFormBatch, delete forms" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a37652d27e7f8d8356217d5f45ed4ba89c660cb6 --- /dev/null +++ b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp @@ -0,0 +1,763 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "system_ability_definition.h" +#include "system_test_form_util.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace { +const int FORM_COUNT_200 = 200; +const int FORM_COUNT_112 = 112; +const int TEMP_FORM_COUNT_256 = 256; +const int TEMP_FORM_COUNT_128 = 128; + +std::vector bundleNameList = { + "com.form.formsystemtestservicea", + "com.form.formsystemtestserviceb", +}; +std::vector hapNameList = { + "formSystemTestServiceA-signed", + "formSystemTestServiceB-signed", +}; + +std::vector normalFormsMaxA; +std::vector normalFormsMaxB; +std::vector normalFormsMaxC; + +std::vector tempFormsMaxA; +std::vector tempFormsMaxB; +} // namespace + +namespace OHOS { +namespace AppExecFwk { +class FmsAcquireFormTestMax : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + + static bool SubscribeEvent(); + + void SetUp(); + void TearDown(); + + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityMs; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber; + + void FmsAcquireForm2700(std::string strFormId); + std::string FmsAcquireForm2900A(); + std::string FmsAcquireForm2900B(); + void FmsAcquireForm3000(); + std::string FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName); + void FmsAcquireForm2800(std::string strFormId); + void FmsAcquireForm3200(); + + void FmsAcquireFormDeleteA(const std::string &strFormId); + void FmsAcquireFormDeleteB(const std::string &strFormId); + void FmsAcquireFormDeleteC(const std::string &strFormId); + std::string FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName); + bool FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName); +}; +std::vector FmsAcquireFormTestMax::eventList = { + FORM_EVENT_RECV_DELETE_FORM_COMMON, FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, + FORM_EVENT_RECV_ACQUIRE_FORM_2700, FORM_EVENT_RECV_ACQUIRE_FORM_2800, FORM_EVENT_RECV_ACQUIRE_FORM_2900, + FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, FORM_EVENT_RECV_ACQUIRE_FORM_3000, FORM_EVENT_RECV_ACQUIRE_FORM_3100, + FORM_EVENT_RECV_ACQUIRE_FORM_3200, +}; + + +FormEvent FmsAcquireFormTestMax::event = FormEvent(); +sptr FmsAcquireFormTestMax::abilityMs = nullptr; +std::shared_ptr FmsAcquireFormTestMax::subscriber = nullptr; +void FmsAcquireFormTestMax::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void FmsAcquireFormTestMax::SetUpTestCase() +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void FmsAcquireFormTestMax::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; + CommonEventManager::UnSubscribeCommonEvent(subscriber); +} + +void FmsAcquireFormTestMax::SetUp() +{ +} + +void FmsAcquireFormTestMax::TearDown() +{ + GTEST_LOG_(INFO) << "CleanMsg calld"; + SystemTestFormUtil::CleanMsg(event); +} +bool FmsAcquireFormTestMax::SubscribeEvent() +{ + GTEST_LOG_(INFO) << "SubscribeEvent calld"; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +/** + * @tc.number: FMS_acquireForm_2900 + * @tc.name: A single host creates 256 different provider forms. + * @tc.desc: The single host can successfully create 256 different provider forms. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2900, Function | MediumTest | Level1) +{ + std::cout << "START FMS_acquireForm_2900" << std::endl; + for (int count = 0; count < Constants::MAX_RECORD_PER_APP/2; count++) { + sleep(7); + std::string strFormId1 = FmsAcquireForm2900A(); + normalFormsMaxA.emplace_back(strFormId1); + std::cout << "FMS_acquireForm_2900, form size of the host A:" << normalFormsMaxA.size() << std::endl; + sleep(7); + std::string strFormId2 = FmsAcquireForm2900B(); + normalFormsMaxA.emplace_back(strFormId2); + std::cout << "FMS_acquireForm_2900, form size of the host A:" << normalFormsMaxA.size() << std::endl; + } + + std::cout << "END FMS_acquireForm_2900" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_3000 + * @tc.name: Create limit value verification using single party form. + * @tc.desc: Failed to create the 257th host form. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3000, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_3000" << std::endl; + std::cout << "FMS_acquireForm_3000, form size of the host A:" << normalFormsMaxA.size() << std::endl; + FmsAcquireForm3000(); + std::cout << "END FMS_acquireForm_3000" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2700 + * @tc.name: When the normal form reaches the maximum value (256) created by the host, + * the temporary form is transferred to the normal form. + * @tc.desc: Verify that when the normal form reaches the maximum value (256) created by the single host, + * the conversion of the temporary form to the normal form fails. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2700, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_2700" << std::endl; + std::cout << "FMS_acquireForm_2700, form size of the host A:" << normalFormsMaxA.size() << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); + + sleep(7); + FmsAcquireForm2700(strFormId); + std::cout << "END FMS_acquireForm_2700" << std::endl; + + std::cout << "the host A, dlete form start" << std::endl; + for (int count = 0; count < normalFormsMaxA.size(); count++) { + sleep(7); + FmsAcquireFormDeleteA(normalFormsMaxA[count]); + std::cout << "delete form count:" << count + 1 << std::endl; + } + normalFormsMaxA.clear(); + std::cout << "the host A, dlete form end" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_3100 + * @tc.name: Multiple hosts create 512 forms respectively. + * @tc.desc: Verify that multiple hosts can create 512 forms. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3100, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_3100" << std::endl; + + std::cout << "START add form to the host A" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::cout << "bundleName: " << bundleNameA << std::endl; + std::cout << "abilityName: " << abilityNameA << std::endl; + for (int count = 0; count < FORM_COUNT_200; count++) { + sleep(7); + std::string strFormId = FmsAcquireForm3100(bundleNameA, abilityNameA); + normalFormsMaxA.emplace_back(strFormId); + std::cout << "add form count:" << count + 1 << std::endl; + } + std::cout << "END add form to the host A" << std::endl; + + std::cout << "START add form to the host B" << std::endl; + std::string bundleNameB = "com.ohos.form.manager.normalb"; + std::string abilityNameB = "FormAbilityB"; + std::cout << "bundleName: " << bundleNameB << std::endl; + std::cout << "abilityName: " << abilityNameB << std::endl; + for (int count = 0; count < FORM_COUNT_200; count++) { + sleep(7); + std::string strFormId = FmsAcquireForm3100(bundleNameB, abilityNameB); + normalFormsMaxB.emplace_back(strFormId); + std::cout << "add form count:" << count + 1 << std::endl; + } + std::cout << "END add form to the host B" << std::endl; + + std::cout << "START add form to the host C" << std::endl; + std::string bundleNameC = "com.ohos.form.manager.normalc"; + std::string abilityNameC = "FormAbilityC"; + std::cout << "bundleName: " << bundleNameC << std::endl; + std::cout << "abilityName: " << abilityNameC << std::endl; + for (int count = 0; count < FORM_COUNT_112; count++) { + sleep(7); + std::string strFormId = FmsAcquireForm3100(bundleNameC, abilityNameC); + normalFormsMaxC.emplace_back(strFormId); + std::cout << "add form count:" << count + 1 << std::endl; + } + std::cout << "END add form to the host C" << std::endl; + + std::cout << "END FMS_acquireForm_3100" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2800 + * @tc.name: When the normal form reaches the maximum value (512) of the form created by FMS, + * the temporary form will be transferred to the normal form. + * @tc.desc: When the normal form reaches the maximum value (512) created by FMS, + * the conversion of temporary form to normal form fails. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2800, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_2800" << std::endl; + std::cout << "FMS_acquireForm_2800, form size of the host A:" << normalFormsMaxA.size() << std::endl; + std::cout << "FMS_acquireForm_2800, form size of the host B:" << normalFormsMaxB.size() << std::endl; + std::cout << "FMS_acquireForm_2800, form size of the host C:" << normalFormsMaxC.size() << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + + std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); + + sleep(7); + FmsAcquireForm2800(strFormId); + std::cout << "END FMS_acquireForm_2800" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_2800 + * @tc.name: When the normal form reaches the maximum value (512) of the form created by FMS, + * the temporary form will be transferred to the normal form. + * @tc.desc: When the normal form reaches the maximum value (512) created by FMS, + * the conversion of temporary form to normal form fails. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3200, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_3200" << std::endl; + std::cout << "FMS_acquireForm_3200, form size of the host A:" << normalFormsMaxA.size() << std::endl; + std::cout << "FMS_acquireForm_3200, form size of the host B:" << normalFormsMaxB.size() << std::endl; + std::cout << "FMS_acquireForm_3200, form size of the host C:" << normalFormsMaxC.size() << std::endl; + FmsAcquireForm3200(); + std::cout << "END FMS_acquireForm_3200" << std::endl; + + std::cout << "the host A, dlete form start" << std::endl; + for (int count = 0; count < normalFormsMaxA.size(); count++) { + sleep(7); + FmsAcquireFormDeleteA(normalFormsMaxA[count]); + std::cout << "delete form count:" << count + 1 << std::endl; + } + normalFormsMaxA.clear(); + std::cout << "the host A, dlete form end" << std::endl; + + std::cout << "the host B, dlete form start" << std::endl; + for (int count = 0; count < normalFormsMaxB.size(); count++) { + sleep(7); + FmsAcquireFormDeleteB(normalFormsMaxB[count]); + std::cout << "delete form count:" << count + 1 << std::endl; + } + normalFormsMaxB.clear(); + std::cout << "the host B, dlete form end" << std::endl; + + std::cout << "the host C, dlete form start" << std::endl; + for (int count = 0; count < normalFormsMaxC.size(); count++) { + sleep(7); + FmsAcquireFormDeleteC(normalFormsMaxC[count]); + std::cout << "delete form count:" << count + 1 << std::endl; + } + normalFormsMaxC.clear(); + std::cout << "the host C, dlete form end" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_3300 + * @tc.name: A single host can create 256 temporary forms. + * @tc.desc: The host of the verification form can successfully create 256 temporary forms. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3300, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_3300" << std::endl; + + std::cout << "START add temp form to the host A" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::cout << "bundleName: " << bundleNameA << std::endl; + std::cout << "abilityName: " << abilityNameA << std::endl; + for (int count = 0; count < TEMP_FORM_COUNT_256; count++) { + sleep(7); + std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); + tempFormsMaxA.emplace_back(strFormId); + std::cout << "FMS_acquireForm_3300, form size of the host A:" << tempFormsMaxA.size() << std::endl; + } + std::cout << "END add temp form to the host A" << std::endl; + + std::cout << "END FMS_acquireForm_3300" << std::endl; + + std::cout << "the host A, dlete temp form start" << std::endl; + for (int count = 0; count < tempFormsMaxA.size(); count++) { + sleep(7); + FmsAcquireFormDeleteA(tempFormsMaxA[count]); + std::cout << "delete temp form count:" << count + 1 << std::endl; + } + tempFormsMaxA.clear(); + std::cout << "the host A, dlete temp form end" << std::endl; +} +/** + * @tc.number: FMS_acquireForm_3400 + * @tc.name: 256 temporary forms can be created by multiple hosts. + * @tc.desc: Verify that multiple hosts can successfully create 256 temporary forms. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3400, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_3400" << std::endl; + + std::cout << "START add temp form to the host A" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.normal"; + std::string abilityNameA = "FormAbilityA"; + std::cout << "bundleName: " << bundleNameA << std::endl; + std::cout << "abilityName: " << abilityNameA << std::endl; + for (int count = 0; count < TEMP_FORM_COUNT_128; count++) { + sleep(7); + std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); + tempFormsMaxA.emplace_back(strFormId); + std::cout << "FMS_acquireForm_3400, temp form size of the host A:" << tempFormsMaxA.size() << std::endl; + } + std::cout << "END add temp form to the host A" << std::endl; + + std::cout << "START add temp form to the host B" << std::endl; + std::string bundleNameB = "com.ohos.form.manager.normalb"; + std::string abilityNameB = "FormAbilityB"; + std::cout << "bundleName: " << bundleNameB << std::endl; + std::cout << "abilityName: " << abilityNameB << std::endl; + for (int count = 0; count < TEMP_FORM_COUNT_128; count++) { + sleep(7); + std::string strFormId = FmsAcquireFormTemp(bundleNameB, abilityNameB); + tempFormsMaxB.emplace_back(strFormId); + std::cout << "FMS_acquireForm_3400, temp form size of the host B:" << tempFormsMaxB.size() << std::endl; + } + std::cout << "END add temp form to the host B" << std::endl; + + std::cout << "END FMS_acquireForm_3400" << std::endl; +} + +/** + * @tc.number: FMS_acquireForm_3500 + * @tc.name: Create temporary form limit value (256) verification. + * @tc.desc: Failed to create the 257th temporary form for multiple users. + */ +HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3500, Function | MediumTest | Level1) +{ + sleep(7); + std::cout << "START FMS_acquireForm_3500" << std::endl; + + std::cout << "START add temp form to the host B" << std::endl; + std::string bundleNameB = "com.ohos.form.manager.normalb"; + std::string abilityNameB = "FormAbilityB"; + std::cout << "bundleName: " << bundleNameB << std::endl; + std::cout << "abilityName: " << abilityNameB << std::endl; + + bool result = FmsAcquireFormTempForFailed(bundleNameB, abilityNameB); + EXPECT_TRUE(result); + if (result) { + std::cout << "END add temp form to the host B, Failed to create the 257th temporary form." << std::endl; + } + std::cout << "END FMS_acquireForm_3500" << std::endl; + + std::cout << "the host A, dlete temp form start" << std::endl; + for (int count = 0; count < tempFormsMaxA.size(); count++) { + sleep(7); + FmsAcquireFormDeleteA(tempFormsMaxA[count]); + std::cout << "delete temp form count:" << count + 1 << std::endl; + } + tempFormsMaxA.clear(); + std::cout << "the host A, dlete temp form end" << std::endl; + + std::cout << "the host B, dlete temp form start" << std::endl; + for (int count = 0; count < tempFormsMaxB.size(); count++) { + sleep(7); + FmsAcquireFormDeleteB(tempFormsMaxB[count]); + std::cout << "delete temp form count:" << count + 1 << std::endl; + } + tempFormsMaxB.clear(); + std::cout << "the host B, dlete temp form end" << std::endl; +} + +std::string FmsAcquireFormTestMax::FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3100, EVENT_CODE_3100, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result; + } else { + GTEST_LOG_(INFO) << "FmsAcquireForm3100, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result2; + + return strFormId; +} + +void FmsAcquireFormTestMax::FmsAcquireForm2700(std::string strFormId) +{ + std::cout << "START FmsAcquireForm2700, cast temp form" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData1 = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2700, EVENT_CODE_2700, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700); + bool result3 = data3 == "false"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FmsAcquireForm2700, result:" << result3; + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result4 = data4 == "true"; + EXPECT_TRUE(result4); + GTEST_LOG_(INFO) << "FmsAcquireForm2700, delete form, result:" << result4; + std::cout << "END FmsAcquireForm2700, cast temp form" << std::endl; +} +void FmsAcquireFormTestMax::FmsAcquireForm3200() +{ + std::cout << "START FmsAcquireForm3200" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normalc"; + std::string abilityName = "FormAbilityC"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3200, EVENT_CODE_3200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireForm3200, result:" << result; + + std::cout << "END FmsAcquireForm3200" << std::endl; +} +void FmsAcquireFormTestMax::FmsAcquireForm2800(std::string strFormId) +{ + std::cout << "START FmsAcquireForm2800, cast temp form" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData1 = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2800, EVENT_CODE_2800, eventData1); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800)); + std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800); + bool result3 = data3 == "false"; + EXPECT_TRUE(result3); + GTEST_LOG_(INFO) << "FmsAcquireForm2800, result:" << result3; + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result4 = data4 == "true"; + EXPECT_TRUE(result4); + GTEST_LOG_(INFO) << "FmsAcquireForm2800, delete form, result:" << result4; + std::cout << "END FmsAcquireForm2800, cast temp form" << std::endl; +} + +std::string FmsAcquireFormTestMax::FmsAcquireForm2900A() +{ + std::cout << "START FmsAcquireForm2900A, Provider A" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2900; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2900, EVENT_CODE_2900, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result; + } else { + GTEST_LOG_(INFO) << "FmsAcquireForm2900A, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result2; + + std::cout << "END FmsAcquireForm2900A, Provider A" << std::endl; + return strFormId; +} +std::string FmsAcquireFormTestMax::FmsAcquireForm2900B() +{ + std::cout << "START FmsAcquireForm2900B, Provider B" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2900_1; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2900_1, EVENT_CODE_2910, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FmsAcquireForm2900B, result:" << result; + } else { + GTEST_LOG_(INFO) << "FmsAcquireForm2900B, formId:" << strFormId; + } + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2911)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2911); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + GTEST_LOG_(INFO) << "FmsAcquireForm2900B, result:" << result2; + + std::cout << "END FmsAcquireForm2900B, Provider B" << std::endl; + return strFormId; +} +void FmsAcquireFormTestMax::FmsAcquireForm3000() +{ + std::cout << "START FmsAcquireForm3000" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3000; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3000, EVENT_CODE_3000, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000); + bool result = data == "false"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireForm3000, result:" << result; + + std::cout << "END FmsAcquireForm3000" << std::endl; +} +std::string FmsAcquireFormTestMax::FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName) +{ + std::cout << "START FmsAcquireFormTemp, add temp form" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); + bool result = !strFormId.empty(); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result; + } else { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formId:" << strFormId; + } + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1); + bool result2 = !data2.empty(); + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result2; + } else { + GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formData:" << data2; + } + std::cout << "END FmsAcquireFormTemp, add temp form" << std::endl; + + return strFormId; +} + +bool FmsAcquireFormTestMax::FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName) +{ + std::cout << "START FmsAcquireFormTempForFailed, add temp form" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); + std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); + bool result = strFormId.empty(); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormTempForFailed, result:" << result; + + std::cout << "END FmsAcquireFormTempForFailed, add temp form" << std::endl; + + return result; +} + +void FmsAcquireFormTestMax::FmsAcquireFormDeleteA(const std::string &strFormId) +{ + std::cout << "START FmsAcquireFormDeleteA, start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityA"; + std::cout << "START FmsAcquireFormDeleteA, bundleName: " << bundleName << std::endl; + std::cout << "START FmsAcquireFormDeleteA, abilityName: " << abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormDeleteA, delete form, result:" << result; + + std::cout << "END FmsAcquireFormDeleteA end" << std::endl; +} + +void FmsAcquireFormTestMax::FmsAcquireFormDeleteB(const std::string &strFormId) +{ + std::cout << "START FmsAcquireFormDeleteB, start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normalb"; + std::string abilityName = "FormAbilityB"; + std::cout << "START FmsAcquireFormDeleteB, bundleName: " << bundleName << std::endl; + std::cout << "START FmsAcquireFormDeleteB, abilityName: " << abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormDeleteB, delete form, result:" << result; + + std::cout << "END FmsAcquireFormDeleteB end" << std::endl; +} +void FmsAcquireFormTestMax::FmsAcquireFormDeleteC(const std::string &strFormId) +{ + std::cout << "START FmsAcquireFormDeleteC, start." << std::endl; + std::string bundleName = "com.ohos.form.manager.normalc"; + std::string abilityName = "FormAbilityC"; + std::cout << "START FmsAcquireFormDeleteC, bundleName: " << bundleName << std::endl; + std::cout << "START FmsAcquireFormDeleteC, abilityName: " << abilityName << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = strFormId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); + // wait delete form + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FmsAcquireFormDeleteC, delete form, result:" << result; + + std::cout << "END FmsAcquireFormDeleteC end" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_delete_form_test/BUILD.gn b/test/systemtest/common/fms/fms_delete_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..17cffb293de605abdf451b6b668e7561a53e0e2d --- /dev/null +++ b/test/systemtest/common/fms/fms_delete_form_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("FormDeleteFormTest") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "fms_delete_form_test.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"FMSDeleteFormTest\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":FormDeleteFormTest" ] +} diff --git a/test/systemtest/common/fms/fms_delete_form_test/fms_delete_form_test.cpp b/test/systemtest/common/fms/fms_delete_form_test/fms_delete_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..045002daac9380d4bd60cb58de2327c95bc1dc36 --- /dev/null +++ b/test/systemtest/common/fms/fms_delete_form_test/fms_delete_form_test.cpp @@ -0,0 +1,1204 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "system_ability_definition.h" +#include "system_test_form_util.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace OHOS { +namespace AppExecFwk { +class FmsDeleteFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + + static bool SubscribeEvent(); + + void SetUp(); + void TearDown(); + + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityManager; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber; + bool FmsGetCacheInfoByFormId(std::int64_t formId); + bool FmsGetHostInfoByFormId(std::int64_t formId, std::string hostBundleName); + bool FmsGetStorageFormInfos(std::int64_t formId); + bool FmsGetFormTimerTask(std::int64_t formId); + void FMS_deleteForm_1400_A(); + void FMS_deleteForm_1400_B(); + void FMS_deleteForm_1500_acquireForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId); + void FMS_deleteForm_1500_clearForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId); + void FMS_deleteForm_1500_Create_Delete(std::string delFormId, std::string &createFormId); + void FMS_deleteForm_1600_acquireForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId); + void FMS_deleteForm_1600_clearForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId); + void FMS_deleteForm_1600_Delete_Create(std::string delFormId, std::string &createFormId); + void FMS_deleteForm_1700_acquireForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId); + void FMS_deleteForm_1700_clearForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId); + void FMS_deleteForm_1700_Delete_Create(std::string delFormId, std::string &createFormId); + void FMS_acquireTempFormBatch(const std::string &bundleName, const std::string &abilityName, + const int count); + void FMS_acquireNormalFormBatch(const std::string &bundleName, const std::string &abilityName, + const int count); + void FMS_deleteFormBatch(const std::string &bundleName, const std::string &abilityName); +}; + +std::vector FmsDeleteFormTest::eventList = { + FORM_EVENT_ABILITY_ONACTIVED, + FORM_EVENT_RECV_DELETE_FORM_0100, + FORM_EVENT_RECV_DELETE_FORM_0200, + FORM_EVENT_RECV_DELETE_FORM_0300, + FORM_EVENT_RECV_DELETE_FORM_0400, + FORM_EVENT_RECV_DELETE_FORM_0500, + FORM_EVENT_RECV_DELETE_FORM_0600, + FORM_EVENT_RECV_DELETE_FORM_0700, + FORM_EVENT_RECV_DELETE_FORM_0800, + FORM_EVENT_RECV_DELETE_FORM_0900, + FORM_EVENT_RECV_DELETE_FORM_1000, + FORM_EVENT_RECV_DELETE_FORM_1100, + FORM_EVENT_RECV_DELETE_FORM_1200, + FORM_EVENT_RECV_DELETE_FORM_1201, + FORM_EVENT_RECV_DELETE_FORM_1400, + FORM_EVENT_RECV_DELETE_FORM_1401, + FORM_EVENT_RECV_DELETE_FORM_1500, + FORM_EVENT_RECV_DELETE_FORM_1501, + FORM_EVENT_RECV_DELETE_FORM_1502, + FORM_EVENT_RECV_DELETE_FORM_1600, + FORM_EVENT_RECV_DELETE_FORM_1601, + FORM_EVENT_RECV_DELETE_FORM_1602, + FORM_EVENT_RECV_DELETE_FORM_1700, + FORM_EVENT_RECV_DELETE_FORM_1701, + FORM_EVENT_RECV_DELETE_FORM_1702, + FORM_EVENT_RECV_ONE_NORMAL_FORM, + FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, + FORM_EVENT_RECV_ONE_NORMAL_FORM_B, + FORM_EVENT_RECV_ONE_NORMAL_FORM_B_DEL, + COMMON_EVENT_ON_DELETE, + FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, + FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, + FORM_EVENT_RECV_CLEAR_FORM_BATCH +}; + +FormEvent FmsDeleteFormTest::event = FormEvent(); +sptr FmsDeleteFormTest::abilityManager = nullptr; +std::shared_ptr FmsDeleteFormTest::subscriber = nullptr; +void FmsDeleteFormTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void FmsDeleteFormTest::SetUpTestCase() +{ + std::cout << "START Install============" << std::endl; + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void FmsDeleteFormTest::TearDownTestCase() +{ + std::cout << "START Uninstall============" << std::endl; + CommonEventManager::UnSubscribeCommonEvent(subscriber); +} + +void FmsDeleteFormTest::SetUp() +{ +} + +void FmsDeleteFormTest::TearDown() +{ + SystemTestFormUtil::CleanMsg(event); +} +bool FmsDeleteFormTest::SubscribeEvent() +{ + std::vector eventList = { + FORM_EVENT_ABILITY_ONACTIVED, + FORM_EVENT_RECV_DELETE_FORM_0100, + FORM_EVENT_RECV_DELETE_FORM_0200, + FORM_EVENT_RECV_DELETE_FORM_0300, + FORM_EVENT_RECV_DELETE_FORM_0400, + FORM_EVENT_RECV_DELETE_FORM_0500, + FORM_EVENT_RECV_DELETE_FORM_0600, + FORM_EVENT_RECV_DELETE_FORM_0700, + FORM_EVENT_RECV_DELETE_FORM_0800, + FORM_EVENT_RECV_DELETE_FORM_0900, + FORM_EVENT_RECV_DELETE_FORM_1000, + FORM_EVENT_RECV_DELETE_FORM_1100, + FORM_EVENT_RECV_DELETE_FORM_1200, + FORM_EVENT_RECV_DELETE_FORM_1201, + FORM_EVENT_RECV_DELETE_FORM_1400, + FORM_EVENT_RECV_DELETE_FORM_1401, + FORM_EVENT_RECV_DELETE_FORM_1500, + FORM_EVENT_RECV_DELETE_FORM_1501, + FORM_EVENT_RECV_DELETE_FORM_1502, + FORM_EVENT_RECV_DELETE_FORM_1600, + FORM_EVENT_RECV_DELETE_FORM_1601, + FORM_EVENT_RECV_DELETE_FORM_1602, + FORM_EVENT_RECV_DELETE_FORM_1700, + FORM_EVENT_RECV_DELETE_FORM_1701, + FORM_EVENT_RECV_DELETE_FORM_1702, + FORM_EVENT_RECV_ONE_NORMAL_FORM, + FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, + FORM_EVENT_RECV_ONE_NORMAL_FORM_B, + FORM_EVENT_RECV_ONE_NORMAL_FORM_B_DEL, + COMMON_EVENT_ON_DELETE, + FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, + FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, + FORM_EVENT_RECV_CLEAR_FORM_BATCH + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +/** + * @tc.number: FMS_deleteForm_0100 + * @tc.name: host is not a system app + * @tc.desc: 1.delete the form that formID is 1 + * 2.Verify the result is false + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0100, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_deleteForm_0100" << std::endl; + + std::string bundleName = "com.ohos.form.manager.notsystemapp"; + std::string abilityName = "FormAbilityNotSys"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_0100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0100, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0100, EVENT_CODE_100)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0100, EVENT_CODE_100); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0100, result:" << result; + } + + std::cout << "============END FMS_deleteForm_0100" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0200 + * @tc.name: host does not have permission + * @tc.desc: 1.delete the form that formID is 1 + * 2.Verify the result is false + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0200, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_deleteForm_0200" << std::endl; + + std::string bundleName = "com.ohos.form.manager.nopermission"; + std::string abilityName = "FormAbilityNoPerm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_0200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0200, EVENT_CODE_200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0200, EVENT_CODE_200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0200, EVENT_CODE_200); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0200, result:" << result; + } + + std::cout << "============END FMS_deleteForm_0200" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0300 + * @tc.name: formID id is error(formID < 0) + * @tc.desc: 1.delete the form + * 2.Verify the result is false + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0300, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_deleteForm_0300" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_0300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0300, EVENT_CODE_300, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0300, EVENT_CODE_300)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0300, EVENT_CODE_300); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0300, result:" << result; + } + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_0300" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0400 + * @tc.name: formID id is error(formID = 0) + * @tc.desc: 1.delete the form + * 2.Verify the result is false + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0400, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_deleteForm_0400" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_0400; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0400, EVENT_CODE_400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0400, EVENT_CODE_400)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0400, EVENT_CODE_400); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0400, result:" << result; + } + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_0400" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0500 + * @tc.name: formID id is error because formId is not self + * @tc.desc: 1.host A create a formA + * 2.host B delete the formA + * 2.Verify the result is false + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0500, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_deleteForm_0500" << std::endl; + + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + + GTEST_LOG_(INFO) << "FMS_deleteForm_0500, data:[" << data << "]" << std::endl; + bool result1 = data != ""; + EXPECT_TRUE(result1); + + if (data != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityDeleteForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = data; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0500, EVENT_CODE_500, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0500, EVENT_CODE_500)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0500, EVENT_CODE_500); + bool result2 = data2 == "false"; + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0500, result2:" << result2; + } + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, data); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + } + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_deleteForm_0500" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0600 + * @tc.name: Delete a normal form and the form reference is not 0 after deletion + * @tc.desc: 1.host A create a normal formA + * 2.host B create a form with formA's ID + * 3.delete formA, and verify the result is true + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0600, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_deleteForm_0600" << std::endl; + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + GTEST_LOG_(INFO) << "FMS_deleteForm_0600, formOne:[" << formOne << "]" << std::endl; + if (formOne != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityDeleteForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = formOne; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0600, EVENT_CODE_600, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0600, EVENT_CODE_600)); + std::string formTwo = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0600, EVENT_CODE_600); + bool result = formTwo == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0600, result:" << result; + } + // can't receive onDelete + EXPECT_EQ(-1, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + + bool cacheRes = FmsGetCacheInfoByFormId(atoll(formOne.c_str())); + bool hostRes = FmsGetHostInfoByFormId(atoll(formOne.c_str()), "com.ohos.form.manager.normal"); + bool storageRes = FmsGetStorageFormInfos(atoll(formOne.c_str())); + EXPECT_TRUE(cacheRes); + EXPECT_FALSE(hostRes); + EXPECT_TRUE(storageRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_0600" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0700 + * @tc.name: After deleting a normal form, the form reference is 0. + * After deleting a form, there are still created normal forms in FMS. + * @tc.desc: 1.host A an host B create one normal card respectively + * 2.host A delete the form and verify the result is true + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0700, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_deleteForm_0700" << std::endl; + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + GTEST_LOG_(INFO) << "FMS_deleteForm_0700, formOne:[" << formOne << "]" << std::endl; + EXPECT_TRUE(formOne != ""); + if (formOne != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityDeleteForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = formOne; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0700, EVENT_CODE_700, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0700, EVENT_CODE_700)); + std::string formTwo = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0700, EVENT_CODE_700); + GTEST_LOG_(INFO) << "FMS_deleteForm_0700, formTwo:[" << formTwo << "]" << std::endl; + bool result = (formTwo != "false" && formTwo != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0700, result:" << result; + } + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + std::string onDeleteData = SystemTestFormUtil::GetData(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK); + EXPECT_TRUE(onDeleteData == formTwo); + bool cacheRes = FmsGetCacheInfoByFormId(atoll(formTwo.c_str())); + bool storageRes = FmsGetStorageFormInfos(atoll(formTwo.c_str())); + bool timerRes = FmsGetFormTimerTask(atoll(formTwo.c_str())); + EXPECT_FALSE(cacheRes); + EXPECT_FALSE(storageRes); + EXPECT_FALSE(timerRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_0700" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0800 + * @tc.name: After deleting a normal form, there is no created normal form in FMS. + * @tc.desc: 1.host create one normal card + * 2.host delete the form and verify the result is true + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0800, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_deleteForm_0800" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_0800; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0800, EVENT_CODE_800, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0800, EVENT_CODE_800)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0800, EVENT_CODE_800); + bool result = (data != "false" && data != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0800, result:" << result; + } + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + std::string onDeleteData = SystemTestFormUtil::GetData(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK); + EXPECT_TRUE(onDeleteData == data); + bool cacheRes = FmsGetCacheInfoByFormId(atoll(data.c_str())); + bool storageRes = FmsGetStorageFormInfos(atoll(data.c_str())); + bool timerRes = FmsGetFormTimerTask(atoll(data.c_str())); + EXPECT_FALSE(cacheRes); + EXPECT_FALSE(storageRes); + EXPECT_FALSE(timerRes); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_0800" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_0900 + * @tc.name: Form ID error (FormID does not exist) + * @tc.desc: 1.host create one normal card + * 2.host delete the form + * 3.host delete the form again and verify the result is false + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0900, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_deleteForm_0900" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_0900; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_0900, EVENT_CODE_900, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_0900, EVENT_CODE_900)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_0900, EVENT_CODE_900); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_0900, result:" << result; + } + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_deleteForm_0900" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_1000 + * @tc.name: You can delete a card after releasing it + * @tc.desc: 1.host create one normal card + * 2.host release the form + * 3.host delete the form and verify the result is true + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1000, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_deleteForm_1000" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_1000; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1000, EVENT_CODE_1000, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1000, EVENT_CODE_1000)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1000, EVENT_CODE_1000); + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1000, result:" << result; + } + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_deleteForm_1000" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_1100 + * @tc.name: When deleting a temporary form, cache data is deleted. + * @tc.desc: 1.host a and b create one temporary card respectively + * 2.host a delete the form and verify the result is true + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1100, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_deleteForm_1100" << std::endl; + + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "true"; // temp form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + + GTEST_LOG_(INFO) << "FMS_deleteForm_1100, formOne:[" << formOne << "]" << std::endl; + if (formOne != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityDeleteForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = formOne; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1100, EVENT_CODE_1100, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1100, EVENT_CODE_1100)); + std::string formTwo = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1100, EVENT_CODE_1100); + GTEST_LOG_(INFO) << "FMS_deleteForm_1100, formTwo:[" << formTwo << "]" << std::endl; + bool result = (formTwo != "false" && formTwo != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1100, result:" << result; + } + // can receive onDelete + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + std::string onDeleteData = SystemTestFormUtil::GetData(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK); + GTEST_LOG_(INFO) << "00000, onDeleteData:[" << onDeleteData << "]" << std::endl; + EXPECT_TRUE(onDeleteData == formTwo); + + bool cacheRes = FmsGetCacheInfoByFormId(atoll(formTwo.c_str())); + EXPECT_FALSE(cacheRes); + bool cacheRes2 = FmsGetCacheInfoByFormId(atoll(formOne.c_str())); + EXPECT_TRUE(cacheRes2); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + } + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_deleteForm_1100" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_1200 + * @tc.name: single host (using a single thread) continuously deletes multiple normal and temporary forms + * @tc.desc: 1.There are 5 normal forms and 5 temporary forms created by the single host + * 2.single host (using a single thread) deletes 10 deletes successfully + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1200, Function | MediumTest | Level2) +{ + int createFormCount = 10; + std::string formIds[10] = {""}; + std::cout << "============START FMS_deleteForm_1200" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + + for (int i=0; i>index:" << i; + bool result = (formIds[i] != "false" && formIds[i] != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1200, result:" << result; + } + } + for (int i=0; i>index:" << i; + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1201, result:" << result; + } + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_1200" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_1400 + * @tc.name: Multiple hosts delete normal and temporary forms respectively + * @tc.desc: 1.host A and B have 5 normal forms and 5 temporary forms respectively. + * 2.host A and B delete their forms successively. + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1400, Function | MediumTest | Level2) +{ + std::cout << "============START FMS_deleteForm_1400" << std::endl; + FMS_deleteForm_1400_A(); + FMS_deleteForm_1400_B(); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_1400" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_1500 + * @tc.name: create 256 temporary forms and delete one + * @tc.desc: 1.create 256 temporary forms and delete one + * 2.create one temporary form successfully . + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1500, Function | MediumTest | Level2) +{ + std::cout << "============START FMS_deleteForm_1500" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + int count = Constants::MAX_RECORD_PER_APP - 1; + FMS_acquireTempFormBatch(bundleName, abilityName, count); + std::string formId = ""; + FMS_deleteForm_1500_acquireForm(bundleName, abilityName, formId); + FMS_deleteForm_1500_clearForm(bundleName, abilityName, formId); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_1500" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_1600 + * @tc.name: create 256 normal forms and delete one + * @tc.desc: 1.create 256 normal forms and delete one + * 2.create one normal form successfully . + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1600, Function | MediumTest | Level2) +{ + std::cout << "============START FMS_deleteForm_1600" << std::endl; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + int count = Constants::MAX_RECORD_PER_APP - 1; + FMS_acquireNormalFormBatch(bundleName, abilityName, count); + std::string formId = ""; + FMS_deleteForm_1600_acquireForm(bundleName, abilityName, formId); + FMS_deleteForm_1600_clearForm(bundleName, abilityName, formId); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_1600" << std::endl; +} + +/** + * @tc.number: FMS_deleteForm_1700 + * @tc.name: When the number of normal forms of multiple hosts reaches 512, + * you can delete forms and create forms + * @tc.desc: 1.host A create 200 normal forms + * 2.host B create 200 normal forms + * 3.host C create 112 normal forms + * 4.host C delete one normal form and create one normal form successfully . + */ +HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1700, Function | MediumTest | Level2) +{ + std::cout << "============START FMS_deleteForm_1700" << std::endl; + std::string bundleNameA = "com.ohos.form.manager.commona"; + std::string abilityNameA = "FormAbilityCommonA"; + int countA = 200; + FMS_acquireNormalFormBatch(bundleNameA, abilityNameA, countA); + + std::string bundleNameB = "com.ohos.form.manager.commonb"; + std::string abilityNameB = "FormAbilityCommonB"; + int countB = 200; + FMS_acquireNormalFormBatch(bundleNameB, abilityNameB, countB); + + std::string bundleNameC = "com.ohos.form.manager.normal"; + std::string abilityNameC = "FormAbilityDeleteForm"; + int countC = 111; + FMS_acquireNormalFormBatch(bundleNameC, abilityNameC, countC); + + std::string formId = ""; + FMS_deleteForm_1700_acquireForm(bundleNameC, abilityNameC, formId); + FMS_deleteForm_1700_clearForm(bundleNameC, abilityNameC, formId); + FMS_deleteFormBatch(bundleNameA, abilityNameA); + FMS_deleteFormBatch(bundleNameB, abilityNameB); + FMS_deleteFormBatch(bundleNameC, abilityNameC); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_deleteForm_1700" << std::endl; +} + +bool FmsDeleteFormTest::FmsGetCacheInfoByFormId(std::int64_t formId) +{ + std::string cachedData = SystemTestFormUtil::QueryFormInfoByFormId(formId); + bool cacheRes = false; + std::string formIdStr = std::to_string(formId); + std::string::size_type pos = cachedData.find(formIdStr); + if (pos != cachedData.npos) { + std::cout << "######### formId is found in cache" << std::endl; + cacheRes = true; + } else { + std::cout << "######### Can't find formId in cache!" << std::endl; + cacheRes = false; + } + return cacheRes; +} +bool FmsDeleteFormTest::FmsGetHostInfoByFormId(std::int64_t formId, std::string hostBundleName) +{ + std::string hostData = SystemTestFormUtil::QueryFormInfoByFormId(formId); + bool hostRes = false; + std::string::size_type pos = hostData.find(hostBundleName); + if (pos != hostData.npos) { + std::cout << "######### hostBundleName is found in cache" << std::endl; + hostRes = true; + } else { + std::cout << "######### Can't find hostBundleName in cache!" << std::endl; + hostRes = false; + } + return hostRes; +} +bool FmsDeleteFormTest::FmsGetStorageFormInfos(std::int64_t formId) +{ + std::string storageData = SystemTestFormUtil::QueryStorageFormInfos(); + bool storageRes = false; + std::string formIdStr = std::to_string(formId); + std::string::size_type pos = storageData.find(formIdStr); + if (pos != storageData.npos) { + std::cout << "######### formId is found in storage" << std::endl; + storageRes = true; + } else { + std::cout << "######### Can't find formId in storage!" << std::endl; + storageRes = false; + } + return storageRes; +} +bool FmsDeleteFormTest::FmsGetFormTimerTask(std::int64_t formId) +{ + std::string timerRes = SystemTestFormUtil::QueryFormTimerByFormId(formId); + if (timerRes == "true") { + std::cout << "######### formId is found in TimerTask" << std::endl; + return true; + } else { + std::cout << "######### Can't find formId in TimerTask!" << std::endl; + return false; + } +} +void FmsDeleteFormTest::FMS_deleteForm_1400_A() +{ + int createFormCount = 10; + std::string formIds[10] = {""}; + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + + for (int i = 0; i < createFormCount; i++) { + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + int tmp = 5; + std::string eventData = ((i / tmp == 1) ? "true" : "false"); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_1400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + formIds[i] = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1400[A][#Create#]formId:[" << formIds[i] << "]======>>index:" << i; + bool result = (formIds[i] != "false" && formIds[i] != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1400[A], result:" << result; + } + } + for (int i = 0; i < createFormCount; i++) { + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = formIds[i]; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_1400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1400[A][#Delete#]formId:[" << formIds[i] << "]======>>index:" << i; + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1401[A], result:" << result; + } + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + } +} +void FmsDeleteFormTest::FMS_deleteForm_1400_B() +{ + int createFormCount = 10; + std::string formIds[10] = {""}; + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + + for (int i = 0; i < createFormCount; i++) { + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + int tmp = 5; + std::string eventData = ((i / tmp == 1) ? "true" : "false"); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1400, EVENT_CODE_1400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1400, EVENT_CODE_1400)); + formIds[i] = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1400, EVENT_CODE_1400); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1400[B][#Create#]formId:[" << formIds[i] << "]======>>index:" << i; + bool result = (formIds[i] != "false" && formIds[i] != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1400[B], result:" << result; + } + } + for (int i = 0; i < createFormCount; i++) { + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = formIds[i]; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1401, EVENT_CODE_1401, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1401, EVENT_CODE_1401)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1401, EVENT_CODE_1401); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1400[B][#Delete#]formId:[" << formIds[i] << "]======>>index:" << i; + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1401[B], result:" << result; + } + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, COMMON_EVENT_ON_DELETE, + FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK)); + } +} +void FmsDeleteFormTest::FMS_deleteForm_1500_Create_Delete(std::string delFormId, std::string &createFormId) +{ + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // delete one and create one + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1501, EVENT_CODE_1510, delFormId); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1501, EVENT_CODE_1510)); + createFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1501, EVENT_CODE_1510); + bool result = (createFormId != "deleteError" && createFormId != "acquireError" && createFormId != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1501, result:" << result; + } +} +void FmsDeleteFormTest::FMS_deleteForm_1600_Delete_Create(std::string delFormId, std::string &createFormId) +{ + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // delete one and create one + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1601, EVENT_CODE_1610, delFormId); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1601, EVENT_CODE_1610)); + createFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1601, EVENT_CODE_1610); + bool result = (createFormId != "deleteError" && createFormId != "acquireError" && createFormId != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1601, result:" << result; + } +} +void FmsDeleteFormTest::FMS_deleteForm_1700_Delete_Create(std::string delFormId, std::string &createFormId) +{ + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityDeleteForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // delete one and create one + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1701, EVENT_CODE_1701, delFormId); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1701, EVENT_CODE_1701)); + createFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1701, EVENT_CODE_1701); + bool result = (createFormId != "deleteError" && createFormId != "acquireError" && createFormId != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1701, result:" << result; + } +} +void FmsDeleteFormTest::FMS_deleteForm_1500_acquireForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_1500; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1500, EVENT_CODE_1500, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1500, EVENT_CODE_1500)); + std::string formId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1500, EVENT_CODE_1500); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1500 [#Create#]formId:[" << formId << "]"; + bool result = (formId != "false" && formId != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1500, result:" << result; + } + FMS_deleteForm_1500_Create_Delete(formId, outformId); +} +void FmsDeleteFormTest::FMS_deleteForm_1500_clearForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = outformId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1502, EVENT_CODE_1511, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1502, EVENT_CODE_1511)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1502, EVENT_CODE_1511); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1500_clearForm [#Delete#]formId:[" << outformId << "]"; + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1500_clearForm, result:" << result; + } + FMS_deleteFormBatch(bundleName, abilityName); +} +void FmsDeleteFormTest::FMS_deleteForm_1600_acquireForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_1600; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1600, EVENT_CODE_1600, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1600, EVENT_CODE_1600)); + std::string formId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1600, EVENT_CODE_1600); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1600 [#Create#]formId:[" << formId << "]"; + bool result = (formId != "false" && formId != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1600, result:" << result; + } + FMS_deleteForm_1600_Delete_Create(formId, outformId); +} +void FmsDeleteFormTest::FMS_deleteForm_1600_clearForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = outformId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1602, EVENT_CODE_1611, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1602, EVENT_CODE_1611)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1602, EVENT_CODE_1611); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1600 [#Delete#]formId:[" << outformId << "]"; + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1600, result:" << result; + } + FMS_deleteFormBatch(bundleName, abilityName); +} +void FmsDeleteFormTest::FMS_deleteForm_1700_acquireForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_DELETE_FORM_1700; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1700, EVENT_CODE_1700, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1700, EVENT_CODE_1700)); + std::string formId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1700, EVENT_CODE_1700); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1700 [#Create#]formId:[" << formId << "]"; + bool result = (formId != "false" && formId != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1700, result:" << result; + } + FMS_deleteForm_1700_Delete_Create(formId, outformId); +} +void FmsDeleteFormTest::FMS_deleteForm_1700_clearForm(const std::string &bundleName, const std::string &abilityName, + std::string &outformId) +{ + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = outformId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_1702, EVENT_CODE_1702, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_1702, EVENT_CODE_1702)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_1702, EVENT_CODE_1702); + GTEST_LOG_(INFO) << "========FMS_deleteForm_1700 [#Delete#]formId:[" << outformId << "]"; + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_deleteForm_1700, result:" << result; + } +} +void FmsDeleteFormTest::FMS_acquireTempFormBatch(const std::string &bundleName, const std::string &abilityName, + const int count) +{ + std::cout << "START FMS_acquireTempFormBatch" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = std::to_string(count); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_TEMP_FORM_BATCH, EVENT_CODE_TEMP_BATCH, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, + EVENT_CODE_TEMP_BATCH)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_TEMP_FORM_BATCH, + EVENT_CODE_TEMP_BATCH); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_acquireTempFormBatch, count: " << eventData; + } else { + GTEST_LOG_(INFO) << "FMS_acquireTempFormBatch, result:" << result; + } + std::cout << "END FMS_acquireTempFormBatch" << std::endl; +} +void FmsDeleteFormTest::FMS_acquireNormalFormBatch(const std::string &bundleName, const std::string &abilityName, + const int count) +{ + std::cout << "START FMS_acquireNormalFormBatch" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = std::to_string(count); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH, eventData); + + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_BATCH, EVENT_CODE_BATCH); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_acquireNormalFormBatch, count: " << eventData; + } else { + GTEST_LOG_(INFO) << "FMS_acquireNormalFormBatch, result:" << result; + } + std::cout << "END FMS_acquireNormalFormBatch" << std::endl; +} +void FmsDeleteFormTest::FMS_deleteFormBatch(const std::string &bundleName, const std::string &abilityName) +{ + std::cout << "START FMS_deleteFormBatch, delete forms" << std::endl; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + std::string eventData = FORM_EVENT_REQ_CLEAR_FORM_BATCH; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_CLEAR_FORM_BATCH, EVENT_CODE_TEMP, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_CLEAR_FORM_BATCH, EVENT_CODE_CLEAR_BATCH); + bool result = data == "true"; + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "FMS_deleteFormBatch, result:" << result; + std::cout << "END FMS_deleteFormBatch, delete forms" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_fuzz_test/BUILD.gn b/test/systemtest/common/fms/fms_fuzz_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..e381fe1e5ed021a3f49288ca0d59069b3a28b841 --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("fmsFuzzTest") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/fms_fuzz_test/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "src/fms_fuzz_test.cpp", + "src/fuzz_test_manager.cpp", + "src/get_param.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"fmsFuzzTest\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":fmsFuzzTest" ] +} diff --git a/test/systemtest/common/fms/fms_fuzz_test/fms_fuzz_test_config/config.json b/test/systemtest/common/fms/fms_fuzz_test/fms_fuzz_test_config/config.json new file mode 100755 index 0000000000000000000000000000000000000000..cd8c99c96d39561918cb3d8495d0ad9ab0a9745d --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/fms_fuzz_test_config/config.json @@ -0,0 +1,29 @@ +{ + "ExecutionTimes": 10, + "FormManagerAbility": { + "ReleaseForm": [], + "DeleteForm": [], + "AcquireForm": [], + "UpdateForm": [], + "CastTempForm": [], + "NotifyVisibleForms": [], + "NotifyInvisibleForms": [], + "SetFormNextRefreshTime": [], + "RequestForm":[], + "EnableUpdateForm": [], + "DisableUpdateForm": [], + "CheckFMSReady": [], + "GetAllFormsInfo":[], + "GetFormsInfoByApp": [], + "GetFormsInfoByModule": [], + "ProcessFormUpdate": [], + "ProcessFormUninstall": [], + "OnDeathReceived":[], + "OnCreate": [], + "OnDelete": [], + "OnCastTemptoNormal":[], + "OnUpdate": [], + "OnVisibilityChanged": [], + "OnTriggerEvent": [] + } +} diff --git a/test/systemtest/common/fms/fms_fuzz_test/include/fuzz_test_config_parser.h b/test/systemtest/common/fms/fms_fuzz_test/include/fuzz_test_config_parser.h new file mode 100755 index 0000000000000000000000000000000000000000..d042b5684e3c780e0e1c5fe54276cc7e10b2411d --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/include/fuzz_test_config_parser.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FUZZ_CONFIG_PARSER_H +#define FUZZ_CONFIG_PARSER_H + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +namespace OHOS { +const std::string FUZZ_TEST_CONFIG_FILE_PATH {"./config.json"}; + +const std::string FUZZ_TEST_MAIN_LOOP_KEY {"ExecutionTimes"}; + +struct FuzzTestData { + int32_t mainLoopFlag {0}; + std::vector methodVec {}; +}; + +class FuzzTestConfigParser { +public: + void ParseForFuzzTest(const std::string &path, FuzzTestData &ftd) + { + std::cout << __func__ << std::endl; + if (path.empty()) { + std::cout << __FUNCTION__ << " invalid file path, check!" << std::endl; + return; + } + + nlohmann::json jsonObj; + std::ifstream(path) >> jsonObj; + std::cout << path; + for (auto it = jsonObj.begin(); it != jsonObj.end(); ++it) { + if (!it.key().compare(FUZZ_TEST_MAIN_LOOP_KEY)) { + ftd.mainLoopFlag = it.value(); + continue; + } + + PushBackParam(it, ftd); + } + } + void PushBackParam(const auto &it, FuzzTestData &ftd) + { + auto className = it.key(); + if (it->is_structured()) { + for (auto itm = it->begin(); itm != it->end(); ++itm) { + auto methodName = itm.key(); + if (!(it->is_structured() && (it->size() != 0))) { + ftd.methodVec.push_back(className + methodName); + continue; + } + + std::string param {}; + for (auto itp = itm->begin(); itp != itm->end(); ++itp) { + auto tp = itp.value(); + param += tp; + } + ftd.methodVec.push_back(className + methodName + param); + } + } + } +}; +} // namespace OHOS +#endif // FUZZ_CONFIG_PARSER_H diff --git a/test/systemtest/common/fms/fms_fuzz_test/include/fuzz_test_manager.h b/test/systemtest/common/fms/fms_fuzz_test/include/fuzz_test_manager.h new file mode 100755 index 0000000000000000000000000000000000000000..913b6924e02c2dabea616a4622b77d855a8b0c5c --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/include/fuzz_test_manager.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FormManagerFuzzTest_H +#define FormManagerFuzzTest_H + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +namespace OHOS { +namespace AppExecFwk { +class FuzzTestManager { +public: + using std::shared_ptr Ptr; + ~FuzzTestManager() + {} + static Ptr GetInstance() + { + if (fuzzTestInstance == nullptr) { + fuzzTestInstance = std::shared_ptr(std::make_shared FuzzTestManager); + } + return fuzzTestInstance; + } + + void StartFuzzTest(); + +private: + void SetJsonFunction(std::string); + void SetExecutionTimes(uint16_t executionTimes); + FuzzTestManager(); + FuzzTestManager(FuzzTestManager &) = delete; + FuzzTestManager &operator=(const FuzzTestManager &) = delete; + static Ptr fuzzTestInstance; + uint16_t m_executionTimes {}; + std::unordered_map remainderMap_ {}; + std::unordered_map> callFunctionMap_ {}; + + void RegisterFormManagerAbility(); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_fuzz_test/include/get_param.h b/test/systemtest/common/fms/fms_fuzz_test/include/get_param.h new file mode 100755 index 0000000000000000000000000000000000000000..4e1245f9d28a9e02d22684908a2e7c0f493f321e --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/include/get_param.h @@ -0,0 +1,392 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 GET_PARAM_H +#define GET_PARAM_H +#include +#include +#include +#include + +#include "ability.h" +#include "form_info.h" +#include "form_js_info.h" +#include "pac_map.h" +#include "parcel.h" +#include "patterns_matcher.h" +#include "uri.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +bool GetBoolParam(); +uint8_t GetU8Param(); +unsigned int GetUIntParam(); +uint16_t GetU16Param(); +uint32_t GetU32Param(); +uint64_t GetU64Param(); +int8_t GetS8Param(); +int16_t GetS16Param(); +int32_t GetS32Param(); +int64_t GetS64Param(); +char32_t GetChar32Param(); + +short GetShortParam(); +long GetLongParam(); +int GetIntParam(); +double GetDoubleParam(); +float GetFloatParam(); +char GetCharParam(); +std::string GetStringParam(); +std::map GetS64S32MapParam(); +std::vector GetBoolVectorParam(); +std::vector GetShortVectorParam(); +std::vector GetLongVectorParam(); +std::vector GetIntVectorParam(); +std::vector GetFloatVectorParam(); +std::vector GetDoubleVectorParam(); +std::vector GetCharVectorParam(); +std::vector GetChar32VectorParam(); +std::vector GetStringVectorParam(); +template +std::vector GetUnsignVectorParam(); +std::vector GetS8VectorParam(); +std::vector GetS16VectorParam(); +std::vector GetS32VectorParam(); +std::vector GetS64VectorParam(); +std::shared_ptr GetParamAbility(); +OHOS::AppExecFwk::Want GetParamWant(); +OHOS::AppExecFwk::FormInfo GetParamFormInfo(); +std::vector GetmFormInfoVectorParam(); +OHOS::AppExecFwk::FormJsInfo GetParamFormJsInfo(); +std::shared_ptr GetParamFormCallback(); +sptr GetParamSptrAbility(); +OHOS::AppExecFwk::FormProviderData GetParamFormProviderData(); + +class GetParam : public Ability { +public: + GetParam(); + ~GetParam(); + + bool ReleaseForm(const int64_t formId); + + /** + * @brief Releases an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application, if isReleaseCache is + * false, this method is same as {@link #releaseForm(int)}, otherwise the Form Manager Service still store this + * form in the cache.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @param isReleaseCache Indicates whether to clear cache in service. + * @return Returns {@code true} if the form is successfully released; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be released by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ + bool ReleaseForm(const int64_t formId, const bool isReleaseCache); + + /** + * @brief Deletes an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application and the Form Manager + * Service no longer keeps the cache information about the form.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @return Returns {@code true} if the form is successfully deleted; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be deleted by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ + bool DeleteForm(const int64_t formId); + + /** + * @brief The form callback. + */ + class FormCallback { + public: + + /** + * @brief Called to notify the application that the {@code FormJsInfo} instance has been obtained after + * the application called the asynchronous method {@link Ability#acquireForm(Want, FormCallback)}. + * The application must present the form information on a specific page in this callback. + * + * @param result Specifies whether the asynchronous form acquisition process is successful. + * {@link FormCallback#OHOS_FORM_ACQUIRE_SUCCESS} indicates that the form + * is successfully obtained, and other values indicate that the process fails. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + virtual void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const = 0; + + /** + * @brief Called to notify the application that the {@code FormJsInfo} instance has been obtained after + * the application called the asynchronous method {@link Ability#acquireForm(Want, FormCallback)}. + * The application must present the form information on a specific page in this callback. + * + * @param result Specifies whether the asynchronous form acquisition process is successful. + * {@link FormCallback#OHOS_FORM_UPDATE_SUCCESS} indicates that the form is + * successfully obtained, and other values indicate that the process fails. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + virtual void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const = 0; + + /** + * @brief Called to notify the application that the {@code Form} provider has been uninstalled and the + * corresponding + * {@code Form} instance is no longer available. + * + * @param formId Indicates the ID of the {@code Form} instance provided by the uninstalled form provider. + */ + virtual void OnFormUninstall(const int64_t formId) const = 0; + }; + + /** + * @brief Obtains a specified form that matches the application bundle name, module name, form name, and + * other related information specified in the passed {@code Want}. + * + *

This method is asynchronous. After the {@link FormJsInfo} instance is obtained. + * + * @param formId Indicates the form ID. + * @param want Indicates the detailed information about the form to be obtained, including the bundle name, + * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data. + * @param callback Indicates the callback to be invoked whenever the {@link FormJsInfo} instance is obtained. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool AcquireForm(const int64_t formId, const Want &want, const std::shared_ptr callback); + + /** + * @brief Updates the content of a specified JS form. + * + *

This method is called by a form provider to update JS form data as needed. + * + * @param formId Indicates the form ID. + * @param formProviderData The data used to update the JS form displayed on the client. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool UpdateForm(const int64_t formId, const FormProviderData &formProviderData); + + /** + * @brief Cast temp form with formId. + * + * @param formId Indicates the form's ID. + * + * @return Returns {@code true} if the form is successfully casted; returns {@code false} otherwise. + */ + bool CastTempForm(const int64_t formId); + + /** + * @brief Sends a notification to the form framework to make the specified forms visible. + * + *

After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map)} + * will be called to notify the form provider of the form visibility change event.

+ * + * @param formIds Indicates the IDs of the forms to be made visible. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool NotifyVisibleForms(const std::vector &formIds); + + /** + * @brief Sends a notification to the form framework to make the specified forms invisible. + * + *

After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map)} + * will be called to notify the form provider of the form visibility change event.

+ * + * @param formIds Indicates the IDs of the forms to be made invisible. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool NotifyInvisibleForms(const std::vector &formIds); + + /** + * @brief Set form next refresh time. + * + *

This method is called by a form provider to set refresh time. + * + * @param formId Indicates the ID of the form to set refresh time. + * @param nextTime Indicates the next time gap now in seconds, can not be litter than 300 seconds. + * @return Returns {@code true} if seting succeed; returns {@code false} otherwise. + */ + + bool SetFormNextRefreshTime(const int64_t formId, const int64_t nextTime); + + /** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + void ProcessFormUpdate(const FormJsInfo &formJsInfo) override; + + /** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ + void ProcessFormUninstall(const int64_t formId) override; + + /** + * @brief Called to reacquire form and update the form host after the death callback is received. + * + */ + void OnDeathReceived() override; + + /** + * @brief Called to return a FormProviderInfo object. + * + *

You must override this method if your ability will serve as a form provider to provide a form for clients. + * The default implementation returns nullptr.

+ * + * @param want Indicates the detailed information for creating a FormProviderInfo. + * The Want object must include the form ID, form name of the form, + * which can be obtained from Ability#PARAM_FORM_IDENTITY_KEY, + * Ability#PARAM_FORM_NAME_KEY, and Ability#PARAM_FORM_DIMENSION_KEY, + * respectively. Such form information must be managed as persistent data for further form + * acquisition, update, and deletion. + * + * @return Returns the created FormProviderInfo object. + */ + virtual FormProviderInfo OnCreate(const Want &want) override; + + /** + * @brief Called to notify the form provider that a specified form has been deleted. Override this method if + * you want your application, as the form provider, to be notified of form deletion. + * + * @param formId Indicates the ID of the deleted form. + * @return None. + */ + virtual void OnDelete(const int64_t formId) override; + + /** + * @brief Called when the form provider is notified that a temporary form is successfully converted to + * a normal form. + * + * @param formId Indicates the ID of the form. + * @return None. + */ + virtual void OnCastTemptoNormal(const int64_t formId) override; + + /** + * @brief Called to notify the form provider to update a specified form. + * + * @param formId Indicates the ID of the form to update. + * @return none. + */ + virtual void OnUpdate(const int64_t formId) override; + + /** + * @brief Called when the form provider receives form events from the fms. + * + * @param formEventsMap Indicates the form events occurred. The key in the Map object indicates the form ID, + * and the value indicates the event type, which can be either FORM_VISIBLE + * or FORM_INVISIBLE. FORM_VISIBLE means that the form becomes visible, + * and FORM_INVISIBLE means that the form becomes invisible. + * @return none. + */ + virtual void OnVisibilityChanged(const std::map &formEventsMap) override; + /** + * @brief Called to notify the form provider to update a specified form. + * + * @param formId Indicates the ID of the form to update. + * @param message Form event message. + */ + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + /** + * @brief Requests for form data update. + * + * This method must be called when the application has detected that a system setting item (such as the language, + * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form + * provider automatically updates the form data (if there is any update) through the form framework, with the update + * process being unperceivable by the application. + * + * @param formId Indicates the ID of the form to update. + * @return Returns true if the update request is successfully initiated, returns false otherwise. + */ + bool RequestForm(const int64_t formId); + + /** + * @brief Requests for form data update, by passing a set of parameters (using Want) to the form provider. + * + * This method must be called when the application has detected that a system setting item (such as the language, + * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form + * provider automatically updates the form data (if there is any update) through the form framework, with the update + * process being unperceivable by the application. + * + * @param formId Indicates the ID of the form to update. + * @param want Indicates a set of parameters to be transparently passed to the form provider. + * @return Returns true if the update request is successfully initiated, returns false otherwise. + */ + bool RequestForm(const int64_t formId, const Want &want); + /** + * @brief Enable form update. + * + * @param formIds formIds of hostclient. + */ + bool EnableUpdateForm(const std::vector &formIds); + + /** + * @brief Disable form update. + * + * @param formIds formIds of hostclient. + */ + bool DisableUpdateForm(const std::vector &formIds); + + /** + * @brief Check form manager service ready. + * + * @return Returns true if form manager service ready; returns false otherwise. + */ + bool CheckFMSReady(); + + /** + * @brief Get All FormsInfo. + * + * @param formInfos Returns the forms' information of all forms provided. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ + bool GetAllFormsInfo(std::vector &formInfos); + + /** + * @brief Get forms info by application name. + * + * @param bundleName Application name. + * @param formInfos Returns the forms' information of the specify application name. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ + bool GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos); + + /** + * @brief Get forms info by application name and module name. + * + * @param bundleName Application name. + * @param moduleName Module name of hap. + * @param formInfos Returns the forms' information of the specify application name and module name. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ + bool GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector &formInfos); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_fuzz_test/src/fms_fuzz_test.cpp b/test/systemtest/common/fms/fms_fuzz_test/src/fms_fuzz_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..ee78075c9cadd75aa8f50c9ac8361f0800d96646 --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/src/fms_fuzz_test.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "../include/fuzz_test_manager.h" +#include "../include/get_param.h" +#include "nlohmann/json.hpp" + +using namespace testing::ext; + +namespace OHOS { +namespace AppExecFwk { +class FmsFuzzTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void FmsFuzzTest::SetUpTestCase() +{ + std::cout << "FmsFuzzTest SetUpTestCase" << std::endl; +} + +void FmsFuzzTest::TearDownTestCase() +{ + std::cout << "FmsFuzzTest TearDownTestCase" << std::endl; +} + +void FmsFuzzTest::SetUp() +{ + std::cout << "FmsFuzzTest SetUp" << std::endl; +} + +void FmsFuzzTest::TearDown() +{ + std::cout << "FmsFuzzTest TearDown" << std::endl; +} + +/** + * @tc.number: FMS_fuzztest_0100 + * @tc.name: form manager service stress test + * @tc.desc: 1.under root,there is a config.json + * 2../FmsFuzzTest; hilog > xxxx.log + */ +HWTEST_F(FmsFuzzTest, FMS_fuzztest_0100, Function | MediumTest | Level1) +{ + std::cout << "Begin FMS_fuzztest_0100" << std::endl; + + FormManagerFuzzTest::GetInstance()->StartFuzzTest(); + + std::cout << "End FMS_fuzztest_0100" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_fuzz_test/src/fuzz_test_manager.cpp b/test/systemtest/common/fms/fms_fuzz_test/src/fuzz_test_manager.cpp new file mode 100755 index 0000000000000000000000000000000000000000..352cb3dd7c7de70dffc4d40625e0a138c930ea78 --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/src/fuzz_test_manager.cpp @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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. + */ +#define private public +#define protected public + +#include +#include + +#include "ability.h" +#include "hilog_wrapper.h" +#include "../include/fuzz_test_config_parser.h" +#include "../include/get_param.h" +#include "../include/fuzz_test_manager.h" + +#undef private +#undef protected +using namespace OHOS::AppExecFwk; +namespace OHOS { +namespace AppExecFwk { +std::shared_ptr FuzzTestManager::fuzzTestInstance = nullptr; +const std::string formManagerAbilityKitName = "FormManagerAbility"; + +// RegisterFormManagerAbility +void FuzzTestManager::RegisterFormManagerAbility() +{ + RegisterFormManagerAbilityA(); + RegisterFormManagerAbilityB(); + RegisterFormManagerAbilityC(); +} + +void FuzzTestManager::RegisterFormManagerAbilityA() +{ + callFunctionMap_[formManagerAbilityKitName + "ReleaseForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->ReleaseForm(GetS64Param(), GetBoolParam()); + }; + callFunctionMap_[formManagerAbilityKitName + "DeleteForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->DeleteForm(GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "AcquireForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->AcquireForm(GetS64Param(), GetParamWant(), GetParamFormCallback()); + }; + callFunctionMap_[formManagerAbilityKitName + "UpdateForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->UpdateForm(GetS64Param(), GetParamFormProviderData()); + }; + callFunctionMap_[formManagerAbilityKitName + "CastTempForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->CastTempForm(GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "NotifyVisibleForms"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->NotifyVisibleForms(GetS64VectorParam()); + }; + callFunctionMap_[formManagerAbilityKitName + "NotifyInvisibleForms"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->NotifyInvisibleForms(GetS64VectorParam()); + }; + callFunctionMap_[formManagerAbilityKitName + "SetFormNextRefreshTime"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->SetFormNextRefreshTime(GetS64Param(), GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "RequestForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->RequestForm(GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "EnableUpdateForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->EnableUpdateForm(GetS64VectorParam()); + }; + callFunctionMap_[formManagerAbilityKitName + "DisableUpdateForm"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->DisableUpdateForm(GetS64VectorParam()); + }; +} + +void FuzzTestManager::RegisterFormManagerAbilityB() +{ + callFunctionMap_[formManagerAbilityKitName + "CheckFMSReady"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->CheckFMSReady(); + }; + callFunctionMap_[formManagerAbilityKitName + "GetAllFormsInfo"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + std::vector formInfos; + formManagerAbility->GetAllFormsInfo(formInfos); + }; + callFunctionMap_[formManagerAbilityKitName + "GetFormsInfoByApp"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + string bundleName = GetStringParam(); + std::vector formInfos; + formManagerAbility->GetFormsInfoByApp(bundleName, formInfos); + }; + callFunctionMap_[formManagerAbilityKitName + "GetFormsInfoByModule"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + string bundleName = GetStringParam(); + string moduleName = GetStringParam(); + std::vector formInfos; + formManagerAbility->GetFormsInfoByModule(bundleName, moduleName, formInfos); + }; +} + +void FuzzTestManager::RegisterFormManagerAbilityC() +{ + callFunctionMap_[formManagerAbilityKitName + "ProcessFormUpdate"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->ProcessFormUpdate(GetParamFormJsInfo()); + }; + callFunctionMap_[formManagerAbilityKitName + "ProcessFormUninstall"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->ProcessFormUninstall(GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "OnDeathReceived"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->OnDeathReceived(); + }; + callFunctionMap_[formManagerAbilityKitName + "OnCreate"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->OnCreate(GetParamWant()); + }; + callFunctionMap_[formManagerAbilityKitName + "OnDelete"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->OnDelete(GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "OnCastTemptoNormal"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->OnCastTemptoNormal(GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "OnUpdate"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->OnUpdate(GetS64Param()); + }; + callFunctionMap_[formManagerAbilityKitName + "OnVisibilityChanged"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->OnVisibilityChanged(GetS64S32MapParam()); + }; + callFunctionMap_[formManagerAbilityKitName + "OnTriggerEvent"] = []() { + std::shared_ptr formManagerAbility = GetParamAbility(); + formManagerAbility->OnTriggerEvent(GetS64Param(), GetStringParam()); + }; +} + +FuzzTestManager::FuzzTestManager() +{ + RegisterFormManagerAbility(); +} + +void FuzzTestManager::SetJsonFunction(std::string functionName) +{ + remainderMap_.emplace(functionName, m_executionTimes); +} + +void FuzzTestManager::SetExecutionTimes(uint16_t executionTimes) +{ + m_executionTimes = executionTimes; + for_each(remainderMap_.begin(), remainderMap_.end(), + [executionTimes](std::unordered_map::reference executionTimesTemp) { + executionTimesTemp.second = executionTimes; + }); +} + +int GetRandomInt(int minNum, int maxNum) +{ + return GetU16Param() % (maxNum - minNum + 1) + minNum; +} + +void action(int a) +{ + std::cout << "Interrupt signal (" << a << ") received.\n"; +} + +void FuzzTestManager::StartFuzzTest() +{ + std::cout << __func__ << std::endl; + OHOS::FuzzTestConfigParser jsonParser; + OHOS::FuzzTestData tempData; + + std::cout << "parseFromFile start" << std::endl; + jsonParser.ParseForFuzzTest(FUZZ_TEST_CONFIG_FILE_PATH, tempData); + std::cout << " ExecutionTimes :" << tempData.mainLoopFlag << std::endl; + for_each(tempData.methodVec.begin(), tempData.methodVec.end(), [this](std::vector::reference s) { + SetJsonFunction(s); + }); + SetExecutionTimes(tempData.mainLoopFlag); + + std::vector index; + std::unordered_map::iterator it = remainderMap_.begin(); + while (it != remainderMap_.end()) { + if (it->second <= 0) { + it = remainderMap_.erase(it); + } else { + index.push_back(it->first); + it++; + } + } + + std::cout << remainderMap_.size() << "--------fuzz test start--------" << callFunctionMap_.size() << std::endl; + for (;remainderMap_.size() > 0;) { + std::string functionName; + int offset = GetRandomInt(0, index.size() - 1); + functionName = index[offset]; + if (callFunctionMap_.find(functionName) != callFunctionMap_.end()) { + std::cout << "call function : " << functionName << std::endl; + callFunctionMap_[functionName](); + std::cout << "function end :" << functionName << std::endl; + } else { + std::cout << "can't find function : " << functionName << std::endl; + } + remainderMap_[functionName]--; + if (remainderMap_[functionName] <= 0) { + remainderMap_.erase(functionName); + index.erase(index.begin() + offset); + }; + } + std::cout << remainderMap_.size() << "--------fuzz test end--------" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/systemtest/common/fms/fms_fuzz_test/src/get_param.cpp b/test/systemtest/common/fms/fms_fuzz_test/src/get_param.cpp new file mode 100755 index 0000000000000000000000000000000000000000..b5c2ec92fc0542dc95b450459f1ce997485e03e8 --- /dev/null +++ b/test/systemtest/common/fms/fms_fuzz_test/src/get_param.cpp @@ -0,0 +1,460 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include + +#include "ability.h" +#include "values_bucket.h" +#include "../include/get_param.h" + +using namespace std; +using namespace OHOS::AppExecFwk; +using Uri = OHOS::Uri; +namespace OHOS { +namespace AppExecFwk { +const int zero = 0; +const int two = 2; +const int CHAR_MIN = -128; +const int CHAR_MAX = 127; +const int STRING_MAX = 256; +bool GetBoolParam() +{ + bool param; + if (GetIntParam() % two == zero) { + param = true; + } else { + param = false; + } + cout << "Bool param is: " << param << endl; + return param; +} + +size_t GenRandom(size_t min, size_t max) +{ + std::random_device rd; + static uniform_int_distribution u(min, max); + static default_random_engine e(rd()); + size_t param = u(e); + return param; +} + +int8_t GetS8Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT8_MIN, INT8_MAX); + static default_random_engine e(rd()); + int8_t param = u(e); + cout << "Int8_t param is: " << param << endl; + return param; +} +int16_t GetS16Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT16_MIN, INT16_MAX); + static default_random_engine e(rd()); + int16_t param = u(e); + cout << "Int16_t param is: " << param << endl; + return param; +} +int32_t GetS32Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT32_MIN, INT32_MAX); + static default_random_engine e(rd()); + int32_t param = u(e); + cout << "Int32_t param is: " << param << endl; + return param; +} + +int64_t GetS64Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT64_MIN, INT64_MAX); + static default_random_engine e(rd()); + int64_t param = u(e); + cout << "Int64_t param is: " << param << endl; + return param; +} + +template +T GetUnsignParam() +{ + std::random_device rd; + static uniform_int_distribution u; + static default_random_engine e(rd()); + T param = u(e); + return param; +} + +size_t GetSizeTParam() +{ + size_t param = GetUnsignParam(); + return param; +} + +uint8_t GetU8Param() +{ + uint8_t param = GetUnsignParam(); + cout << "Uint8_t param is: " << param << endl; + return param; +} + +unsigned int GetUIntParam() +{ + unsigned int param = GetUnsignParam(); + cout << "Unsigned int param is: " << param << endl; + return param; +} + +uint16_t GetU16Param() +{ + uint16_t param = GetUnsignParam(); + cout << "Uint16_t param is: " << param << endl; + return param; +} + +uint32_t GetU32Param() +{ + uint32_t param = GetUnsignParam(); + cout << "Uint32_t param is: " << param << endl; + return param; +} + +uint64_t GetU64Param() +{ + uint64_t param = GetUnsignParam(); + cout << "Uint64_t param is: " << param << endl; + return param; +} + +short GetShortParam() +{ + std::random_device rd; + static uniform_int_distribution u(SHRT_MIN, SHRT_MAX); + static default_random_engine e(rd()); + short param = u(e); + cout << "Short param is: " << param << endl; + return param; +} + +long GetLongParam() +{ + std::random_device rd; + static uniform_int_distribution u(LONG_MIN, LONG_MAX); + static default_random_engine e(rd()); + long param = u(e); + cout << "Long param is: " << param << endl; + return param; +} + +int GetIntParam() +{ + std::random_device rd; + static uniform_int_distribution<> u(INT_MIN, INT_MAX); + static default_random_engine e(rd()); + int param = u(e); + cout << "Int param is: " << param << endl; + return param; +} + +double GetDoubleParam() +{ + double param = 0; + std::random_device rd; + static uniform_real_distribution u(DBL_MIN, DBL_MAX); + static default_random_engine e(rd()); + param = u(e); + cout << "double param is: " << param << endl; + return param; +} + +float GetFloatParam() +{ + float param = 0; + std::random_device rd; + static uniform_real_distribution u(FLT_MIN, FLT_MAX); + static default_random_engine e(rd()); + param = u(e); + cout << "Float param is: " << param << endl; + return param; +} + +char GetCharParam() +{ + std::random_device rd; + static uniform_int_distribution<> u(CHAR_MIN, CHAR_MAX); + static default_random_engine e(rd()); + char param = u(e); + return param; +} + +char32_t GetChar32Param() +{ + char32_t param = ' '; + std::random_device rd; + static uniform_int_distribution u; + static default_random_engine e(rd()); + param = u(e); + return param; +} + +string GetStringParam() +{ + string param = ""; + char ch = GetCharParam(); + size_t len = GenRandom(0, 255); + while (len--) { + ch = GetCharParam(); + param += ch; + } + cout << "String param length is: " << param.length() << endl; + return param; +} + +std::map GetS64S32MapParam() +{ + map param; + size_t len = GenRandom(0, 255); + while (len--) { + int64_t int64Value = GetS64Param(); + int32_t int32Value = GetS32Param(); + param.insert(pair(int64Value, int32Value)); + } + cout << "int64_t, int32_t map param length is: " << param.size() << endl; + return param; +} + +template +vector GetUnsignVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + T t = GetUnsignParam(); + param.push_back(t); + } + cout << "Uint vector param length is: " << param.size() << endl; + return param; +} + +template +T GetClassParam() +{ + T param; + return param; +} + +std::vector GetBoolVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int t = GetBoolParam(); + param.push_back(t); + } + cout << "Bool vector param length is: " << param.size() << endl; + return param; +} + +std::vector GetShortVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + short t = GetShortParam(); + param.push_back(t); + } + cout << "Short vector param length is: " << param.size() << endl; + return param; +} + +std::vector GetLongVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + long t = GetLongParam(); + param.push_back(t); + } + cout << "Long vector param length is: " << param.size() << endl; + return param; +} + +vector GetIntVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int t = GetIntParam(); + param.push_back(t); + } + cout << "Int vector param length is: " << param.size() << endl; + return param; +} + +std::vector GetFloatVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + float t = GetIntParam(); + param.push_back(t); + } + cout << "Float vector param length is: " << param.size() << endl; + return param; +} + +std::vector GetDoubleVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + double t = GetIntParam(); + param.push_back(t); + } + cout << "Double vector param length is: " << param.size() << endl; + return param; +} + +vector GetCharVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + char t = GetCharParam(); + param.push_back(t); + } + cout << "Char vector param length is: " << param.size() << endl; + return param; +} + +vector GetChar32VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + char32_t t = GetChar32Param(); + param.push_back(t); + } + cout << "Char32_t vector param length is: " << param.size() << endl; + return param; +} + +vector GetStringVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + string t = GetStringParam(); + param.push_back(t); + } + cout << "String vector param length is: " << param.size() << endl; + return param; +} + +vector GetS8VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int8_t temp = GetS8Param(); + param.push_back(temp); + } + cout << "Int8_t vector param length is: " << param.size() << endl; + return param; +} + +vector GetS16VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int16_t temp = GetS16Param(); + param.push_back(temp); + } + cout << "Int16_t vector param length is: " << param.size() << endl; + return param; +} + +vector GetS32VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int32_t temp = GetS32Param(); + param.push_back(temp); + } + cout << "Int32_t vector param length is: " << param.size() << endl; + return param; +} + +vector GetS64VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int64_t temp = GetS64Param(); + param.push_back(temp); + } + cout << "Int32_t vector param length is: " << param.size() << endl; + return param; +} + +std::shared_ptr GetParamAbility() +{ + return make_shared(); +} + +OHOS::AppExecFwk::Want GetParamWant() +{ + return OHOS::AppExecFwk::Want(); +} + +OHOS::AppExecFwk::FormInfo GetParamFormInfo() +{ + return OHOS::AppExecFwk::FormInfo(); +} + +OHOS::AppExecFwk::FormJsInfo GetParamFormJsInfo() +{ + return OHOS::AppExecFwk::FormJsInfo(); +} + +std::shared_ptr GetParamFormCallback() +{ + return shared_ptr(); +} + +OHOS::AppExecFwk::FormProviderData GetParamFormProviderData() +{ + return OHOS::AppExecFwk::FormProviderData(); +} + +std::vector GetmFormInfoVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::FormInfo t = GetParamFormInfo(); + param.push_back(t); + } + cout << "FormInfo vector param length is: " << param.size() << endl; + return param; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/systemtest/common/fms/fms_performance_test/BUILD.gn b/test/systemtest/common/fms/fms_performance_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..667112559ec2286edb4ef11d7622e858c06a24e3 --- /dev/null +++ b/test/systemtest/common/fms/fms_performance_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("FmsPerformanceTest") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "fms_performance_test.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"FmsPerformanceTest\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":FmsPerformanceTest" ] +} diff --git a/test/systemtest/common/fms/fms_performance_test/fms_performance_config/fms_performance_config.json b/test/systemtest/common/fms/fms_performance_test/fms_performance_config/fms_performance_config.json new file mode 100755 index 0000000000000000000000000000000000000000..706a917a72ebb3a3d515e0e16d18a6f23a1b81ff --- /dev/null +++ b/test/systemtest/common/fms/fms_performance_test/fms_performance_config/fms_performance_config.json @@ -0,0 +1,3 @@ +{ + "ExecutionTimes": 5 +} diff --git a/test/systemtest/common/fms/fms_performance_test/fms_performance_test.cpp b/test/systemtest/common/fms/fms_performance_test/fms_performance_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..d9093e5201fdd658d2c750179f330c37018e6d07 --- /dev/null +++ b/test/systemtest/common/fms/fms_performance_test/fms_performance_test.cpp @@ -0,0 +1,803 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "system_test_form_util.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "performance_config_parser.h" +#include "system_ability_definition.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace OHOS { +namespace AppExecFwk { +const int FOUR = 4; +static PerformanceLevel pLevel_; +static int64_t totalTime = 0; +const std::string TEST_RESULT_PATH = "./performance_test_result.txt"; + +class FmsPerformanceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + static bool SubscribeEvent(); + static bool SavePerformanceTestResult(const std::string &testcase, const int64_t &timeValue); + + void SetUp(); + void TearDown(); + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + + // Test case + static void PerformanceTest_0100(); + static void PerformanceTest_0200(); + static void PerformanceTest_0300(); + static void PerformanceTest_0400(); + static void PerformanceTest_0500(); + static void PerformanceTest_0600(); + static void PerformanceTest_0700(); + static void PerformanceTest_1300(); + static void PerformanceTest_1400(); + static void PerformanceTest_1500(); + static void PerformanceTest_1600(); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityMs; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber_; +}; + +std::vector FmsPerformanceTest::eventList = { + FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_PERFORMANCE_TEST_0100, FORM_EVENT_RECV_PERFORMANCE_TEST_0200, + FORM_EVENT_RECV_PERFORMANCE_TEST_0300, FORM_EVENT_RECV_PERFORMANCE_TEST_0400, FORM_EVENT_RECV_PERFORMANCE_TEST_0500, + FORM_EVENT_RECV_PERFORMANCE_TEST_0600, FORM_EVENT_RECV_PERFORMANCE_TEST_0700, FORM_EVENT_RECV_PERFORMANCE_TEST_1300, + FORM_EVENT_RECV_PERFORMANCE_TEST_1400, FORM_EVENT_RECV_PERFORMANCE_TEST_1500, FORM_EVENT_RECV_PERFORMANCE_TEST_1600, +}; + +FormEvent FmsPerformanceTest::event = FormEvent(); +sptr FmsPerformanceTest::abilityMs = nullptr; +std::shared_ptr FmsPerformanceTest::subscriber_ = nullptr; +void FmsPerformanceTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +bool FmsPerformanceTest::SavePerformanceTestResult(const std::string &testcase, const int64_t &timeValue) +{ + std::ofstream o(TEST_RESULT_PATH, std::ios::app); + o.close(); + + std::fstream f(TEST_RESULT_PATH, std::ios::app); + if (!f.good()) { + return false; + } + + f << std::setw(FOUR) << testcase << " consuming:" << timeValue << " ms" << std::endl; + + f.close(); + return true; +} + +void FmsPerformanceTest::SetUpTestCase() +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + + PerformanceConfigParser pcp; + pcp.ParseForPerformance(PERFORMANCE_CONFIG_FILE_PATH, pLevel_); + std::cout << "performance test level : " + << "executionTimes : " << pLevel_.executionTimesLevel << std::endl; +} + +void FmsPerformanceTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + std::cout << "========performance test level : " + << "case execution Times : " << pLevel_.executionTimesLevel << std::endl; +} + +void FmsPerformanceTest::SetUp() +{ + std::ofstream o(TEST_RESULT_PATH); + o.close(); + std::fstream f(TEST_RESULT_PATH); + if (!f.good()) { + return; + } + f << std::setw(FOUR) << "total execution times:" << pLevel_.executionTimesLevel << std::endl; + + f.close(); +} + +void FmsPerformanceTest::TearDown() +{ + SystemTestFormUtil::CleanMsg(event); + + std::ofstream o(TEST_RESULT_PATH, std::ios::app); + o.close(); + std::fstream f(TEST_RESULT_PATH, std::ios::app); + if (!f.good()) { + return; + } + f << std::setw(FOUR) << "total time:" << totalTime << " ms" << std::endl; + + f.close(); +} +bool FmsPerformanceTest::SubscribeEvent() +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FmsPerformanceTest::PerformanceTest_0100() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // AcquireForm + std::string eventData = FORM_EVENT_REQ_PERFORMANCE_TEST_0100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_PERFORMANCE_TEST_0100, EVENT_CODE_100, eventData); + + // OnAcquired + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0100, EVENT_CODE_101)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0100, EVENT_CODE_101); + std::string formId = data; + + // OnUpdate + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0100, EVENT_CODE_102)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0100, EVENT_CODE_102); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_0100", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_0100 AcquireForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_0200() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // DeleteForm + std::string eventData = FORM_EVENT_REQ_PERFORMANCE_TEST_0100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0200, EVENT_CODE_200, eventData); + + // DeleteForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0200, EVENT_CODE_200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0200, EVENT_CODE_200); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_0200", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_0200 DeleteForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_0300() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // ReleaseForm + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_0300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0300, EVENT_CODE_300, eventData); + + // ReleaseForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0300, EVENT_CODE_300)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0300, EVENT_CODE_300); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_0300", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_0300 ReleaseForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_0400() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // CastTempForm + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_0400; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0400, EVENT_CODE_400, eventData); + + // CastTempForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0400, EVENT_CODE_400)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0400, EVENT_CODE_400); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_0400", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_0400 CastTempForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_0500() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // NotifyVisibleForms + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_0500; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0500, EVENT_CODE_500, eventData); + + // NotifyVisibleForms Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0500, EVENT_CODE_500)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0500, EVENT_CODE_500); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_0500", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_0500 NotifyVisibleForms, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_0600() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // NotifyInvisibleForms + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_0600; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0600, EVENT_CODE_600, eventData); + + // NotifyInvisibleForms Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0600, EVENT_CODE_600)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0600, EVENT_CODE_600); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_0600", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_0600 NotifyInvisibleForms, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_0700() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // RequestForm + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_0700; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_0700, EVENT_CODE_700, eventData); + + // RequestForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0700, EVENT_CODE_700)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_0700, EVENT_CODE_700); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_0700", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_0700 RequestForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_1300() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // GetAllFormsInfo + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_1300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1300, EVENT_CODE_1300, eventData); + + // GetAllFormsInfo Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1300, EVENT_CODE_1300)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1300, EVENT_CODE_1300); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_1300", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_1300 RequestForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_1400() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // GetAllFormsInfo + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_1300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1400, EVENT_CODE_1400, eventData); + + // GetAllFormsInfo Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1400, EVENT_CODE_1400)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1400, EVENT_CODE_1400); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_1400", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_1400 RequestForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_1500() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // GetAllFormsInfo + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_1500; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1500, EVENT_CODE_1500, eventData); + + // GetAllFormsInfo Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1500, EVENT_CODE_1500)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1500, EVENT_CODE_1500); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_1500", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_1500 RequestForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsPerformanceTest::PerformanceTest_1600() +{ + struct timespec time1 = {0}; + struct timespec time2 = {0}; + int64_t usecTimesA = 1000000000; + int64_t usecTimesB = 1000000; + int64_t consuming = 0; + + clock_gettime(CLOCK_REALTIME, &time1); + + std::string bundleName = "com.ohos.form.manager.performance"; + std::string abilityName = "FormAbilityPerformance"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // GetAllFormsInfo + std::string eventData = FORM_EVENT_RECV_PERFORMANCE_TEST_1600; + SystemTestFormUtil::PublishEvent(FORM_EVENT_RECV_PERFORMANCE_TEST_1600, EVENT_CODE_1600, eventData); + + // GetAllFormsInfo Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1600, EVENT_CODE_1600)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_PERFORMANCE_TEST_1600, EVENT_CODE_1600); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + clock_gettime(CLOCK_REALTIME, &time2); + consuming = (time2.tv_sec * usecTimesA + time2.tv_nsec - (time1.tv_sec * usecTimesA + time1.tv_nsec)) + / usecTimesB; + totalTime += consuming; + bool ret = FmsPerformanceTest::SavePerformanceTestResult("FMS_performanceTest_1600", consuming); + std::cout << "SavePerformanceTestResult: "<< ret << "consuming:" << consuming << std::endl; + GTEST_LOG_(INFO) << "FMS_performanceTest_1600 RequestForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +/** + * @tc.number : FMS_performanceTest_0100 + * @tc.name : AcquireForm performance test + * @tc.desc : Test the time required to AcquireForm + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_0100, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_0100" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_0100(); + std::cout << "FMS_performanceTest_0100 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_0100" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_0400 + * @tc.name : CastTempForm performance test + * @tc.desc : Test the time required to CastTempForm + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_0400, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_0400" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_0400(); + std::cout << "FMS_performanceTest_0400 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_0400" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_0300 + * @tc.name : ReleaseForm performance test + * @tc.desc : Test the time required to ReleaseForm + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_0300, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_0300" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_0300(); + std::cout << "FMS_performanceTest_0300 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_0300" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_0200 + * @tc.name : DeleteForm performance test + * @tc.desc : Test the time required to DeleteForm + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_0200, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_0200" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_0200(); + std::cout << "FMS_performanceTest_0200 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_0200" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_0500 + * @tc.name : NotifyVisibleForms performance test + * @tc.desc : Test the time required to NotifyVisibleForms + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_0500, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_0500" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_0500(); + std::cout << "FMS_performanceTest_0500 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_0500" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_0600 + * @tc.name : NotifyInvisibleForms performance test + * @tc.desc : Test the time required to NotifyInvisibleForms + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_0600, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_0600" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_0600(); + std::cout << "FMS_performanceTest_0600 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_0600" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_0700 + * @tc.name : RequestForm performance test + * @tc.desc : Test the time required to RequestForm + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_0700, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_0700" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_0700(); + std::cout << "FMS_performanceTest_0700 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_0700" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_1300 + * @tc.name : GetAllFormsInfo performance test + * @tc.desc : Test the time required to GetAllFormsInfo + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_1300, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_1300" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_1300(); + std::cout << "FMS_performanceTest_1300 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_1300" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_1400 + * @tc.name : GetFormsInfoByApp performance test + * @tc.desc : Test the time required to GetFormsInfoByApp + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_1400, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_1400" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_1400(); + std::cout << "FMS_performanceTest_1400 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_1400" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_1500 + * @tc.name : GetFormsInfoByModule performance test + * @tc.desc : Test the time required to GetFormsInfoByModule + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_1500, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_1500" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_1500(); + std::cout << "FMS_performanceTest_1500 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_1500" << std::endl; +} + +/** + * @tc.number : FMS_performanceTest_1600 + * @tc.name : CheckFMSReady performance test + * @tc.desc : Test the time required to CheckFMSReady + */ +HWTEST_F(FmsPerformanceTest, FMS_performanceTest_1600, Function | MediumTest | Level3) +{ + std::cout << "START FMS_performanceTest_1600" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < pLevel_.executionTimesLevel; iExecutionTimes++) { + FmsPerformanceTest::PerformanceTest_1600(); + std::cout << "FMS_performanceTest_1600 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_performanceTest_1600" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_performance_test/performance_config_parser.h b/test/systemtest/common/fms/fms_performance_test/performance_config_parser.h new file mode 100755 index 0000000000000000000000000000000000000000..de47019dbcc8d81a75a1d87a41abeca2be7bdac5 --- /dev/null +++ b/test/systemtest/common/fms/fms_performance_test/performance_config_parser.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 PERFORMANCE_CONFIG_PARSER_H +#define PERFORMANCE_CONFIG_PARSER_H + +#include +#include +#include + +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace AppExecFwk { +const std::string PERFORMANCE_CONFIG_FILE_PATH {"./fms_performance_config.json"}; + +const std::string PERFORMANCE_EXECUTION_TIMES_KEY {"ExecutionTimes"}; + +struct PerformanceLevel { + int32_t executionTimesLevel {1}; +}; + +class PerformanceConfigParser { +public: + void ParseForPerformance(const std::string &path, PerformanceLevel &stlevel) + { + std::ifstream jf(path); + if (!jf.is_open()) { + std::cout << "json file can not open!" << std::endl; + return; + } + nlohmann::json jsonObj; + jf >> jsonObj; + const auto &jsonObjEnd = jsonObj.end(); + if (jsonObj.find(PERFORMANCE_EXECUTION_TIMES_KEY) != jsonObjEnd) { + jsonObj.at(PERFORMANCE_EXECUTION_TIMES_KEY).get_to(stlevel.executionTimesLevel); + if (stlevel.executionTimesLevel == 0) { + stlevel.executionTimesLevel = 1; + } + } + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // PERFORMANCE_CONFIG_PARSER_H diff --git a/test/systemtest/common/fms/fms_release_form_test/BUILD.gn b/test/systemtest/common/fms/fms_release_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..47b1c1d1d35a27860e4098da77b58c12ebbc2bde --- /dev/null +++ b/test/systemtest/common/fms/fms_release_form_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("FormReleaseFormTest") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "fms_release_form_test.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"FMSReleaseFormTest\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":FormReleaseFormTest" ] +} diff --git a/test/systemtest/common/fms/fms_release_form_test/fms_release_form_test.cpp b/test/systemtest/common/fms/fms_release_form_test/fms_release_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f12f44272edd14f46b89189958722d80bdbc0125 --- /dev/null +++ b/test/systemtest/common/fms/fms_release_form_test/fms_release_form_test.cpp @@ -0,0 +1,789 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "system_ability_definition.h" +#include "system_test_form_util.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace OHOS { +namespace AppExecFwk { +class FmsReleaseFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + + static bool SubscribeEvent(); + + void SetUp(); + void TearDown(); + + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityManager; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber; + bool FmsGetCacheInfoByFormId(std::int64_t formId); + bool FmsGetHostInfoByFormId(std::int64_t formId, std::string hostBundleName); + bool FmsGetStorageFormInfos(std::int64_t formId); + bool FmsGetFormTimerTask(std::int64_t formId); +}; + +std::vector FmsReleaseFormTest::eventList = { + FORM_EVENT_ABILITY_ONACTIVED, + FORM_EVENT_RECV_RELEASE_FORM_0100, + FORM_EVENT_RECV_RELEASE_FORM_0200, + FORM_EVENT_RECV_RELEASE_FORM_0300, + FORM_EVENT_RECV_RELEASE_FORM_0400, + FORM_EVENT_RECV_RELEASE_FORM_0500, + FORM_EVENT_RECV_RELEASE_FORM_0600, + FORM_EVENT_RECV_RELEASE_FORM_0700, + FORM_EVENT_RECV_RELEASE_FORM_0800, + FORM_EVENT_RECV_RELEASE_FORM_0900, + FORM_EVENT_RECV_RELEASE_FORM_1000, + FORM_EVENT_RECV_RELEASE_FORM_1100, + FORM_EVENT_RECV_RELEASE_FORM_1200, + FORM_EVENT_RECV_RELEASE_FORM_1300, + FORM_EVENT_RECV_RELEASE_FORM_1400, + FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, + FORM_EVENT_RECV_ONE_NORMAL_FORM, + FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL +}; + +FormEvent FmsReleaseFormTest::event = FormEvent(); +sptr FmsReleaseFormTest::abilityManager = nullptr; +std::shared_ptr FmsReleaseFormTest::subscriber = nullptr; +void FmsReleaseFormTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void FmsReleaseFormTest::SetUpTestCase() +{ + std::cout << "START Install============" << std::endl; + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void FmsReleaseFormTest::TearDownTestCase() +{ + std::cout << "START Uninstall============" << std::endl; + CommonEventManager::UnSubscribeCommonEvent(subscriber); +} + +void FmsReleaseFormTest::SetUp() +{ +} + +void FmsReleaseFormTest::TearDown() +{ + SystemTestFormUtil::CleanMsg(event); +} +bool FmsReleaseFormTest::SubscribeEvent() +{ + std::vector eventList = { + FORM_EVENT_ABILITY_ONACTIVED, + FORM_EVENT_RECV_RELEASE_FORM_0100, + FORM_EVENT_RECV_RELEASE_FORM_0200, + FORM_EVENT_RECV_RELEASE_FORM_0300, + FORM_EVENT_RECV_RELEASE_FORM_0400, + FORM_EVENT_RECV_RELEASE_FORM_0500, + FORM_EVENT_RECV_RELEASE_FORM_0600, + FORM_EVENT_RECV_RELEASE_FORM_0700, + FORM_EVENT_RECV_RELEASE_FORM_0800, + FORM_EVENT_RECV_RELEASE_FORM_0900, + FORM_EVENT_RECV_RELEASE_FORM_1000, + FORM_EVENT_RECV_RELEASE_FORM_1100, + FORM_EVENT_RECV_RELEASE_FORM_1200, + FORM_EVENT_RECV_RELEASE_FORM_1300, + FORM_EVENT_RECV_RELEASE_FORM_1400, + FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, + FORM_EVENT_RECV_ONE_NORMAL_FORM, + FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} +/** + * @tc.number: FMS_releaseForm_0100 + * @tc.name: host is not a system app + * @tc.desc: 1.release the form that formID is 1 + * 2.Verify the result is false + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0100, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_releaseForm_0100" << std::endl; + + std::string bundleName = "com.ohos.form.manager.notsystemapp"; + std::string abilityName = "FormAbilityNotSys"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_0100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0100, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0100, EVENT_CODE_100)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0100, EVENT_CODE_100); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0100, result:" << result; + } + + std::cout << "============END FMS_releaseForm_0100" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0200 + * @tc.name: host does not have permission + * @tc.desc: 1.release the form that formID is 1 + * 2.Verify the result is false + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0200, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_releaseForm_0200" << std::endl; + + std::string bundleName = "com.ohos.form.manager.nopermission"; + std::string abilityName = "FormAbilityNoPerm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_0200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0200, EVENT_CODE_200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0200, EVENT_CODE_200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0200, EVENT_CODE_200); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0200, result:" << result; + } + + std::cout << "============END FMS_releaseForm_0200" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0300 + * @tc.name: formID id is error(formID < 0) + * @tc.desc: 1.release the form + * 2.Verify the result is false + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0300, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_releaseForm_0300" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityReleaseForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_0300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0300, EVENT_CODE_300, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0300, EVENT_CODE_300)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0300, EVENT_CODE_300); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0300, result:" << result; + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_releaseForm_0300" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0400 + * @tc.name: formID id is error(formID = 0) + * @tc.desc: 1.release the form + * 2.Verify the result is false + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0400, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_releaseForm_0400" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityReleaseForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_0400; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0400, EVENT_CODE_400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0400, EVENT_CODE_400)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0400, EVENT_CODE_400); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0400, result:" << result; + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_releaseForm_0400" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0500 + * @tc.name: formID id is error because formId is not self + * @tc.desc: 1.host A create a formA + * 2.host B release the formA + * 2.Verify the result is false + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0500, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_releaseForm_0500" << std::endl; + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + + GTEST_LOG_(INFO) << "FMS_releaseForm_0500, data:[" << data << "]" << std::endl; + if (data != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityReleaseForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = data; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0500, EVENT_CODE_500, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0500, EVENT_CODE_500)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0500, EVENT_CODE_500); + bool result = data2 == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0500, result:" << result; + } + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, data); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_releaseForm_0500" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0600 + * @tc.name: Form ID error (FormID does not exist) + * @tc.desc: 1.host create one normal card + * 2.host delete the form + * 3.host release the form and verify the result is false + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0600, Function | MediumTest | Level0) +{ + std::cout << "============START FMS_releaseForm_0600" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityReleaseForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_0600; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0600, EVENT_CODE_600, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0600, EVENT_CODE_600)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0600, EVENT_CODE_600); + bool result = data == "false"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0600, result:" << result; + } + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_releaseForm_0600" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0700 + * @tc.name: form reference is not 0 after release form(isReleaseCache:false) + * @tc.desc: 1.host A create a normal formA + * 2.host B create a form with formA's ID + * 3.release formA(isReleaseCache is false), and verify the result is true + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0700, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_releaseForm_0700" << std::endl; + + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + GTEST_LOG_(INFO) << "FMS_releaseForm_0700, formOne:[" << formOne << "]" << std::endl; + if (formOne != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityReleaseForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = formOne; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0700, EVENT_CODE_700, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0700, EVENT_CODE_700)); + std::string formTwo = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0700, EVENT_CODE_700); + bool result = formTwo == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0700, result:" << result; + } + bool cacheRes = FmsGetCacheInfoByFormId(atoll(formOne.c_str())); + bool hostRes = FmsGetHostInfoByFormId(atoll(formOne.c_str()), "com.ohos.form.manager.normal"); + bool storageRes = FmsGetStorageFormInfos(atoll(formOne.c_str())); + EXPECT_TRUE(cacheRes); + EXPECT_FALSE(hostRes); + EXPECT_TRUE(storageRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101)); + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_releaseForm_0700" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0800 + * @tc.name: After releasing a normal form, the form reference is 0.(isReleaseCache:false) + * there are still created normal forms in FMS. + * @tc.desc: 1.host A an host B create one normal card respectively + * 2.host A release the form and verify the result is true + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0800, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_releaseForm_0800" << std::endl; + + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + GTEST_LOG_(INFO) << "FMS_releaseForm_0800, formOne:[" << formOne << "]" << std::endl; + if (formOne != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityReleaseForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = formOne; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0800, EVENT_CODE_800, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0800, EVENT_CODE_800)); + std::string formTwo = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0800, EVENT_CODE_800); + GTEST_LOG_(INFO) << "FMS_releaseForm_0800, formTwo:[" << formTwo << "]" << std::endl; + bool result = (formTwo != "false" && formTwo != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0800, result:" << result; + } + bool cacheRes = FmsGetCacheInfoByFormId(atoll(formTwo.c_str())); + bool storageRes = FmsGetStorageFormInfos(atoll(formTwo.c_str())); + bool timerRes = FmsGetFormTimerTask(atoll(formTwo.c_str())); + EXPECT_TRUE(cacheRes); + EXPECT_TRUE(storageRes); + EXPECT_FALSE(timerRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, formTwo); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101)); + } + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_releaseForm_0800" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_0900 + * @tc.name: After releasing a normal form, there is no created normal form in FMS.(isReleaseCache:false) + * @tc.desc: 1.host create one normal card + * 2.host release the form and verify the result is true + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0900, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_releaseForm_0900" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityReleaseForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_0900; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_0900, EVENT_CODE_900, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_0900, EVENT_CODE_900)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_0900, EVENT_CODE_900); + GTEST_LOG_(INFO) << "FMS_releaseForm_0900, data:[" << data << "]" << std::endl; + bool result = (data != "false" && data != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_0900, result:" << result; + } + bool cacheRes = FmsGetCacheInfoByFormId(atoll(data.c_str())); + bool hostRes = FmsGetHostInfoByFormId(atoll(data.c_str()), "com.ohos.form.manager.normal"); + bool storageRes = FmsGetStorageFormInfos(atoll(data.c_str())); + EXPECT_TRUE(cacheRes); + EXPECT_FALSE(hostRes); + EXPECT_TRUE(storageRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, data); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101)); + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_releaseForm_0900" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_1100 + * @tc.name: After releasing a normal form, the form reference is 0.(isReleaseCache:true) + * there are still created normal forms in FMS. + * @tc.desc: 1.host A an host B create one normal form respectively + * 2.host A release the form and verify the result is true + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1100, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_releaseForm_1100" << std::endl; + + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + GTEST_LOG_(INFO) << "FMS_releaseForm_1100, formOne:[" << formOne << "]" << std::endl; + if (formOne != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityReleaseForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = formOne; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_1100, EVENT_CODE_1100, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_1100, EVENT_CODE_1100)); + std::string formTwo = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_1100, EVENT_CODE_1100); + GTEST_LOG_(INFO) << "FMS_releaseForm_1100, formTwo:[" << formTwo << "]" << std::endl; + bool result = (formTwo != "false" && formTwo != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_1100, result:" << result; + } + bool cacheRes = FmsGetCacheInfoByFormId(atoll(formTwo.c_str())); + bool storageRes = FmsGetStorageFormInfos(atoll(formTwo.c_str())); + bool timerRes = FmsGetFormTimerTask(atoll(formTwo.c_str())); + EXPECT_FALSE(cacheRes); + EXPECT_TRUE(storageRes); + EXPECT_FALSE(timerRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, formTwo); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101)); + } + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_releaseForm_1100" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_1200 + * @tc.name: After releasing a normal form, there is no created normal form in FMS.(isReleaseCache:true) + * @tc.desc: 1.host create one normal card + * 2.host release the form and verify the result is true + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1200, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_releaseForm_1200" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityReleaseForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_1200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_1200, EVENT_CODE_1200, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_1200, EVENT_CODE_1200)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_1200, EVENT_CODE_1200); + GTEST_LOG_(INFO) << "FMS_releaseForm_1200, data:[" << data << "]" << std::endl; + bool result = (data != "false" && data != ""); + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_1200, result:" << result; + } + bool cacheRes = FmsGetCacheInfoByFormId(atoll(data.c_str())); + bool hostRes = FmsGetHostInfoByFormId(atoll(data.c_str()), "com.ohos.form.manager.normal"); + bool storageRes = FmsGetStorageFormInfos(atoll(data.c_str())); + EXPECT_FALSE(cacheRes); + EXPECT_FALSE(hostRes); + EXPECT_TRUE(storageRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, data); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101)); + SystemTestFormUtil::CleanMsg(event); + std::cout << "============END FMS_releaseForm_1200" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_1300 + * @tc.name: single host continuously release forms + * @tc.desc: 1.There are 2 forms created by the single host + * 2.single host release 2 forms successfully + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1300, Function | MediumTest | Level2) +{ + std::cout << "============START FMS_releaseForm_1300" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityReleaseForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = ""; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_1300, EVENT_CODE_1300, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300); + bool result = data != ""; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_1300, result:" << result; + } + GTEST_LOG_(INFO) << "FMS_releaseForm_1300, data:[" << data << "]" << std::endl; + if (data != "") { + std::string eventData2 = data; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_1300, EVENT_CODE_1300, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300)); + std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_1300, EVENT_CODE_1300); + bool result2 = data2 == "true"; + EXPECT_TRUE(result2); + if (!result2) { + GTEST_LOG_(INFO) << "FMS_releaseForm_1300, result2:" << result2; + } + } + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_releaseForm_1300" << std::endl; +} + +/** + * @tc.number: FMS_releaseForm_1400 + * @tc.name: release temp form + * @tc.desc: 1.host create one temp form + * 2.release the form and judge the result is true + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1400, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_releaseForm_1400" << std::endl; + + std::string bundleName = "com.ohos.form.manager.normal"; + std::string abilityName = "FormAbilityReleaseForm"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = FORM_EVENT_REQ_RELEASE_FORM_1400; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_1400, EVENT_CODE_1400, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_1400, EVENT_CODE_1400)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_1400, EVENT_CODE_1400); + bool result = data == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_1400, result:" << result; + } + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_releaseForm_1400" << std::endl; +} +/** + * @tc.number: FMS_releaseForm_1000 + * @tc.name: form reference is not 0 after release form(isReleaseCache:true) + * @tc.desc: 1.host A create a normal formA + * 2.host B create a form with formA's ID + * 3.release formA(isReleaseCache:true), and verify the result is true + */ +HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1000, Function | MediumTest | Level1) +{ + std::cout << "============START FMS_releaseForm_1000" << std::endl; + + std::string bundleName = "com.ohos.form.manager.commona"; + std::string abilityName = "FormAbilityCommonA"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData = "false"; // normal form + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); + std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); + + GTEST_LOG_(INFO) << "FMS_releaseForm_1000, formOne:[" << formOne << "]" << std::endl; + if (formOne != "") { + std::string bundleName2 = "com.ohos.form.manager.normal"; + std::string abilityName2 = "FormAbilityReleaseForm"; + MAP_STR_STR params2; + Want want2 = SystemTestFormUtil::MakeWant("device", abilityName2, bundleName2, params2); + SystemTestFormUtil::StartAbility(want2, abilityManager); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + std::string eventData2 = formOne; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_1000, EVENT_CODE_1000, eventData2); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_1000, EVENT_CODE_1000)); + std::string formTwo = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_RELEASE_FORM_1000, EVENT_CODE_1000); + bool result = formTwo == "true"; + EXPECT_TRUE(result); + if (!result) { + GTEST_LOG_(INFO) << "FMS_releaseForm_1000, result:" << result; + } + bool cacheRes = FmsGetCacheInfoByFormId(atoll(formOne.c_str())); + bool hostRes = FmsGetHostInfoByFormId(atoll(formOne.c_str()), "com.ohos.form.manager.normal"); + bool storageRes = FmsGetStorageFormInfos(atoll(formOne.c_str())); + EXPECT_TRUE(cacheRes); + EXPECT_FALSE(hostRes); + EXPECT_TRUE(storageRes); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM_DEL, EVENT_CODE_101)); + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101, formOne); + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_RELEASE_FORM_COMMON_DEL, EVENT_CODE_101)); + } + SystemTestFormUtil::CleanMsg(event); + + std::cout << "============END FMS_releaseForm_1000" << std::endl; +} +bool FmsReleaseFormTest::FmsGetCacheInfoByFormId(std::int64_t formId) +{ + std::string cachedData = SystemTestFormUtil::QueryFormInfoByFormId(formId); + bool cacheRes = false; + std::string formIdStr = std::to_string(formId); + std::string::size_type pos = cachedData.find(formIdStr); + if (pos != cachedData.npos) { + std::cout << "######### formId is found in cache" << std::endl; + cacheRes = true; + } else { + std::cout << "######### Can't find formId in cache!" << std::endl; + cacheRes = false; + } + return cacheRes; +} +bool FmsReleaseFormTest::FmsGetHostInfoByFormId(std::int64_t formId, std::string hostBundleName) +{ + std::string hostData = SystemTestFormUtil::QueryFormInfoByFormId(formId); + bool hostRes = false; + std::string::size_type pos = hostData.find(hostBundleName); + if (pos != hostData.npos) { + std::cout << "######### hostBundleName is found in cache" << std::endl; + hostRes = true; + } else { + std::cout << "######### Can't find hostBundleName in cache!" << std::endl; + hostRes = false; + } + return hostRes; +} +bool FmsReleaseFormTest::FmsGetStorageFormInfos(std::int64_t formId) +{ + std::string storageData = SystemTestFormUtil::QueryStorageFormInfos(); + bool storageRes = false; + std::string formIdStr = std::to_string(formId); + std::string::size_type pos = storageData.find(formIdStr); + if (pos != storageData.npos) { + std::cout << "######### formId is found in storage" << std::endl; + storageRes = true; + } else { + std::cout << "######### Can't find formId in storage!" << std::endl; + storageRes = false; + } + return storageRes; +} +bool FmsReleaseFormTest::FmsGetFormTimerTask(std::int64_t formId) +{ + std::string timerRes = SystemTestFormUtil::QueryFormTimerByFormId(formId); + if (timerRes == "true") { + std::cout << "######### formId is found in TimerTask" << std::endl; + return true; + } else { + std::cout << "######### Can't find formId in TimerTask!" << std::endl; + return false; + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_self_starting_test/BUILD.gn b/test/systemtest/common/fms/fms_self_starting_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..11d47f57178bf93bdd1e5ea7cd00db66a2c85ee8 --- /dev/null +++ b/test/systemtest/common/fms/fms_self_starting_test/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("FmsSelfStartingTest") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "${appexecfwk_path}/services/formmgr/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + ] + + sources = [ + "${appexecfwk_path}/services/formmgr/include/form_db_info.h", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "fms_self_starting_test.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${aafwk_path}/services/formmgr:libfms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"FmsSelfStartingTest\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":FmsSelfStartingTest" ] +} diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0100.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0100.sh new file mode 100644 index 0000000000000000000000000000000000000000..f3b009ef7e5d3269a4b8a1b1b5b18f65de600e74 --- /dev/null +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0100.sh @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. + +ps -e|grep FormMgrService + +if [ $? -eq 0 ]; then + echo "FMS restart succeed" +else + echo "FMS restart failed" +fi + diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0200.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0200.sh new file mode 100644 index 0000000000000000000000000000000000000000..83305444874c66ddea3ca04e53fd616336b2aa59 --- /dev/null +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0200.sh @@ -0,0 +1,36 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. + +sleepSeconds=10 +loop=1 + +echo "loop times: ${loop}" +for i in $(seq 1 ${loop}) +do + echo "==========loop: ${i} start==========" + echo "kill foundation" + pgrep foundation | xargs kill -9 + + echo "sleep ${sleepSeconds} seconds" + sleep ${sleepSeconds} + ps -e|grep FormMgrService + + if [ $? -eq 0 ]; then + echo "loop ${i}: FMS restart succeed" + else + echo "loop ${i}: FMS restart failed" + exit + fi +done + +exit \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0300.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0300.sh new file mode 100644 index 0000000000000000000000000000000000000000..2523335aa34819bb17c6bb247e2286a8761fb438 --- /dev/null +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0300.sh @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. +testfile="/data/formmgr/fms_self_starting_test_config.json" +sleepSeconds=10 + +rm -rf /data/formmgr +mkdir /data/formmgr + +chown system /data/formmgr +chgrp system /data/formmgr + +touch ${testfile} +echo \{\"AddForm\":true,\"DeleteForm\":false,\"Compare\":false\} > ${testfile}; +chown system ${testfile} +chgrp system ${testfile} + +sleep 2 +echo "acquire forms" +./FmsSelfStartingTest + +sleep 2 +echo "kill foundation" +pgrep foundation | xargs kill -9 + +echo "sleep ${sleepSeconds} seconds" +sleep ${sleepSeconds} + +sleep 2 +beforeKill=`pgrep foundation` +echo ${beforeKill} > "/data/formmgr/beforeKill.txt" +echo "kill foundation" +pgrep foundation | xargs kill -9 + +echo "sleep ${sleepSeconds} seconds" +sleep ${sleepSeconds} + +afterKill=`pgrep foundation` +echo ${afterKill} > "/data/formmgr/afterKill.txt" +if [ "${beforeKill}" == "${afterKill}" ]; then + echo "process has not changed" +else + echo "process has changed" +fi + +rm -f ${testfile} +touch ${testfile} +echo \{\"AddForm\":false,\"DeleteForm\":false,\"Compare\":true\} > ${testfile}; +chown system ${testfile} +chgrp system ${testfile} +sleep 12 +echo "compare forms" +./FmsSelfStartingTest + +rm -f ${testfile} +touch ${testfile} +echo \{\"AddForm\":false,\"DeleteForm\":true,\"Compare\":false\} > ${testfile}; +chown system ${testfile} +chgrp system ${testfile} +sleep 2 +echo "delete forms" +./FmsSelfStartingTest + +rm -rf /data/formmgr + +exit diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0400.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0400.sh new file mode 100644 index 0000000000000000000000000000000000000000..205a4a4795cc1772e64ee8b0fdce24be88a3c119 --- /dev/null +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0400.sh @@ -0,0 +1,36 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. + +sleepSeconds=10 +loop=4 + +echo "loop times: ${loop}" +for i in $(seq 1 ${loop}) +do + echo "==========loop: ${i} start==========" + echo "kill foundation" + pgrep foundation | xargs kill -9 + + echo "sleep ${sleepSeconds} seconds" + sleep ${sleepSeconds} + ps -e|grep FormMgrService + + if [ $? -eq 0 ]; then + echo "loop ${i}: FMS restart succeed" + else + echo "loop ${i}: FMS restart failed" + exit + fi +done + +exit \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp b/test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c19a1b705b0477961438387feb4897a550c48f5 --- /dev/null +++ b/test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "distributed_kv_data_manager.h" +#include "form_db_info.h" +#include "form_data_mgr.h" +#include "form_item_info.h" +#include "form_storage_mgr.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "self_starting_test_config_parser.h" +#include "system_ability_definition.h" +#include "system_test_form_util.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace OHOS { +namespace AppExecFwk { +static SelfStartingTestInfo selfStarting; +static SelfStartingTestConfigParser selfStartingParser; +const int ADD_FORM_A_NUMBER = 10; +const int ADD_FORM_LENGTH = 20; +class FmsSelfStartingTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + static bool SubscribeEvent(); + + bool CompareA(); + bool CompareB(); + + void SetUp(); + void TearDown(); + + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + void ClearStorage(); + bool CheckKvStore(); + void TryTwice(const std::function &func); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityMs; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber_; +}; + +std::vector FmsSelfStartingTest::eventList = { + FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_SELF_STARTING_TEST_0100, FORM_EVENT_RECV_SELF_STARTING_TEST_0200, + FORM_EVENT_RECV_SELF_STARTING_TEST_0300 +}; + +FormEvent FmsSelfStartingTest::event = FormEvent(); +sptr FmsSelfStartingTest::abilityMs = nullptr; +std::shared_ptr FmsSelfStartingTest::subscriber_ = nullptr; +void FmsSelfStartingTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void FmsSelfStartingTest::SetUpTestCase() +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + SelfStartingTestConfigParser selfStartingTcp; + selfStartingTcp.ParseForSelfStartingTest(FMS_TEST_CONFIG_FILE_PATH, selfStarting); + std::cout << "self starting test status : " + << "addFormStatus : " << selfStarting.addFormStatus << + ", deleteFormStatus:" << selfStarting.deleteFormStatus << + ", compareStatus:" << selfStarting.compareStatus << std::endl; + + if (selfStarting.addFormStatus) { + selfStartingParser.ClearStorage(); + for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) { + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, iCount + 1); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, iCount + 1); + // Set Want info end + int errorCode = STtools::SystemTestFormUtil::DistributedDataAddForm(want); + if (errorCode != 0) { + GTEST_LOG_(INFO) << "add form failed, iCount:" << iCount << ", errorCode:" << errorCode; + } + sleep(1); + } + } + + if (selfStarting.addFormStatus) { + for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) { + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME2); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME2); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE); + want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME2, FORM_PROVIDER_ABILITY_NAME2); + APP_LOGI("%{public}s, formCount: %{public}d", __func__, iCount + 1); + want.SetParam(Constants::PARAM_FORM_ADD_COUNT, iCount + 1); + // Set Want info end + int errorCode = STtools::SystemTestFormUtil::DistributedDataAddForm(want); + if (errorCode != 0) { + GTEST_LOG_(INFO) << "add form failed, iCount:" << iCount << ", errorCode:" << errorCode; + } + sleep(1); + } + } +} + +bool FmsSelfStartingTest::CompareA() +{ + bool compare = true; + for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) { + int64_t formId = iCount + 1; + InnerFormInfo innerFormInfo; + selfStartingParser.GetStorageFormInfoById(std::to_string(formId), innerFormInfo); + if (innerFormInfo.GetFormId() != formId) { + compare = false; + break; + } + if (innerFormInfo.GetModuleName() != PARAM_PROVIDER_MODULE_NAME1) { + compare = false; + break; + } + if (innerFormInfo.GetBundleName() != FORM_PROVIDER_BUNDLE_NAME1) { + compare = false; + break; + } + if (innerFormInfo.GetAbilityName() != FORM_PROVIDER_ABILITY_NAME1) { + compare = false; + break; + } + if (innerFormInfo.GetFormName() != PARAM_FORM_NAME1) { + compare = false; + break; + } + } + return compare; +} + +bool FmsSelfStartingTest::CompareB() +{ + bool compare = true; + for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) { + int64_t formId = iCount + 1; + InnerFormInfo innerFormInfo; + selfStartingParser.GetStorageFormInfoById(std::to_string(formId), innerFormInfo); + if (innerFormInfo.GetFormId() != formId) { + compare = false; + break; + } + if (innerFormInfo.GetModuleName() != PARAM_PROVIDER_MODULE_NAME2) { + compare = false; + break; + } + if (innerFormInfo.GetBundleName() != FORM_PROVIDER_BUNDLE_NAME2) { + compare = false; + break; + } + if (innerFormInfo.GetAbilityName() != FORM_PROVIDER_ABILITY_NAME2) { + compare = false; + break; + } + if (innerFormInfo.GetFormName() != PARAM_FORM_NAME2) { + compare = false; + break; + } + } + return compare; +} + +void FmsSelfStartingTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + if (selfStarting.deleteFormStatus) { + for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) { + int64_t formId = iCount + 1; + int errorCode = STtools::SystemTestFormUtil::DistributedDataDeleteForm(std::to_string(formId)); + if (errorCode != 0) { + GTEST_LOG_(INFO) << "delete form failed, iCount:" << iCount << ", errorCode:" << errorCode; + } + } + } + + if (selfStarting.deleteFormStatus) { + for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) { + int64_t formId = iCount + 1; + int errorCode = STtools::SystemTestFormUtil::DistributedDataDeleteForm(std::to_string(formId)); + if (errorCode != 0) { + GTEST_LOG_(INFO) << "delete form failed, iCount:" << ", errorCode:" << errorCode; + } + } + selfStartingParser.ClearStorage(); + } +} + +void FmsSelfStartingTest::SetUp() +{ +} + +void FmsSelfStartingTest::TearDown() +{ + GTEST_LOG_(INFO) << "CleanMsg calld"; + SystemTestFormUtil::CleanMsg(event); +} +bool FmsSelfStartingTest::SubscribeEvent() +{ + GTEST_LOG_(INFO) << "SubscribeEvent calld"; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +/** + * @tc.number: FMS_Start_0300_03 + * @tc.name: Form number 512 + * @tc.desc: + */ +HWTEST_F(FmsSelfStartingTest, FMS_Start_0300_03, Function | MediumTest | Level1) +{ + std::cout << "START FMS_Start_0300_03" << std::endl; + + if (selfStarting.compareStatus) { + std::ifstream opbefore("/data/formmgr/beforeKill.txt"); + std::ifstream opafter("/data/formmgr/afterKill.txt"); + std::string beforeKill; + std::string afterKill; + while (!opbefore.eof()) { + beforeKill += opbefore.get(); + } + while (!opafter.eof()) { + afterKill += opafter.get(); + } + opbefore.close(); + opafter.close(); + EXPECT_TRUE(beforeKill != afterKill); + + EXPECT_TRUE(CompareA()); + + EXPECT_TRUE(CompareB()); + } + std::cout << "END FMS_Start_0300_03" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/systemtest/common/fms/fms_self_starting_test/self_starting_test_config_parser.h b/test/systemtest/common/fms/fms_self_starting_test/self_starting_test_config_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..b02ca7be21fc092f2311c3dfc860aee13148ce97 --- /dev/null +++ b/test/systemtest/common/fms/fms_self_starting_test/self_starting_test_config_parser.h @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 STRESS_TEST_CONFIG_PARSER_H +#define STRESS_TEST_CONFIG_PARSER_H + +#include +#include +#include + +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace AppExecFwk { +const std::string FMS_TEST_CONFIG_FILE_PATH {"/data/formmgr/fms_self_starting_test_config.json"}; +const std::string STRESS_TEST_EXECUTION_TIMES_KEY {"AddForm"}; +const std::string STRESS_TEST_SLEEP_TIME_KEY {"DeleteForm"}; +const std::string STRESS_TEST_COMPARE_TIME_KEY {"Compare"}; + +struct SelfStartingTestInfo { + bool addFormStatus {true}; + bool deleteFormStatus {false}; + bool compareStatus {false}; +}; + +class SelfStartingTestConfigParser { +public: + void ParseForSelfStartingTest(const std::string &path, SelfStartingTestInfo &selfStarting) + { + std::ifstream jf(path); + if (!jf.is_open()) { + std::cout << "json file can not open!" << std::endl; + return; + } + nlohmann::json jsonObj; + jf >> jsonObj; + const auto &jsonObjEnd = jsonObj.end(); + if (jsonObj.find(STRESS_TEST_EXECUTION_TIMES_KEY) != jsonObjEnd) { + jsonObj.at(STRESS_TEST_EXECUTION_TIMES_KEY).get_to(selfStarting.addFormStatus); + } + + if (jsonObj.find(STRESS_TEST_SLEEP_TIME_KEY) != jsonObjEnd) { + jsonObj.at(STRESS_TEST_SLEEP_TIME_KEY).get_to(selfStarting.deleteFormStatus); + } + + if (jsonObj.find(STRESS_TEST_COMPARE_TIME_KEY) != jsonObjEnd) { + jsonObj.at(STRESS_TEST_COMPARE_TIME_KEY).get_to(selfStarting.compareStatus); + } + } + + void ClearStorage() + { + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + GTEST_LOG_(INFO) << "kvStore is nullptr"; + return; + } + } + DistributedKv::Status status; + std::vector allEntries; + TryTwice([this, &status, &allEntries] { + status = GetEntries(allEntries); + return status; + }); + + if (status != DistributedKv::Status::SUCCESS) { + GTEST_LOG_(INFO) << "get entries error"; + } else { + for (const auto &item : allEntries) { + std::lock_guard lock(kvStorePtrMutex_); + kvStorePtr_->Delete(item.key); + } + } + } + + bool CheckKvStore() + { + if (kvStorePtr_ != nullptr) { + return true; + } + int32_t tryTimes = MAX_TIMES; + while (tryTimes > 0) { + DistributedKv::Status status = GetKvStore(); + if (status == DistributedKv::Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + usleep(SLEEP_INTERVAL); + tryTimes--; + } + return kvStorePtr_ != nullptr; + } + + void TryTwice(const std::function &func) + { + DistributedKv::Status status = func(); + if (status == DistributedKv::Status::IPC_ERROR) { + status = func(); + } + } + + DistributedKv::Status GetEntries(std::vector &allEntries) + { + DistributedKv::Status status = DistributedKv::Status::ERROR; + // if prefix is empty, get all entries. + DistributedKv::Key key(""); + if (kvStorePtr_) { + // sync call GetEntries, the callback will be trigger at once + status = kvStorePtr_->GetEntries(key, allEntries); + } + return status; + } + + DistributedKv::Status GetKvStore() + { + DistributedKv::Status status; + DistributedKv::Options options = { + .createIfMissing = true, + .encrypt = false, + .autoSync = true, + .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION + }; + + dataManager_.GetSingleKvStore( + options, appId_, storeId_, [this, &status](DistributedKv::Status paramStatus, + std::unique_ptr singleKvStore) { + status = paramStatus; + if (status != DistributedKv::Status::SUCCESS) { + return; + } + { + kvStorePtr_ = std::move(singleKvStore); + } + GTEST_LOG_(INFO) << "get kvStore success"; + }); + + return status; + } + + bool GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) + { + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + GTEST_LOG_(INFO) << "kvStore is nullptr"; + return false; + } + } + bool ret = true; + APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + + DistributedKv::Status status = DistributedKv::Status::ERROR; + std::vector allEntries; + DistributedKv::Key key(formId); + if (kvStorePtr_) { + // sync call GetEntries, the callback will be trigger at once + status = kvStorePtr_->GetEntries(key, allEntries); + } + + if (status != DistributedKv::Status::SUCCESS) { + APP_LOGE("get entries error: %{public}d", status); + ret = false; + } else { + if (allEntries.empty()) { + APP_LOGE("%{public}s not match any FormInfo", formId.c_str()); + ret = false; + } else { + nlohmann::json jsonObject = nlohmann::json::parse(allEntries.front().value.ToString(), nullptr, false); + if (jsonObject.is_discarded()) { + APP_LOGE("error key: %{private}s", allEntries.front().key.ToString().c_str()); + ret = false; + } + if (innerFormInfo.FromJson(jsonObject) != true) { + APP_LOGE("error key: %{private}s", allEntries.front().key.ToString().c_str()); + ret = false; + } + } + } + + return ret; + } + + const DistributedKv::AppId appId_ {"form_storage"}; + const DistributedKv::StoreId storeId_ {"installed_form_datas"}; + DistributedKv::DistributedKvDataManager dataManager_; + std::unique_ptr kvStorePtr_; + mutable std::mutex kvStorePtrMutex_; + const int32_t MAX_TIMES = 600; // 1min + const int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // STRESS_TEST_CONFIG_PARSER_H diff --git a/test/systemtest/common/fms/fms_stress_test/BUILD.gn b/test/systemtest/common/fms/fms_stress_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..914278dbcc01cff510707a027d8ee806717d15b3 --- /dev/null +++ b/test/systemtest/common/fms/fms_stress_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmanagerst" + +ohos_systemtest("FmsStressTest") { + module_out_path = module_output_path + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/test/systemtest/common/fms/common/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "${appexecfwk_path}/test/systemtest/common/fms/common/src/form_event.cpp", + "${appexecfwk_path}/test/systemtest/common/fms/common/src/system_test_form_util.cpp", + "fms_stress_test.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + ] + + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gtest_main", + ] + + defines = [ "APP_LOG_TAG = \"FmsStressTest\"" ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "form_runtime:form_manager", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimodalinput_base:libmmi-client", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":FmsStressTest" ] +} diff --git a/test/systemtest/common/fms/fms_stress_test/fms_stress_test.cpp b/test/systemtest/common/fms/fms_stress_test/fms_stress_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..b70576e9a6809c940c99f73c48c443308db977e5 --- /dev/null +++ b/test/systemtest/common/fms/fms_stress_test/fms_stress_test.cpp @@ -0,0 +1,614 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "ability_info.h" +#include "ability_handler.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "context_deal.h" +#include "form_event.h" +#include "form_st_common_info.h" +#include "system_test_form_util.h" +#include "iservice_registry.h" +#include "nlohmann/json.hpp" +#include "stress_test_config_parser.h" +#include "system_ability_definition.h" + +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::STtools; + +namespace OHOS { +namespace AppExecFwk { +static StressTestLevel stLevel_; +static int g_iSuccessfulTimes = 0; +class FmsStressTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + static bool SubscribeEvent(); + + void SetUp(); + void TearDown(); + void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); + void TerminateAbility(const std::string &eventName, const std::string &abilityName); + + // Test case + static void StressTest_0100(); + static void StressTest_0200(); + static void StressTest_0300(); + static void StressTest_1100(); + static void StressTest_1300(); + static void StressTest_1700(); + static void StressTest_1800(); + + class FormEventSubscriber : public CommonEventSubscriber { + public: + explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~FormEventSubscriber() = default; + }; + + static sptr abilityMs; + static FormEvent event; + static std::vector eventList; + static std::shared_ptr subscriber_; +}; + +std::vector FmsStressTest::eventList = { + FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_STRESS_TEST_0100, + FORM_EVENT_RECV_STRESS_TEST_0100_01, FORM_EVENT_RECV_STRESS_TEST_0200, + FORM_EVENT_RECV_STRESS_TEST_0200_01, FORM_EVENT_RECV_STRESS_TEST_0200_02, FORM_EVENT_RECV_STRESS_TEST_0200_03, + FORM_EVENT_RECV_STRESS_TEST_0300, FORM_EVENT_RECV_STRESS_TEST_0300_01, FORM_EVENT_RECV_STRESS_TEST_0300_02, + FORM_EVENT_RECV_STRESS_TEST_0400, FORM_EVENT_RECV_STRESS_TEST_0500, + FORM_EVENT_RECV_STRESS_TEST_1100, FORM_EVENT_RECV_STRESS_TEST_1100_01, FORM_EVENT_RECV_STRESS_TEST_1100_02, + FORM_EVENT_RECV_STRESS_TEST_1100_03, FORM_EVENT_RECV_STRESS_TEST_1300, FORM_EVENT_RECV_STRESS_TEST_1300_01, + FORM_EVENT_RECV_STRESS_TEST_1300_02, FORM_EVENT_RECV_STRESS_TEST_1300_03, + FORM_EVENT_RECV_STRESS_TEST_1700, FORM_EVENT_RECV_STRESS_TEST_1700_01, FORM_EVENT_RECV_STRESS_TEST_1700_02, + FORM_EVENT_RECV_STRESS_TEST_1800, +}; + +FormEvent FmsStressTest::event = FormEvent(); +sptr FmsStressTest::abilityMs = nullptr; +std::shared_ptr FmsStressTest::subscriber_ = nullptr; +void FmsStressTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +void FmsStressTest::SetUpTestCase() +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + + StressTestConfigParser stcp; + stcp.ParseForStressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "executionTimes : " << stLevel_.executionTimesLevel << ", time:" << stLevel_.sleepTime << std::endl; +} + +void FmsStressTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + std::cout << "========stress test level : " + << "case execution Times : " << stLevel_.executionTimesLevel << ", time:" << stLevel_.sleepTime << std::endl; +} + +void FmsStressTest::SetUp() +{ + g_iSuccessfulTimes = 0; +} + +void FmsStressTest::TearDown() +{ + std::cout << "========Stress test: " + << "Current case Successful Times : " << g_iSuccessfulTimes++ << "=========" << std::endl; + GTEST_LOG_(INFO) << "CleanMsg calld"; + SystemTestFormUtil::CleanMsg(event); +} +bool FmsStressTest::SubscribeEvent() +{ + GTEST_LOG_(INFO) << "SubscribeEvent calld"; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FmsStressTest::StressTest_0100() +{ + std::string bundleName = "com.ohos.form.manager.stress"; + std::string abilityName = "FormAbilityStress"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // AcquireForm + std::string eventData = FORM_EVENT_REQ_STRESS_TEST_0100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_0100, EVENT_CODE_100, eventData); + + // OnAcquired + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0100, EVENT_CODE_101)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0100, EVENT_CODE_101); + std::string formId = data; + + // OnUpdate + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0100, EVENT_CODE_102)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0100, EVENT_CODE_102); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_0100 AcquireForm, result:" << result; + } + + // DeleteForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0100_01, EVENT_CODE_103)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0100_01, EVENT_CODE_103); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + g_iSuccessfulTimes++; + GTEST_LOG_(INFO) << "FMS_stressTest_0100 DeleteForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsStressTest::StressTest_0200() +{ + std::string bundleName = "com.ohos.form.manager.stress"; + std::string abilityName = "FormAbilityStress"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // AcquireForm + std::string eventData = FORM_EVENT_REQ_STRESS_TEST_0200; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_0200, EVENT_CODE_200, eventData); + + // OnAcquired + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0200, EVENT_CODE_201)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0200, EVENT_CODE_201); + std::string formId = data; + GTEST_LOG_(INFO) << "FMS_stressTest_0200 AcquireForm, formId:" << formId; + + // OnUpdate + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0200, EVENT_CODE_202)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0200, EVENT_CODE_202); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_0200 AcquireForm 001, result:" << result; + } + + // ReleaseForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0200_01, EVENT_CODE_203)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0200_01, EVENT_CODE_203); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_0200 ReleaseForm, result:" << result; + } + + // OnAcquired + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0200_02, EVENT_CODE_204)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0200_02, EVENT_CODE_204); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_0200 AcquireForm 002, result:" << result; + } + + // DeleteForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0200_03, EVENT_CODE_205)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0200_03, EVENT_CODE_205); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + g_iSuccessfulTimes++; + GTEST_LOG_(INFO) << "FMS_stressTest_0200 DeleteForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsStressTest::StressTest_0300() +{ + std::string bundleName = "com.ohos.form.manager.stress"; + std::string abilityName = "FormAbilityStress"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // AcquireForm + std::string eventData = FORM_EVENT_REQ_STRESS_TEST_0300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_0300, EVENT_CODE_300, eventData); + + // OnAcquired + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0300, EVENT_CODE_301)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0300, EVENT_CODE_301); + std::string formId = data; + + // OnUpdate + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0300, EVENT_CODE_302)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0300, EVENT_CODE_302); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_0300 AcquireForm, result:" << result; + } + + // CastTempForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0300_01, EVENT_CODE_303)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0300_01, EVENT_CODE_303); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_0300 CastTempForm, result:" << result; + } + + // DeleteForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_0300_02, EVENT_CODE_304)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_0300_02, EVENT_CODE_304); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + g_iSuccessfulTimes++; + GTEST_LOG_(INFO) << "FMS_stressTest_0300 DeleteForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsStressTest::StressTest_1100() +{ + std::string bundleName = "com.ohos.form.manager.stress"; + std::string abilityName = "FormAbilityStress"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // AcquireForm + std::string eventData = FORM_EVENT_REQ_STRESS_TEST_1100; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_1100, EVENT_CODE_1100, eventData); + + // OnAcquired + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1100, EVENT_CODE_1101)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1100, EVENT_CODE_1101); + std::string formId = data; + + // OnUpdate + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1100, EVENT_CODE_1102)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1100, EVENT_CODE_1102); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1100 AcquireForm, result:" << result; + } + + // NotifyInvisibleForms Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1100_01, EVENT_CODE_1103)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1100_01, EVENT_CODE_1103); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1100 NotifyInvisibleForms, result:" << result; + } + + // NotifyVisibleForms Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1100_02, EVENT_CODE_1104)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1100_02, EVENT_CODE_1104); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1100 notifyVisibleForms, result:" << result; + } + + // DeleteForm + eventData = formId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_1100_03, EVENT_CODE_1105, eventData); + + // DeleteForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1100_03, EVENT_CODE_1105)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1100_03, EVENT_CODE_1105); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + g_iSuccessfulTimes++; + GTEST_LOG_(INFO) << "FMS_stressTest_1100 DeleteForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsStressTest::StressTest_1300() +{ + std::string bundleName = "com.ohos.form.manager.stress"; + std::string abilityName = "FormAbilityStress"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // AcquireForm + std::string eventData = FORM_EVENT_REQ_STRESS_TEST_1300; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_1300, EVENT_CODE_1300, eventData); + + // OnAcquired + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1300, EVENT_CODE_1301)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1300, EVENT_CODE_1301); + std::string formId = data; + + // OnUpdate + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1300, EVENT_CODE_1302)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1300, EVENT_CODE_1302); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1300 AcquireForm, result:" << result; + } + + // EnableUpdateForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1300_01, EVENT_CODE_1303)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1300_01, EVENT_CODE_1303); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1300 EnableUpdateForm, result:" << result; + } + + // DisableUpdateForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1300_02, EVENT_CODE_1304)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1300_02, EVENT_CODE_1304); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1300 DisableUpdateForm, result:" << result; + } + + // DeleteForm + eventData = formId; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_1300_03, EVENT_CODE_1305, eventData); + + // DeleteForm Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1300_03, EVENT_CODE_1305)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1300_03, EVENT_CODE_1305); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + g_iSuccessfulTimes++; + GTEST_LOG_(INFO) << "FMS_stressTest_1300 DeleteForm, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsStressTest::StressTest_1700() +{ + std::string bundleName = "com.ohos.form.manager.stress"; + std::string abilityName = "FormAbilityStress"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // GetAllFormsInfo + std::string eventData = FORM_EVENT_REQ_STRESS_TEST_1700; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_1700, EVENT_CODE_1700, eventData); + + // GetAllFormsInfo Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1700, EVENT_CODE_1700)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1700, EVENT_CODE_1700); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1700 GetAllFormsInfo, result:" << result; + } + + // GetFormsInfoByApp Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1700_01, EVENT_CODE_1701)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1700_01, EVENT_CODE_1701); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + GTEST_LOG_(INFO) << "FMS_stressTest_1700 GetFormsInfoByApp, result:" << result; + } + + // GetFormsInfoByModule Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1700_02, EVENT_CODE_1702)); + data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1700_02, EVENT_CODE_1702); + result = data == "true"; + EXPECT_TRUE(result); + if (result) { + g_iSuccessfulTimes++; + GTEST_LOG_(INFO) << "FMS_stressTest_1700 GetFormsInfoByModule, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +void FmsStressTest::StressTest_1800() +{ + std::string bundleName = "com.ohos.form.manager.stress"; + std::string abilityName = "FormAbilityStress"; + MAP_STR_STR params; + Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); + SystemTestFormUtil::StartAbility(want, abilityMs); + EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); + + // CheckFMSReady + std::string eventData = FORM_EVENT_REQ_STRESS_TEST_1800; + SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_STRESS_TEST_1800, EVENT_CODE_1800, eventData); + + // CheckFMSReady Result + EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_STRESS_TEST_1800, EVENT_CODE_1800)); + std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_STRESS_TEST_1800, EVENT_CODE_1800); + bool result = data == "true"; + EXPECT_TRUE(result); + if (result) { + g_iSuccessfulTimes++; + GTEST_LOG_(INFO) << "FMS_stressTest_1800 CheckFMSReady, result:" << result; + } + + SystemTestFormUtil::CleanMsg(event); +} + +/** + * @tc.number : FMS_stressTest_0100 + * @tc.name : AcquireForm/DeleteForm stress test + * @tc.desc : AcquireForm successfully/DeleteForm successfully + */ +HWTEST_F(FmsStressTest, FMS_stressTest_0100, Function | MediumTest | Level2) +{ + std::cout << "START FMS_stressTest_0100" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < stLevel_.executionTimesLevel; iExecutionTimes++) { + sleep(stLevel_.sleepTime); + FmsStressTest::StressTest_0100(); + std::cout << "FMS_stressTest_0100 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_stressTest_0100" << std::endl; +} + +/** + * @tc.number : FMS_stressTest_0200 + * @tc.name : AcquireForm、ReleaseForm/DeleteForm stress test + * @tc.desc : AcquireForm successfully/ReleaseForm successfully/DeleteForm successfully + */ +HWTEST_F(FmsStressTest, FMS_stressTest_0200, Function | MediumTest | Level2) +{ + std::cout << "START FMS_stressTest_0200" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < stLevel_.executionTimesLevel; iExecutionTimes++) { + sleep(stLevel_.sleepTime); + FmsStressTest::StressTest_0200(); + std::cout << "FMS_stressTest_0200 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_stressTest_0200" << std::endl; +} + +/** + * @tc.number : FMS_stressTest_0300 + * @tc.name : AcquireForm/CastTempForm/DeleteForm stress test + * @tc.desc : AcquireForm successfully/CastTempForm successfully/DeleteForm successfully + */ +HWTEST_F(FmsStressTest, FMS_stressTest_0300, Function | MediumTest | Level2) +{ + std::cout << "START FMS_stressTest_0300" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < stLevel_.executionTimesLevel; iExecutionTimes++) { + sleep(stLevel_.sleepTime); + FmsStressTest::StressTest_0300(); + std::cout << "FMS_stressTest_0300 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_stressTest_0300" << std::endl; +} + +/** + * @tc.number : FMS_stressTest_1100 + * @tc.name : NotifyInvisibleForms/NotifyVisibleForms stress test + * @tc.desc : NotifyInvisibleForms successfully/NotifyVisibleForms successfully + */ +HWTEST_F(FmsStressTest, FMS_stressTest_1100, Function | MediumTest | Level2) +{ + std::cout << "START FMS_stressTest_1100" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < stLevel_.executionTimesLevel; iExecutionTimes++) { + sleep(stLevel_.sleepTime); + FmsStressTest::StressTest_1100(); + std::cout << "FMS_stressTest_1100 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_stressTest_1100" << std::endl; +} + +/** + * @tc.number : FMS_stressTest_1300 + * @tc.name : EnableUpdateForm/DisableUpdateForm stress test + * @tc.desc : EnableUpdateForm successfully/DisableUpdateForm successfully + */ +HWTEST_F(FmsStressTest, FMS_stressTest_1300, Function | MediumTest | Level2) +{ + std::cout << "START FMS_stressTest_1300" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < stLevel_.executionTimesLevel; iExecutionTimes++) { + sleep(stLevel_.sleepTime); + FmsStressTest::StressTest_1300(); + std::cout << "FMS_stressTest_1300 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_stressTest_1300" << std::endl; +} + +/** + * @tc.number : FMS_stressTest_1700 + * @tc.name : GetAllFormsInfo/GetFormsInfoByApp/GetFormsInfoByModule stress test + * @tc.desc : GetAllFormsInfo successfully/GetFormsInfoByApp successfully/GetFormsInfoByModule successfully + */ +HWTEST_F(FmsStressTest, FMS_stressTest_1700, Function | MediumTest | Level2) +{ + std::cout << "START FMS_stressTest_1700" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < stLevel_.executionTimesLevel; iExecutionTimes++) { + FmsStressTest::StressTest_1700(); + std::cout << "FMS_stressTest_1700 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_stressTest_1700" << std::endl; +} + +/** + * @tc.number : FMS_stressTest_1800 + * @tc.name : CheckFMSReady stress test + * @tc.desc : CheckFMSReady successfully + */ +HWTEST_F(FmsStressTest, FMS_stressTest_1800, Function | MediumTest | Level2) +{ + std::cout << "START FMS_stressTest_1800" << std::endl; + + for (int iExecutionTimes = 0; iExecutionTimes < stLevel_.executionTimesLevel; iExecutionTimes++) { + FmsStressTest::StressTest_1800(); + std::cout << "FMS_stressTest_1800 ExecutionTimes:" << iExecutionTimes + 1 << std::endl; + } + + std::cout << "END FMS_stressTest_1800" << std::endl; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_stress_test/fms_stress_test_config/fms_stress_test_config.json b/test/systemtest/common/fms/fms_stress_test/fms_stress_test_config/fms_stress_test_config.json new file mode 100755 index 0000000000000000000000000000000000000000..c52dcc61af607df4c8b17c7fc84dafb5caecd667 --- /dev/null +++ b/test/systemtest/common/fms/fms_stress_test/fms_stress_test_config/fms_stress_test_config.json @@ -0,0 +1,4 @@ +{ + "ExecutionTimes": 5, + "SleepTime": 3 +} diff --git a/test/systemtest/common/fms/fms_stress_test/stress_test_config_parser.h b/test/systemtest/common/fms/fms_stress_test/stress_test_config_parser.h new file mode 100755 index 0000000000000000000000000000000000000000..5f73309d8ee403fcd298a4a402e1cd3de41323ce --- /dev/null +++ b/test/systemtest/common/fms/fms_stress_test/stress_test_config_parser.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 STRESS_TEST_CONFIG_PARSER_H +#define STRESS_TEST_CONFIG_PARSER_H + +#include +#include +#include + +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace AppExecFwk { +const std::string STRESS_TEST_CONFIG_FILE_PATH {"./fms_stress_test_config.json"}; + +const std::string STRESS_TEST_EXECUTION_TIMES_KEY {"ExecutionTimes"}; +const std::string STRESS_TEST_SLEEP_TIME_KEY {"SleepTime"}; + +struct StressTestLevel { + int32_t executionTimesLevel {1}; + int32_t sleepTime {3}; +}; + +class StressTestConfigParser { +public: + void ParseForStressTest(const std::string &path, StressTestLevel &stlevel) + { + std::ifstream jf(path); + if (!jf.is_open()) { + std::cout << "json file can not open!" << std::endl; + return; + } + nlohmann::json jsonObj; + jf >> jsonObj; + const auto &jsonObjEnd = jsonObj.end(); + if (jsonObj.find(STRESS_TEST_EXECUTION_TIMES_KEY) != jsonObjEnd) { + jsonObj.at(STRESS_TEST_EXECUTION_TIMES_KEY).get_to(stlevel.executionTimesLevel); + if (stlevel.executionTimesLevel == 0) { + stlevel.executionTimesLevel = 1; + } + } + + if (jsonObj.find(STRESS_TEST_SLEEP_TIME_KEY) != jsonObjEnd) { + jsonObj.at(STRESS_TEST_SLEEP_TIME_KEY).get_to(stlevel.sleepTime); + } + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // STRESS_TEST_CONFIG_PARSER_H diff --git a/test/systemtest/common/task_dispatcher/BUILD.gn b/test/systemtest/common/task_dispatcher/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..e91de9647fbd3e3de6edcaee272a88ef7a337ae9 --- /dev/null +++ b/test/systemtest/common/task_dispatcher/BUILD.gn @@ -0,0 +1,90 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/task_dispatcher/" + +config("system_test_task_dispatcher_config") { + include_dirs = [ + "//foundation/aafwk/standard/common/task_dispatcher/include/threading", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include/task", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_systemtest("task_dispatcher_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/include", + "//third_party/jsoncpp/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//base/notification/ces_standard/test/systemtest/common/resource", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/st_ability_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "src/task_dispatcher_test.cpp", + "src/task_dispatcher_tools.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${aafwk_path}/services/appmgr:appmgr_config", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_config", + + ":system_test_task_dispatcher_config", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/:system_test_ability_util_config", + "//foundation/appexecfwk/standard/libs/libeventhandler:libeventhandler_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest_task") { + testonly = true + + deps = [ ":task_dispatcher_test" ] +} diff --git a/test/systemtest/common/task_dispatcher/include/task_dispatcher_test_info.h b/test/systemtest/common/task_dispatcher/include/task_dispatcher_test_info.h new file mode 100644 index 0000000000000000000000000000000000000000..3965bd24c1b0b6782af4dc749241f4f993860c2c --- /dev/null +++ b/test/systemtest/common/task_dispatcher/include/task_dispatcher_test_info.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TASK_DISPATCHER_TEST_INFO_H +#define TASK_DISPATCHER_TEST_INFO_H +namespace OHOS { +namespace AppExecFwk { +#include + +const std::string g_EVENT_REQU_FIRST = "requ_com_ohos_task_dispatcher_first"; +const std::string g_EVENT_RESP_FIRST = "resp_com_ohos_task_dispatcher_first"; +const std::string g_EVENT_REQU_SECOND = "requ_com_ohos_task_dispatcher_second"; +const std::string g_EVENT_RESP_SECOND = "resp_com_ohos_task_dispatcher_second"; +const std::string g_EVENT_REQU_FIRST_B = "requ_com_ohos_task_dispatcher_first_b"; +const std::string g_EVENT_RESP_FIRST_B = "resp_com_ohos_task_dispatcher_first_b"; +const std::string g_EVENT_REQU_SECOND_B = "requ_com_ohos_task_dispatcher_second_b"; +const std::string g_EVENT_RESP_SECOND_B = "resp_com_ohos_task_dispatcher_second_b"; + +enum class TestFunc { + GLOBAL, + PARALLEL, + SERIAL, + SPEC, + HYBRID, + MULTI_APP, + PRIORITY, + CANCEL_TASK, + EXTRA, +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // TASK_DISPATCHER_TEST_INFO_H \ No newline at end of file diff --git a/test/systemtest/common/task_dispatcher/include/task_dispatcher_tools.h b/test/systemtest/common/task_dispatcher/include/task_dispatcher_tools.h new file mode 100644 index 0000000000000000000000000000000000000000..d9edf34f69d3b0ed5897436a489a66e965749707 --- /dev/null +++ b/test/systemtest/common/task_dispatcher/include/task_dispatcher_tools.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 TASK_DISPATCHER_ST_TOOLS +#define TASK_DISPATCHER_ST_TOOLS + +#include +#include +#include +#include + +#include "common_event_manager.h" +#include "context.h" +#include "group.h" +#include "app_log_wrapper.h" +#include "task_dispatcher.h" +#include "task_priority.h" +#include "revocable.h" +#include "runnable.h" + +namespace OHOS { +namespace STtools { +enum class TestDispatcher { + GLOBAL = 0, + PARALLEL, + SERIAL, + UI, + MAIN, +}; +enum class TestOperation { + SYNC = 0, + ASYNC, + DELAY, + SYNC_BARRIER, + ASYNC_BARRIER, + CREATE_GROUP, + ASYNC_GROUP, + GROUP_WAIT, + GROUP_NOTIFY, + APPLY, + REVOCABLE, +}; +struct TestSetting { + long apply = 1; + long delay = 0; + long group_timeout = 0; + bool sync_barrier = false; + bool async_barrier = false; + bool create_group = false; + bool group_wait = false; + bool group_notify = false; + TestDispatcher dispatcher; + TestOperation op; +}; + +class TaskList { +public: + TaskList() = default; + ~TaskList() = default; + TaskList(TestDispatcher dispatcher, std::shared_ptr &context, std::string name); + TaskList &setDispatcherName(std::string name); + TaskList &setDispatcher(TestDispatcher dispatcher); + TaskList &setTaskPriority(AppExecFwk::TaskPriority taskPriority); + TaskList &addOperation(TestOperation operation); + TaskList &setContext(std::shared_ptr &context); + TaskList &addFunc(std::shared_ptr runnable); + + TaskList &addDelay(long delay); + TaskList &addApply(long apply); + TaskList &addRevokeTask(unsigned int num); + TaskList &addWaitTime(long time); + bool executedTask(); + + std::shared_ptr getDispatcher(); + +private: + void makeDispatcher(); + void executeSyncDispatch(); + void executeAsyncDispatch(); + void executeDelayDispatch(); + void executeSyncDispatchBarrier(); + void executeAsyncDispatchBarrier(); + void executeCreateDispatchGroup(); + void executeAsyncGroupDispatch(); + bool executeGroupDispatchWait(); + void executeGroupDispatchNotify(); + void executeApplyDispatch(); + bool executeRevokeTask(); + +private: + TestDispatcher dispatcher = TestDispatcher::GLOBAL; + AppExecFwk::TaskPriority taskPriority = AppExecFwk::TaskPriority::DEFAULT; + std::vector dispatchList; + std::shared_ptr context = nullptr; + std::shared_ptr taskDispatcher = nullptr; + std::queue> funcList; + std::shared_ptr group = nullptr; + std::vector> revocableList; + std::queue delayTimes; + std::queue applyTimes; + std::queue groupWaitTimes; + std::string name; + std::queue revokeTaskNumber; +}; +} // namespace STtools +} // namespace OHOS +#endif // TASK_DISPATCHER_ST_TOOLS \ No newline at end of file diff --git a/test/systemtest/common/task_dispatcher/src/task_dispatcher_test.cpp b/test/systemtest/common/task_dispatcher/src/task_dispatcher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ffa2bcf08fd4ba6869323f2e2c02851631856ff2 --- /dev/null +++ b/test/systemtest/common/task_dispatcher/src/task_dispatcher_test.cpp @@ -0,0 +1,8186 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "ability_lifecycle_executor.h" +#include "common_event_manager.h" +#include "st_ability_util.h" +#include "task_dispatcher_test_info.h" +#include "testConfigParser.h" + +namespace { +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; +using namespace OHOS::STtools; +using namespace testing::ext; +using namespace STABUtil; + +using MAP_STR_STR = std::map; +const std::string bundleNameFirst = "com.ohos.TaskDispatcherA"; +const std::string bundleNameSecond = "com.ohos.TaskDispatcherB"; +const std::string firstAbilityName = "MainAbility"; +const std::string secondAbilityname = "SecondAbility"; +constexpr int WAIT_TIME = 500; +constexpr int DELAY = 10; +int testCaseCode = 100; +std::vector bundleNameList = { + "com.ohos.TaskDispatcherA", + "com.ohos.TaskDispatcherB", +}; +std::vector hapNameList = { + "taskDispatcherTestA", + "taskDispatcherTestB", +}; + +class TaskDispatcherTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static bool SubscribeEvent(); + class AppEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { + public: + explicit AppEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; + ~AppEventSubscriber() {}; + }; + + void StartAbility(const std::string &abilityName, const std::string &bundleName); + static OHOS::sptr abilityMs; + static OHOS::STtools::Event event; + static OHOS::StressTestLevel stLevel_; + static std::shared_ptr subscriber_; +}; + +Event TaskDispatcherTest::event = STtools::Event(); +sptr TaskDispatcherTest::abilityMs = nullptr; +StressTestLevel TaskDispatcherTest::stLevel_ {}; +std::shared_ptr TaskDispatcherTest::subscriber_ = nullptr; + +void TaskDispatcherTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } + TestConfigParser tcp; + tcp.ParseFromFile4StressTest(STRESS_TEST_CONFIG_FILE_PATH, stLevel_); + std::cout << "stress test level : " + << "AMS : " << stLevel_.AMSLevel << " " + << "BMS : " << stLevel_.BMSLevel << " " + << "CES : " << stLevel_.CESLevel << std::endl; + stLevel_.AMSLevel = 1; +} +void TaskDispatcherTest::TearDownTestCase(void) +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void TaskDispatcherTest::SetUp() +{ + STAbilityUtil::InstallHaps(hapNameList); +} + +void TaskDispatcherTest::TearDown() +{ + STAbilityUtil::UninstallBundle(bundleNameList); + STAbilityUtil::CleanMsg(event); +} + +void TaskDispatcherTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + STAbilityUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); +} + +bool TaskDispatcherTest::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_RESP_FIRST, + g_EVENT_RESP_SECOND, + g_EVENT_RESP_FIRST_B, + g_EVENT_RESP_SECOND_B, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void TaskDispatcherTest::StartAbility(const std::string &abilityName, const std::string &bundleName) +{ + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + ErrCode result = STAbilityUtil::StartAbility(want, abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "TaskDispatcherTest::StartAbility : " << result; + if (bundleName == bundleNameSecond) { + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST_B, 0, DELAY)); + } else { + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, 0, DELAY)); + } +} + +/** + * @tc.number : TaskDispatcher_Global_00100 + * @tc.name : global sync:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00200 + * @tc.name : global sync:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_1"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00300 + * @tc.name : global sync:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_2"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00400 + * @tc.name : global sync:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_3"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00500 + * @tc.name : global sync:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_4"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00600 + * @tc.name : global sync:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_5"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00700 + * @tc.name : global sync:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_6"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00800 + * @tc.name : global sync:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_7"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_00900 + * @tc.name : global sync:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_00900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_8"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01000 + * @tc.name : global sync:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_9"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01100 + * @tc.name : global sync:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_10"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01200 + * @tc.name : global sync:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_11"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01300 + * @tc.name : global sync:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_12"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01400 + * @tc.name : global async:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_13"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01500 + * @tc.name : global async:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_14"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01600 + * @tc.name : global async:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_15"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01700 + * @tc.name : global async:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_16"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01800 + * @tc.name : global async:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_17"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_01900 + * @tc.name : global async:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_01900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_18"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_01900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02000 + * @tc.name : global async:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_19"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02100 + * @tc.name : global async:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_20"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02200 + * @tc.name : global async:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_21"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02300 + * @tc.name : global async:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_22"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02400 + * @tc.name : global async:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_23"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02500 + * @tc.name : global async:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_24"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02600 + * @tc.name : global async:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_25"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02700 + * @tc.name : global delay:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_26"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02800 + * @tc.name : global delay:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_27"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_02900 + * @tc.name : global delay:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_02900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_28"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_02900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03000 + * @tc.name : global delay:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_29"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03100 + * @tc.name : global delay:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_30"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03200 + * @tc.name : global delay:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_31"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03300 + * @tc.name : global delay:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_32"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03400 + * @tc.name : global delay:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_33"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03500 + * @tc.name : global delay:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_34"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03600 + * @tc.name : global delay:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_35"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03700 + * @tc.name : global delay:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_36"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03800 + * @tc.name : global delay:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_37"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_03900 + * @tc.name : global delay:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_03900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_38"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_03900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04000 + * @tc.name : global group:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_39"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04100 + * @tc.name : global group:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_40"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04200 + * @tc.name : global group:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_41"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04300 + * @tc.name : global group:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_42"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04400 + * @tc.name : global group:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_43"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04500 + * @tc.name : global group:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_44"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04600 + * @tc.name : global group:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_45"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04700 + * @tc.name : global group:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_46"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04800 + * @tc.name : global group:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_47"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_04900 + * @tc.name : global group:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_04900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_48"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_04900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05000 + * @tc.name : global group:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_49"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05100 + * @tc.name : global group:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_50"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05200 + * @tc.name : global group:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_51"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05300 + * @tc.name : global group wait:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_52"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05400 + * @tc.name : global group wait:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_53"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05500 + * @tc.name : global group wait:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_54"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05600 + * @tc.name : global group wait:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_55"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05700 + * @tc.name : global group wait:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_56"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05800 + * @tc.name : global group wait:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_57"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_05900 + * @tc.name : global group wait:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_05900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_58"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_05900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06000 + * @tc.name : global group wait:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_59"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06100 + * @tc.name : global group wait:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_60"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06200 + * @tc.name : global group wait:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_61"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06300 + * @tc.name : global group wait:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_62"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06400 + * @tc.name : global group wait:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_63"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06500 + * @tc.name : global group wait:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_64"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06600 + * @tc.name : global group notify:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_65"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06700 + * @tc.name : global group notify:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_66"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06800 + * @tc.name : global group notify:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_67"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_06900 + * @tc.name : global group notify:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_06900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_68"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_06900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07000 + * @tc.name : global group notify:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_69"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07100 + * @tc.name : global group notify:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_70"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07200 + * @tc.name : global group notify:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_71"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07300 + * @tc.name : global group notify:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_72"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07400 + * @tc.name : global group notify:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_73"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07500 + * @tc.name : global group notify:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_74"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07600 + * @tc.name : global group notify:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_75"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07700 + * @tc.name : global group notify:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_76"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07800 + * @tc.name : global group notify:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_77"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_07900 + * @tc.name : global apply:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_07900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_78"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_07900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08000 + * @tc.name : global apply:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_79"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08100 + * @tc.name : global apply:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_80"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08200 + * @tc.name : global apply:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_81"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08300 + * @tc.name : global apply:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_82"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08400 + * @tc.name : global apply:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_83"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08500 + * @tc.name : global apply:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_84"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08600 + * @tc.name : global apply:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_85"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08700 + * @tc.name : global apply:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_86"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08800 + * @tc.name : global apply:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_87"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_08900 + * @tc.name : global apply:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_08900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_88"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_08900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_09000 + * @tc.name : global apply:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_09000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_89"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_09000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Global_09100 + * @tc.name : global apply:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Global_09100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::GLOBAL) + "_90"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_09100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00100 + * @tc.name : parallel sync:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00200 + * @tc.name : parallel sync:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_1"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00300 + * @tc.name : parallel sync:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_2"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00400 + * @tc.name : parallel sync:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_3"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00500 + * @tc.name : parallel sync:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_4"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00600 + * @tc.name : parallel sync:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_5"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00700 + * @tc.name : parallel sync:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_6"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00800 + * @tc.name : parallel sync:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_7"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_00900 + * @tc.name : parallel sync:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_00900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_8"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_00900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01000 + * @tc.name : parallel sync:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_9"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01100 + * @tc.name : parallel sync:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_10"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01200 + * @tc.name : parallel sync:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_11"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01300 + * @tc.name : parallel sync:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_12"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01400 + * @tc.name : parallel async:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_13"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01500 + * @tc.name : parallel async:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_14"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01600 + * @tc.name : parallel async:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_15"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01700 + * @tc.name : parallel async:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_16"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01800 + * @tc.name : parallel async:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_17"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_01900 + * @tc.name : parallel async:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_01900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_18"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_01900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02000 + * @tc.name : parallel async:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_19"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02100 + * @tc.name : parallel async:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_20"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02200 + * @tc.name : parallel async:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_21"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02300 + * @tc.name : parallel async:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_22"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02400 + * @tc.name : parallel async:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_23"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02500 + * @tc.name : parallel async:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_24"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02600 + * @tc.name : parallel async:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_25"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02700 + * @tc.name : parallel delay:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_26"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02800 + * @tc.name : parallel delay:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_27"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_02900 + * @tc.name : parallel delay:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_02900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_28"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_02900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03000 + * @tc.name : parallel delay:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_29"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03100 + * @tc.name : parallel delay:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_30"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03200 + * @tc.name : parallel delay:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_31"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03300 + * @tc.name : parallel delay:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_32"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03400 + * @tc.name : parallel delay:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_33"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03500 + * @tc.name : parallel delay:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_34"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03600 + * @tc.name : parallel delay:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_35"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03700 + * @tc.name : parallel delay:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_36"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03800 + * @tc.name : parallel delay:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_37"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_03900 + * @tc.name : parallel delay:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_03900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_38"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_03900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04000 + * @tc.name : parallel group:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_39"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04100 + * @tc.name : parallel group:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_40"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04200 + * @tc.name : parallel group:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_41"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04300 + * @tc.name : parallel group:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_42"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04400 + * @tc.name : parallel group:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_43"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04500 + * @tc.name : parallel group:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_44"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04600 + * @tc.name : parallel group:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_45"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04700 + * @tc.name : parallel group:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_46"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04800 + * @tc.name : parallel group:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_47"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_04900 + * @tc.name : parallel group:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_04900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_48"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_04900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05000 + * @tc.name : parallel group:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_49"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05100 + * @tc.name : parallel group:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_50"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05200 + * @tc.name : parallel group:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_51"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05300 + * @tc.name : parallel group wait:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_52"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05400 + * @tc.name : parallel group wait:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_53"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05500 + * @tc.name : parallel group wait:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_54"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05600 + * @tc.name : parallel group wait:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_55"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05700 + * @tc.name : parallel group wait:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_56"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05800 + * @tc.name : parallel group wait:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_57"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_05900 + * @tc.name : parallel group wait:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_05900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_58"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_05900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06000 + * @tc.name : parallel group wait:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_59"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06100 + * @tc.name : parallel group wait:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_60"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06200 + * @tc.name : parallel group wait:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_61"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06300 + * @tc.name : parallel group wait:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_62"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06400 + * @tc.name : parallel group wait:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_63"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06500 + * @tc.name : parallel group wait:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_64"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06600 + * @tc.name : parallel group notify:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_65"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06700 + * @tc.name : parallel group notify:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_66"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06800 + * @tc.name : parallel group notify:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_67"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_06900 + * @tc.name : parallel group notify:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_06900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_68"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_06900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07000 + * @tc.name : parallel group notify:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_69"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07100 + * @tc.name : parallel group notify:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_70"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07200 + * @tc.name : parallel group notify:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_71"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07300 + * @tc.name : parallel group notify:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_72"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07400 + * @tc.name : parallel group notify:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_73"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07500 + * @tc.name : parallel group notify:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_74"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07600 + * @tc.name : parallel group notify:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_75"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07700 + * @tc.name : parallel group notify:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_76"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07800 + * @tc.name : parallel group notify:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_77"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_07900 + * @tc.name : parallel sync barrier:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_07900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_78"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_07900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08000 + * @tc.name : parallel sync barrier:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_79"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08100 + * @tc.name : parallel sync barrier:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_80"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08200 + * @tc.name : parallel sync barrier:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_81"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08300 + * @tc.name : parallel sync barrier:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_82"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08400 + * @tc.name : parallel sync barrier:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_83"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08500 + * @tc.name : parallel sync barrier:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_84"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08600 + * @tc.name : parallel sync barrier:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_85"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08700 + * @tc.name : parallel sync barrier:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_86"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08800 + * @tc.name : parallel sync barrier:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_87"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_08900 + * @tc.name : parallel sync barrier:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_08900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_88"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_08900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09000 + * @tc.name : parallel sync barrier:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_89"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09100 + * @tc.name : parallel sync barrier:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_90"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09200 + * @tc.name : parallel async barrier:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_91"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09300 + * @tc.name : parallel async barrier:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_92"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09400 + * @tc.name : parallel async barrier:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_93"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09500 + * @tc.name : parallel async barrier:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_94"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09600 + * @tc.name : parallel async barrier:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_95"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09700 + * @tc.name : parallel async barrier:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_96"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09800 + * @tc.name : parallel async barrier:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_97"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_09900 + * @tc.name : parallel async barrier:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_09900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_98"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_09900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10000 + * @tc.name : parallel async barrier:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_99"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10100 + * @tc.name : parallel async barrier:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_100"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10200 + * @tc.name : parallel async barrier:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_101"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10300 + * @tc.name : parallel async barrier:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_102"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10400 + * @tc.name : parallel async barrier:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_103"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10500 + * @tc.name : parallel apply:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_104"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10600 + * @tc.name : parallel apply:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_105"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10700 + * @tc.name : parallel apply:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_106"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10800 + * @tc.name : parallel apply:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_107"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_10900 + * @tc.name : parallel apply:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_10900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_108"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_10900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11000 + * @tc.name : parallel apply:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_109"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11100 + * @tc.name : parallel apply:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_110"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11200 + * @tc.name : parallel apply:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_111"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11300 + * @tc.name : parallel apply:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_112"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11400 + * @tc.name : parallel apply:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_113"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11500 + * @tc.name : parallel apply:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_114"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11600 + * @tc.name : parallel apply:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_115"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Parallel_11700 + * @tc.name : parallel apply:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Parallel_11700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PARALLEL) + "_116"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Parallel_11700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00100 + * @tc.name : serial sync:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00200 + * @tc.name : serial sync:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_1"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00300 + * @tc.name : serial sync:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_2"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00400 + * @tc.name : serial sync:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_3"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00500 + * @tc.name : serial sync:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_4"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00600 + * @tc.name : serial sync:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_5"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00700 + * @tc.name : serial sync:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_6"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00800 + * @tc.name : serial sync:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_7"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_00900 + * @tc.name : serial sync:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_00900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_8"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_00900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01000 + * @tc.name : serial sync:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_9"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01100 + * @tc.name : serial sync:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_10"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01200 + * @tc.name : serial sync:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_11"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01300 + * @tc.name : serial sync:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_12"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01400 + * @tc.name : serial async:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_13"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01500 + * @tc.name : serial async:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_14"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01600 + * @tc.name : serial async:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_15"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01700 + * @tc.name : serial async:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_16"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01800 + * @tc.name : serial async:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_17"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_01900 + * @tc.name : serial async:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_01900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_18"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_01900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02000 + * @tc.name : serial async:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_19"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02100 + * @tc.name : serial async:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_20"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02200 + * @tc.name : serial async:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_21"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02300 + * @tc.name : serial async:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_22"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02400 + * @tc.name : serial async:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_23"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02500 + * @tc.name : serial async:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_24"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02600 + * @tc.name : serial async:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_25"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02700 + * @tc.name : serial delay:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_26"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02800 + * @tc.name : serial delay:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_27"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_02900 + * @tc.name : serial delay:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_02900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_28"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_02900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03000 + * @tc.name : serial delay:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_29"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03100 + * @tc.name : serial delay:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_30"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03200 + * @tc.name : serial delay:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_31"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03300 + * @tc.name : serial delay:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_32"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03400 + * @tc.name : serial delay:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_33"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03500 + * @tc.name : serial delay:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_34"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03600 + * @tc.name : serial delay:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_35"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03700 + * @tc.name : serial delay:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_36"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03800 + * @tc.name : serial delay:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_37"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_03900 + * @tc.name : serial delay:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_03900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_38"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_03900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04000 + * @tc.name : serial apply:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_39"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04100 + * @tc.name : serial apply:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_40"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04200 + * @tc.name : serial apply:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_41"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04300 + * @tc.name : serial apply:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_42"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04400 + * @tc.name : serial apply:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_43"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04500 + * @tc.name : serial apply:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_44"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04600 + * @tc.name : serial apply:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_45"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04700 + * @tc.name : serial apply:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_46"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04800 + * @tc.name : serial apply:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_47"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_04900 + * @tc.name : serial apply:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_04900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_48"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_04900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_05000 + * @tc.name : serial apply:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_05000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_49"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_05000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_05100 + * @tc.name : serial apply:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_05100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_50"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_05100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Serial_05200 + * @tc.name : serial apply:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Serial_05200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SERIAL) + "_51"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Serial_05200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00100 + * @tc.name : spec sync:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00200 + * @tc.name : spec sync:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_1"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00300 + * @tc.name : spec sync:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_2"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00400 + * @tc.name : spec sync:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_3"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00500 + * @tc.name : spec sync:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_4"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00600 + * @tc.name : spec sync:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_5"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00700 + * @tc.name : spec sync:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_6"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00800 + * @tc.name : spec sync:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_7"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_00900 + * @tc.name : spec sync:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_00900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_8"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_00900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01000 + * @tc.name : spec sync:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_9"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01100 + * @tc.name : spec sync:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_10"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01200 + * @tc.name : spec sync:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_11"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01300 + * @tc.name : spec sync:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_12"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01400 + * @tc.name : spec async:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_13"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01500 + * @tc.name : spec async:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_14"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01600 + * @tc.name : spec async:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_15"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01700 + * @tc.name : spec async:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_16"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01800 + * @tc.name : spec async:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_17"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_01900 + * @tc.name : spec async:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_01900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_18"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_01900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02000 + * @tc.name : spec async:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_19"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02100 + * @tc.name : spec async:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_20"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02200 + * @tc.name : spec async:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_21"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02300 + * @tc.name : spec async:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_22"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02400 + * @tc.name : spec async:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_23"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02500 + * @tc.name : spec async:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_24"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02600 + * @tc.name : spec async:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_25"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02700 + * @tc.name : spec delay:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_26"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02800 + * @tc.name : spec delay:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_27"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_02900 + * @tc.name : spec delay:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_02900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_28"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_02900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03000 + * @tc.name : spec delay:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_29"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03100 + * @tc.name : spec delay:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_30"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03200 + * @tc.name : spec delay:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_31"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03300 + * @tc.name : spec delay:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_32"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03400 + * @tc.name : spec delay:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_33"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03500 + * @tc.name : spec delay:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_34"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03600 + * @tc.name : spec delay:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_35"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03700 + * @tc.name : spec delay:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_36"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03800 + * @tc.name : spec delay:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_37"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_03900 + * @tc.name : spec delay:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_03900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_38"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_03900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04000 + * @tc.name : spec apply:parallel sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_39"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04100 + * @tc.name : spec apply:parallel async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_40"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04200 + * @tc.name : spec apply:parallel delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_41"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04300 + * @tc.name : spec apply:parallel group + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_42"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04400 + * @tc.name : spec apply:parallel group wait + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_43"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04500 + * @tc.name : spec apply:parallel group notify + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_44"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04600 + * @tc.name : spec apply:parallel sync barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_45"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04600 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04700 + * @tc.name : spec apply:parallel async barrier + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_46"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04800 + * @tc.name : spec apply:parallel apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_47"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04800 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_04900 + * @tc.name : spec apply:serial sync + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_04900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_48"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_04900 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_05000 + * @tc.name : spec apply:serial async + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_05000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_49"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_05000 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_05100 + * @tc.name : spec apply:serial delay + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_05100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_50"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_05100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Spec_05200 + * @tc.name : spec apply:serial apply + * @tc.desc : two levels task dispatch + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Spec_05200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::SPEC) + "_51"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Spec_05200 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00100 + * @tc.name : GlobalTaskDispatcher all operation + * @tc.desc : dispatcher all operation in GolbalTaskDispatcher + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Global_00100 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00200 + * @tc.name : ParallelTaskDispatcher all operation + * @tc.desc : dispatcher all operation in ParallelTaskDispatcher + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_1"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00200 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00300 + * @tc.name : SerialTaskDispatcher all operation + * @tc.desc : dispatcher all operation in SerialTaskDispatcher + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_2"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00300 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00400 + * @tc.name : SpecTaskDispatcher all operation + * @tc.desc : dispatcher all operation in GolbalTaskDispatcher + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_3"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00400 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00500 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_4"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00500 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00600 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_5"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00600 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00700 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_6"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00700 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00800 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_7"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00800 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00900 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_00900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_8"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_00900 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01000 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_9"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01000 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01100 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_10"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01100 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01200 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_11"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01200 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01300 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_12"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01300 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01400 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_13"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01400 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01500 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_14"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01500 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01600 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_15"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01600 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01700 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_16"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01700 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01800 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01800, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_17"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01800 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_01900 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_01900, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_18"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_01900 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_02000 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02000, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_19"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02000 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_02100 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_20"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02100 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_02200 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_21"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02200 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_00500 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_22"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02300 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_02400 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_23"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02400 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_02500 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_24"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02500 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_02600 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_25"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02600 : " << i; + break; + } + } +} +/** + * @tc.number : TaskDispatcher_Hybird_02700 + * @tc.name : MutiDispatcher hybird + * @tc.desc : dispatcher task in MutiDispatcher by unorder operations + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Hybird_02700, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::HYBRID) + "_26"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Hybird_02700 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Extra_00100 + * @tc.name : start ability in Dispatcher + * @tc.desc : start service ability in dispatcher + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Extra_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::EXTRA) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_SECOND, 0, DELAY)); + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Rxtra_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Priority_00100 + * @tc.name : task Dispatcher priority + * @tc.desc : use dispatcher in different prioritys + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Priority_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PRIORITY) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Priority_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Priority_00200 + * @tc.name : task Dispatcher priority + * @tc.desc : use dispatcher in different prioritys + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Priority_00200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PRIORITY) + "_1"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Priority_00200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Priority_00300 + * @tc.name : task Dispatcher priority + * @tc.desc : use dispatcher in different prioritys + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Priority_00300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PRIORITY) + "_2"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Priority_00300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Priority_00400 + * @tc.name : task Dispatcher priority + * @tc.desc : use dispatcher in different prioritys + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Priority_00400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PRIORITY) + "_3"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Priority_00400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_Priority_00500 + * @tc.name : task Dispatcher priority + * @tc.desc : use dispatcher in different prioritys + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_Priority_00500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::PRIORITY) + "_4"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_Priority_00500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_CancelTask_00100 + * @tc.name : cancel async task successed + * @tc.desc : cancel async task successed + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_CancelTask_00100, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::CANCEL_TASK) + "_0"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_CancelTask_00100 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_CancelTask_00200 + * @tc.name : cancel async task failed + * @tc.desc : cancel async task failed + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_CancelTask_00200, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::CANCEL_TASK) + "_1"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_CancelTask_00200 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_CancelTask_00300 + * @tc.name : cancel delay task successed + * @tc.desc : cancel delay task successed + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_CancelTask_00300, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::CANCEL_TASK) + "_2"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_CancelTask_00300 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_CancelTask_00400 + * @tc.name : cancel delay task failed + * @tc.desc : cancel delay task failed + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_CancelTask_00400, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::CANCEL_TASK) + "_3"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_CancelTask_00400 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_CancelTask_00500 + * @tc.name : cancel async_group task successed + * @tc.desc : cancel async_group task successed + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_CancelTask_00500, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::CANCEL_TASK) + "_4"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_CancelTask_00500 : " << i; + break; + } + } +} + +/** + * @tc.number : TaskDispatcher_CancelTask_00600 + * @tc.name : cancel async_group task failed + * @tc.desc : cancel async_group task failed + */ +HWTEST_F(TaskDispatcherTest, TaskDispatcher_CancelTask_00600, Function | MediumTest | Level1) +{ + StartAbility(firstAbilityName, bundleNameFirst); + std::string data = "Dispatcher_" + std::to_string((int)TestFunc::CANCEL_TASK) + "_5"; + bool result = false; + for (int i = 0; i < stLevel_.AMSLevel; i++) { + STAbilityUtil::PublishEvent(g_EVENT_REQU_FIRST, ++testCaseCode, data); + EXPECT_EQ(0, STAbilityUtil::WaitCompleted(event, g_EVENT_RESP_FIRST, testCaseCode, DELAY)); + data = STAbilityUtil::GetData(event, g_EVENT_RESP_FIRST, testCaseCode); + result = data.compare("1") == 0; + EXPECT_TRUE(result); + if (!result && i > 0) { + GTEST_LOG_(INFO) << "TaskDispatcher_CancelTask_00600 : " << i; + break; + } + } +} +} // namespace \ No newline at end of file diff --git a/test/systemtest/common/task_dispatcher/src/task_dispatcher_tools.cpp b/test/systemtest/common/task_dispatcher/src/task_dispatcher_tools.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a37c916d4928c180a492230d93b0ffe60ef8535d --- /dev/null +++ b/test/systemtest/common/task_dispatcher/src/task_dispatcher_tools.cpp @@ -0,0 +1,296 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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_dispatcher_tools.h" + +namespace OHOS { +namespace STtools { +using namespace AppExecFwk; +using namespace EventFwk; + +TaskList::TaskList(TestDispatcher dispatcher, std::shared_ptr &context, std::string name) + : dispatcher(dispatcher), context(context), name(name){}; +TaskList &TaskList::setDispatcherName(std::string name) +{ + this->name = name; + return *this; +} +TaskList &TaskList::setDispatcher(TestDispatcher dispatcher) +{ + this->dispatcher = dispatcher; + return *this; +}; +TaskList &TaskList::setTaskPriority(TaskPriority taskPriority) +{ + this->taskPriority = taskPriority; + return *this; +} +TaskList &TaskList::addOperation(TestOperation operation) +{ + this->dispatchList.push_back(operation); + return *this; +}; +TaskList &TaskList::setContext(std::shared_ptr &context) +{ + this->context = context; + return *this; +}; +std::shared_ptr TaskList::getDispatcher() +{ + makeDispatcher(); + return taskDispatcher; +}; +TaskList &TaskList::addFunc(std::shared_ptr runnable) +{ + funcList.push(runnable); + return *this; +}; +TaskList &TaskList::addDelay(long delay) +{ + delayTimes.push(delay); + return *this; +}; +TaskList &TaskList::addApply(long apply) +{ + applyTimes.push(apply); + return *this; +}; +TaskList &TaskList::addRevokeTask(unsigned int num) +{ + revokeTaskNumber.push(num); + return *this; +} +TaskList &TaskList::addWaitTime(long time) +{ + groupWaitTimes.push(time); + return *this; +} +bool TaskList::executedTask() +{ + bool result = true; + makeDispatcher(); + if (taskDispatcher == nullptr) { + return false; + } + for (auto operation : dispatchList) { + switch (operation) { + case TestOperation::SYNC: + executeSyncDispatch(); + break; + case TestOperation::ASYNC: + executeAsyncDispatch(); + break; + case TestOperation::DELAY: + executeDelayDispatch(); + break; + case TestOperation::SYNC_BARRIER: + executeSyncDispatchBarrier(); + break; + case TestOperation::ASYNC_BARRIER: + executeAsyncDispatchBarrier(); + break; + case TestOperation::CREATE_GROUP: + executeCreateDispatchGroup(); + break; + case TestOperation::ASYNC_GROUP: + executeAsyncGroupDispatch(); + break; + case TestOperation::GROUP_WAIT: + result = executeGroupDispatchWait(); + break; + case TestOperation::GROUP_NOTIFY: + executeGroupDispatchNotify(); + break; + case TestOperation::APPLY: + executeApplyDispatch(); + break; + case TestOperation::REVOCABLE: + result = executeRevokeTask(); + break; + default: + result = false; + break; + } + } + return result; +}; + +void TaskList::makeDispatcher() +{ + if (context == nullptr) { + taskDispatcher = nullptr; + return; + } + if (taskDispatcher != nullptr) { + return; + } + switch (dispatcher) { + case TestDispatcher::GLOBAL: + taskDispatcher = context->GetGlobalTaskDispatcher(taskPriority); + break; + case TestDispatcher::PARALLEL: + taskDispatcher = context->CreateParallelTaskDispatcher(name, taskPriority); + break; + case TestDispatcher::SERIAL: + taskDispatcher = context->CreateSerialTaskDispatcher(name, taskPriority); + break; + case TestDispatcher::UI: + taskDispatcher = context->GetUITaskDispatcher(); + break; + case TestDispatcher::MAIN: + taskDispatcher = context->GetMainTaskDispatcher(); + break; + default: + break; + } + return; +}; + +void TaskList::executeSyncDispatch() +{ + APP_LOGI("TaskList::executeSyncDispatch"); + if (funcList.size() == 0) { + return; + } + APP_LOGI("TaskList::executeSyncDispatch execute"); + auto runnable = funcList.front(); + funcList.pop(); + taskDispatcher->SyncDispatch(runnable); + return; +}; +void TaskList::executeAsyncDispatch() +{ + APP_LOGI("TaskList::executeAsyncDispatch"); + if (funcList.size() == 0) { + return; + } + APP_LOGI("TaskList::executeAsyncDispatch execute"); + auto runnable = funcList.front(); + funcList.pop(); + std::shared_ptr revocable = taskDispatcher->AsyncDispatch(runnable); + revocableList.push_back(revocable); + return; +}; +void TaskList::executeDelayDispatch() +{ + APP_LOGI("TaskList::executeDelayDispatch"); + if (funcList.size() == 0 || delayTimes.size() == 0) { + return; + } + APP_LOGI("TaskList::executeDelayDispatch execute"); + auto runnable = funcList.front(); + funcList.pop(); + std::shared_ptr revocable = taskDispatcher->DelayDispatch(runnable, delayTimes.front()); + delayTimes.pop(); + revocableList.push_back(revocable); + return; +}; +void TaskList::executeSyncDispatchBarrier() +{ + APP_LOGI("TaskList::executeSyncDispatchBarrier"); + if (funcList.size() == 0) { + return; + } + APP_LOGI("TaskList::executeSyncDispatchBarrier execute"); + auto runnable = funcList.front(); + funcList.pop(); + taskDispatcher->SyncDispatchBarrier(runnable); + return; +}; +void TaskList::executeAsyncDispatchBarrier() +{ + APP_LOGI("TaskList::executeAsyncDispatchBarrier"); + if (funcList.size() == 0) { + return; + } + APP_LOGI("TaskList::executeAsyncDispatchBarrier execute"); + auto runnable = funcList.front(); + funcList.pop(); + taskDispatcher->AsyncDispatchBarrier(runnable); + return; +}; +void TaskList::executeCreateDispatchGroup() +{ + APP_LOGI("TaskList::executeCreateDispatchGroup execute"); + group = taskDispatcher->CreateDispatchGroup(); + return; +}; +void TaskList::executeAsyncGroupDispatch() +{ + APP_LOGI("TaskList::executeAsyncGroupDispatch"); + if (funcList.size() == 0) { + return; + } + APP_LOGI("TaskList::executeAsyncGroupDispatch execute"); + auto runnable = funcList.front(); + funcList.pop(); + std::shared_ptr revocable = taskDispatcher->AsyncGroupDispatch(group, runnable); + revocableList.push_back(revocable); + return; +}; +bool TaskList::executeGroupDispatchWait() +{ + APP_LOGI("TaskList::executeGroupDispatchWait"); + if (groupWaitTimes.size() == 0) { + return false; + } + APP_LOGI("TaskList::executeGroupDispatchWait execute"); + long waitTimeout = groupWaitTimes.front(); + groupWaitTimes.pop(); + return taskDispatcher->GroupDispatchWait(group, waitTimeout); +}; +void TaskList::executeGroupDispatchNotify() +{ + APP_LOGI("TaskList::executeGroupDispatchNotify"); + if (funcList.size() == 0) { + return; + } + APP_LOGI("TaskList::executeGroupDispatchNotify execute"); + auto runnable = funcList.front(); + funcList.pop(); + taskDispatcher->GroupDispatchNotify(group, runnable); +}; +void TaskList::executeApplyDispatch() +{ + APP_LOGI("TaskList::executeApplyDispatch"); + if (funcList.size() == 0 || applyTimes.size() == 0) { + return; + } + APP_LOGI("TaskList::executeApplyDispatch execute"); + auto func = funcList.front(); + funcList.pop(); + auto runnable = std::make_shared>([func](long applyTime) { (*func.get())(); }); + taskDispatcher->ApplyDispatch(runnable, applyTimes.front()); + applyTimes.pop(); +}; +bool TaskList::executeRevokeTask() +{ + APP_LOGI("TaskList::executeRevokeTask"); + if (revokeTaskNumber.size() == 0 || revocableList.size() == 0) { + if (revokeTaskNumber.size() > 0) { + revokeTaskNumber.pop(); + } + return false; + } + if (revocableList.size() < revokeTaskNumber.front()) { + revokeTaskNumber.pop(); + return false; + } + APP_LOGI("TaskList::executeRevokeTask execute"); + bool result = revocableList[revokeTaskNumber.front() - 1]->Revoke(); + revokeTaskNumber.pop(); + return result; +} +} // namespace STtools +} // namespace OHOS \ No newline at end of file diff --git a/tools/BUILD.gn b/tools/BUILD.gn index f3fdf0648f4e4396a4b213df8004ca90385cc7b6..69b1afddf20b8e1713408f5951ad8f3c00f2c915 100644 --- a/tools/BUILD.gn +++ b/tools/BUILD.gn @@ -17,6 +17,6 @@ import("//foundation/aafwk/standard/aafwk.gni") group("tools_target") { deps = [ "aa:tools_aa", - "zip:tools_zip", + "fm:tools_fm", ] } diff --git a/tools/aa/BUILD.gn b/tools/aa/BUILD.gn index 3b911ce2caf7b3044fde3bec9ac556575f6ad292..625017bad2571aab4e61fa5bfd9deb25533a9cec 100644 --- a/tools/aa/BUILD.gn +++ b/tools/aa/BUILD.gn @@ -18,7 +18,7 @@ config("ability_command_config") { include_dirs = [ "include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "//utils/system/safwk/native/include", "//third_party/jsoncpp/include", ] @@ -28,6 +28,11 @@ ohos_source_set("tools_aa_source_set") { sources = [ "src/ability_command.cpp", "src/shell_command.cpp", + "src/shell_command_result.cpp", + "src/system_time.cpp", + "src/test_observer.cpp", + "src/test_observer_proxy.cpp", + "src/test_observer_stub.cpp", ] public_configs = [ @@ -43,6 +48,7 @@ ohos_source_set("tools_aa_source_set") { deps = [ "${aafwk_path}/interfaces/innerkits/ability_manager:ability_manager", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", @@ -82,7 +88,7 @@ ohos_executable("aa") { install_enable = true subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "ability_tools" } group("tools_aa") { diff --git a/tools/aa/include/ability_command.h b/tools/aa/include/ability_command.h index 813851c2a651d52cdf24a12b1bf8da0fc3cc7530..7fde0445cb463dfeefefb6c3b22aa05532653ed5 100644 --- a/tools/aa/include/ability_command.h +++ b/tools/aa/include/ability_command.h @@ -30,7 +30,9 @@ const std::string HELP_MSG = "usage: aa \n" " start start ability with options\n" " stop-service stop service with options\n" " dump dump the ability stack info\n" - " force-stop force stop the process with bundle name\n"; + " dumpsys dump the ability info\n" + " force-stop force stop the process with bundle name\n" + " test start the test framework with options\n"; const std::string HELP_MSG_SCREEN = "usage: aa screen \n" @@ -61,6 +63,26 @@ const std::string HELP_MSG_DUMP = "usage: aa dump \n" " -e, --serv dump the service abilities\n" " -d, --data dump the data abilities\n"; +const std::string HELP_MSG_DUMPSYS = "usage: aa dumpsys \n" + "options list:\n" + " -h, --help list available commands\n" + " -a, --all dump all abilities\n" + " -l, --mission-list dump mission list\n" + " -i, --ability dump abilityRecordId\n" + " -e, --extension dump elementName\n" + " -p, --pending dump pendingWantRecordId\n" + " -r, --process dump process\n" + " -u, --userId userId\n" + " -c, --client client\n"; + +const std::string HELP_MSG_TEST = + "usage: aa test \n" + "options list:\n" + " -h, --help \ + list available commands\n" + " -p -s unittest -s class [-w ] \ + start the test framework with options\n"; + const std::string HELP_MSG_FORCE_STOP = "usage: aa force-stop \n"; const std::string HELP_MSG_NO_ABILITY_NAME_OPTION = "error: -a is expected"; @@ -81,6 +103,13 @@ const std::string STRING_SCREEN_POWER_OFF_NG = "error: failed to power off scree const std::string STRING_FORCE_STOP_OK = "force stop process successfully."; const std::string STRING_FORCE_STOP_NG = "error: failed to force stop process."; + +const std::string STRING_START_USER_TEST_OK = "start user test successfully."; +const std::string STRING_START_USER_TEST_NG = "error: failed to start user test."; + +const int USER_TEST_COMMAND_START_INDEX = 2; +const int USER_TEST_COMMAND_PARAMS_NUM = 2; +const int TIME_RATE_MS = 1000; } // namespace class AbilityManagerShellCommand : public ShellCommand { @@ -99,12 +128,18 @@ private: ErrCode RunAsStartAbility(); ErrCode RunAsStopService(); ErrCode RunAsDumpCommand(); + ErrCode RunAsDumpsysCommand(); ErrCode RunAsForceStop(); ErrCode RunAsDumpCommandOptopt(); ErrCode MakeWantFromCmd(Want &want, std::string &windowMode); -}; + ErrCode RunAsDumpSysCommandOptopt(); + ErrCode RunAsTestCommand(); + bool IsTestCommandIntegrity(const std::map ¶ms); + ErrCode TestCommandError(const std::string &info); + ErrCode StartUserTest(const std::map ¶ms); +}; } // namespace AAFwk } // namespace OHOS diff --git a/tools/aa/include/itest_observer.h b/tools/aa/include/itest_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..8d617010c80ecfb321af70bc68a6dcb6faa01cfa --- /dev/null +++ b/tools/aa/include/itest_observer.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_ITEST_OBSERVER_H +#define FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_ITEST_OBSERVER_H + +#include "iremote_broker.h" +#include "shell_command_result.h" + +namespace OHOS { +namespace AAFwk { +class ITestObserver : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.ITestObserver"); + + virtual void TestStatus(const std::string &msg, const int &resultCode) = 0; + virtual void TestFinished(const std::string &msg, const int &resultCode) = 0; + virtual ShellCommandResult ExecuteShellCommand( + const std::string &cmd, const int64_t timeoutMs) = 0; + + enum class Message { + AA_TEST_STATUS = 1, + AA_TEST_FINISHED = 2, + AA_EXECUTE_SHELL_COMMAND = 3, + }; +}; +} // namespace AAFwk +} // namespace OHOS + +#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_ITEST_OBSERVER_H diff --git a/tools/aa/include/shell_command_result.h b/tools/aa/include/shell_command_result.h new file mode 100644 index 0000000000000000000000000000000000000000..ba1beb9b797d5398ea8d86f014c27f2a54574312 --- /dev/null +++ b/tools/aa/include/shell_command_result.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_SHELL_COMMAND_RESULT_H +#define FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_SHELL_COMMAND_RESULT_H + +#include +#include "parcel.h" + +namespace OHOS { +namespace AAFwk { +struct ShellCommandResult : public Parcelable { + int32_t exitCode {-1}; + std::string stdResult {}; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ShellCommandResult *Unmarshalling(Parcel &parcel); +}; +} // namespace AAFwk +} // namespace OHOS + +#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_SHELL_COMMAND_RESULT_H \ No newline at end of file diff --git a/services/abilitymgr/include/configuration_holder.h b/tools/aa/include/system_time.h similarity index 67% rename from services/abilitymgr/include/configuration_holder.h rename to tools/aa/include/system_time.h index a80d99ca60e5eecea0b1991309fbbab320379ac8..49be9aa17a07e8d6abf9f88a9f104b40c214ff63 100644 --- a/services/abilitymgr/include/configuration_holder.h +++ b/tools/aa/include/system_time.h @@ -12,19 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_AAFWK_CONFIGURATION_HOLDER_H -#define OHOS_AAFWK_CONFIGURATION_HOLDER_H -#include "configuration.h" +#ifndef FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_SYSTEM_TIME_H +#define FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_SYSTEM_TIME_H + +#include "singleton.h" namespace OHOS { namespace AAFwk { -class ConfigurationHolder { +class SystemTime { public: - virtual ~ConfigurationHolder() {}; - virtual void UpdateConfiguration(const AppExecFwk::Configuration &config) = 0; - virtual int GetId() = 0; + static int64_t GetNowSysTime(); }; } // namespace AAFwk } // namespace OHOS -#endif // OHOS_AAFWK_CONFIGURATION_HOLDER_H \ No newline at end of file + +#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_SYSTEM_TIME_H \ No newline at end of file diff --git a/services/abilitymgr/include/configuration_distributor.h b/tools/aa/include/test_observer.h similarity index 47% rename from services/abilitymgr/include/configuration_distributor.h rename to tools/aa/include/test_observer.h index 8934b55bee4a3c0871f60ad95be289e7769bf4c2..74866498862ee293c71bada8daa1708fed4c7367 100644 --- a/services/abilitymgr/include/configuration_distributor.h +++ b/tools/aa/include/test_observer.h @@ -12,30 +12,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_AAFWK_CONFIGURATION_DISTRIBUTOR_H -#define OHOS_AAFWK_CONFIGURATION_DISTRIBUTOR_H -#include -#include -#include "configuration_holder.h" -#include "configuration.h" -#include "nocopyable.h" +#ifndef FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_H +#define FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_H + +#include "test_observer_stub.h" namespace OHOS { namespace AAFwk { -class ConfigurationDistributor final : public NoCopyable { +class TestObserver : public TestObserverStub { public: - ConfigurationDistributor(); - ~ConfigurationDistributor(); - void Atach(const std::weak_ptr &ob); - void Detach(const std::weak_ptr &ob); - void UpdateConfiguration(const AppExecFwk::Configuration &newConfig); - void InitConfiguration(const AppExecFwk::Configuration &); + + TestObserver(); + + virtual ~TestObserver() override; + + virtual void TestStatus(const std::string &msg, const int &resultCode) override; + virtual void TestFinished(const std::string &msg, const int &resultCode) override; + virtual ShellCommandResult ExecuteShellCommand( + const std::string &cmd, const int64_t timeoutMs) override; + bool waitForFinish(const int64_t &timeoutMs); + private: - std::list> observerList_; - std::mutex configLock_; - AppExecFwk::Configuration config_; + bool isFinished_; + static constexpr int64_t SHELL_COMMAND_TIMEOUT_MAX = 5000; }; } // namespace AAFwk } // namespace OHOS -#endif // OHOS_AAFWK_CONFIGURATION_DISTRIBUTOR_H \ No newline at end of file + +#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_H \ No newline at end of file diff --git a/tools/aa/include/test_observer_proxy.h b/tools/aa/include/test_observer_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..62be09d3eb0218755c1e20fc48a4602e9489991b --- /dev/null +++ b/tools/aa/include/test_observer_proxy.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_PROXY_H +#define FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_PROXY_H + +#include "itest_observer.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AAFwk { +class TestObserverProxy : public IRemoteProxy { +public: + explicit TestObserverProxy(const sptr &object); + virtual ~TestObserverProxy() override; + virtual void TestStatus(const std::string &msg, const int &resultCode) override; + virtual void TestFinished(const std::string &msg, const int &resultCode) override; + virtual ShellCommandResult ExecuteShellCommand( + const std::string &cmd, const int64_t timeoutMs) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AAFwk +} // namespace OHOS + +#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_PROXY_H \ No newline at end of file diff --git a/tools/aa/include/test_observer_stub.h b/tools/aa/include/test_observer_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..c78333b9624f9c307c82eb33ff001dd03b10bb78 --- /dev/null +++ b/tools/aa/include/test_observer_stub.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_STUB_H +#define FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_STUB_H + +#include "itest_observer.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AAFwk { +class TestObserverStub : public IRemoteStub { +public: + TestObserverStub(); + virtual ~TestObserverStub() override; + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +}; +} // namespace AAFwk +} // namespace OHOS + +#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_AA_INCLUDE_TEST_OBSERVER_STUB_H diff --git a/tools/aa/src/ability_command.cpp b/tools/aa/src/ability_command.cpp index 61b2afeb96df824d433714877c9460dee2ebaf4a..a241a63ec4b8583c91ae3071bc58b8ec76c26319 100644 --- a/tools/aa/src/ability_command.cpp +++ b/tools/aa/src/ability_command.cpp @@ -20,6 +20,7 @@ #include "mission_snapshot.h" #include "hilog_wrapper.h" #include "ohos/aafwk/base/bool_wrapper.h" +#include "test_observer.h" using namespace OHOS::AppExecFwk; @@ -52,6 +53,19 @@ const struct option LONG_OPTIONS_DUMP[] = { {"mission-infos", no_argument, nullptr, 'S'}, {nullptr, 0, nullptr, 0}, }; +const std::string SHORT_OPTIONS_DUMPSYS = "hal::i:e::p::r::u:c"; +const struct option LONG_OPTIONS_DUMPSYS[] = { + {"help", no_argument, nullptr, 'h'}, + {"all", no_argument, nullptr, 'a'}, + {"mission-list", no_argument, nullptr, 'l'}, + {"ability", required_argument, nullptr, 'i'}, + {"extension", no_argument, nullptr, 'e'}, + {"pending", no_argument, nullptr, 'p'}, + {"process", no_argument, nullptr, 'r'}, + {"userId", required_argument, nullptr, 'u'}, + {"client", no_argument, nullptr, 'c'}, + {nullptr, 0, nullptr, 0}, +}; } // namespace AbilityManagerShellCommand::AbilityManagerShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, TOOL_NAME) @@ -69,7 +83,9 @@ ErrCode AbilityManagerShellCommand::CreateCommandMap() {"start", std::bind(&AbilityManagerShellCommand::RunAsStartAbility, this)}, {"stop-service", std::bind(&AbilityManagerShellCommand::RunAsStopService, this)}, {"dump", std::bind(&AbilityManagerShellCommand::RunAsDumpCommand, this)}, + {"dumpsys", std::bind(&AbilityManagerShellCommand::RunAsDumpsysCommand, this)}, {"force-stop", std::bind(&AbilityManagerShellCommand::RunAsForceStop, this)}, + {"test", std::bind(&AbilityManagerShellCommand::RunAsTestCommand, this)}, }; return OHOS::ERR_OK; @@ -361,16 +377,13 @@ ErrCode AbilityManagerShellCommand::RunAsScreenCommand() } if (option == -1) { - if (counter == 1) { - // When scanning the first argument - if (strcmp(argv_[optind], cmd_.c_str()) == 0) { - // 'aa screen' with no option: aa screen - // 'aa screen' with a wrong argument: aa screen xxx - HILOG_INFO("'aa %{public}s' %{public}s", HELP_MSG_NO_OPTION.c_str(), cmd_.c_str()); - - resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); - result = OHOS::ERR_INVALID_VALUE; - } + // When scanning the first argument + if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) { + // 'aa screen' with no option: aa screen + // 'aa screen' with a wrong argument: aa screen xxx + HILOG_INFO("'aa %{public}s' %{public}s", HELP_MSG_NO_OPTION.c_str(), cmd_.c_str()); + resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); + result = OHOS::ERR_INVALID_VALUE; } break; } @@ -533,6 +546,203 @@ ErrCode AbilityManagerShellCommand::RunAsStopService() return result; } +ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() +{ + ErrCode result = OHOS::ERR_OK; + bool isUserID = false; + bool isClient = false; + int userID = DEFAULT_INVAL_VALUE; + bool isfirstCommand = false; + std::string args; + + for (size_t i = 0; i < argList_.size(); i++) { + if (argList_[i] == "-c" || argList_[i] == "--client") { + if (isClient == false) { + isClient = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + + } else if (argList_[i] == "-u" || argList_[i] == "--userId") { + (void)StrToInt(argList_[i + 1], userID); + if (userID == DEFAULT_INVAL_VALUE) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + if (isUserID == false) { + isUserID = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + + } else if (argList_[i] == std::to_string(userID)) { + continue; + } else { + args += argList_[i]; + args += " "; + } + } + + while (true) { + + int option = getopt_long(argc_, argv_, SHORT_OPTIONS_DUMPSYS.c_str(), LONG_OPTIONS_DUMPSYS, nullptr); + + HILOG_INFO("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind); + + if (optind < 0 || optind > argc_) { + resultReceiver_.append(HELP_MSG_DUMPSYS); + return OHOS::ERR_INVALID_VALUE; + } + + if (option == -1) { + break; + } + + switch (option) { + case 'h': { + // 'aa dumpsys -h' + // 'aa dumpsys --help' + resultReceiver_.append(HELP_MSG_DUMPSYS); + result = OHOS::ERR_INVALID_VALUE; + return result; + break; + } + case 'a': { + if (isfirstCommand == false) { + isfirstCommand = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + // 'aa dumpsys -a' + // 'aa dumpsys --all' + break; + } + case 'l': { + if (isfirstCommand == false) { + isfirstCommand = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + // 'aa dumpsys -l' + // 'aa dumpsys --mission-list' + break; + } + case 'i': { + if (isfirstCommand == false) { + isfirstCommand = true; + int abilityRecordId = DEFAULT_INVAL_VALUE; + (void)StrToInt(optarg, abilityRecordId); + if (abilityRecordId == DEFAULT_INVAL_VALUE) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + // 'aa dumpsys -i' + // 'aa dumpsys --ability' + break; + } + case 'e': { + if (isfirstCommand == false) { + isfirstCommand = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + // 'aa dumpsys -e' + // 'aa dumpsys --extension' + break; + } + case 'p': { + if (isfirstCommand == false) { + isfirstCommand = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + // 'aa dumpsys -p' + // 'aa dumpsys --pending' + break; + } + case 'r': { + if (isfirstCommand == false) { + isfirstCommand = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + // 'aa dumpsys -r' + // 'aa dumpsys --process' + break; + } + case 'u': { + // 'aa dumpsys -u' + // 'aa dumpsys --userId' + break; + } + case 'c': { + // 'aa dumpsys -c' + // 'aa dumpsys --client' + break; + } + case '?': { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + break; + } + default: { + if (strcmp(argv_[optind], cmd_.c_str()) == 0) { + // 'aa dumpsys' with no option: aa dumpsys + // 'aa dumpsys' with a wrong argument: aa dumpsys xxx + HILOG_INFO("'aa dumpsys' with no option."); + + resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); + result = OHOS::ERR_INVALID_VALUE; + } + break; + } + } + } + + if (result != OHOS::ERR_OK) { + resultReceiver_.append(HELP_MSG_DUMPSYS); + } else { + if (isfirstCommand != true) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + + std::vector dumpResults; + result = AbilityManagerClient::GetInstance()->DumpSysState(args, dumpResults, isClient, isUserID, userID); + if (result == OHOS::ERR_OK) { + for (auto it : dumpResults) { + resultReceiver_ += it + "\n"; + } + } else { + HILOG_INFO("failed to dump state."); + } + } + return result; +} + ErrCode AbilityManagerShellCommand::RunAsDumpCommand() { ErrCode result = OHOS::ERR_OK; @@ -737,18 +947,16 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want &want, std::string &win } if (option == -1) { - if (counter == 1) { - // When scanning the first argument - if (strcmp(argv_[optind], cmd_.c_str()) == 0) { - // 'aa start' with no option: aa start - // 'aa start' with a wrong argument: aa start xxx - // 'aa stop-service' with no option: aa stop-service - // 'aa stop-service' with a wrong argument: aa stop-service xxx - HILOG_INFO("'aa %{public}s' %{public}s", HELP_MSG_NO_OPTION.c_str(), cmd_.c_str()); + // When scanning the first argument + if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) { + // 'aa start' with no option: aa start + // 'aa start' with a wrong argument: aa start xxx + // 'aa stop-service' with no option: aa stop-service + // 'aa stop-service' with a wrong argument: aa stop-service xxx + HILOG_INFO("'aa %{public}s' %{public}s", HELP_MSG_NO_OPTION.c_str(), cmd_.c_str()); - resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); - result = OHOS::ERR_INVALID_VALUE; - } + resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); + result = OHOS::ERR_INVALID_VALUE; } break; } @@ -934,6 +1142,104 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want &want, std::string &win return result; } +ErrCode AbilityManagerShellCommand::RunAsTestCommand() +{ + HILOG_INFO("enter"); + std::map params; + for (int i = USER_TEST_COMMAND_START_INDEX; i < argc_; i++) { + HILOG_INFO("argv_[%{public}d]: %{public}s", i, argv_[i]); + std::string opt = argv_[i]; + if (opt == "-h" || opt == "--help") { + resultReceiver_.append(HELP_MSG_TEST); + return OHOS::ERR_OK; + } else if (opt == "-p" || opt == "-w") { + if (i >= argc_ - 1) { + return TestCommandError("error: option [" + opt + "] requires a value.\n"); + } + std::string argv = argv_[++i]; + params[opt] = argv; + } else if (opt == "-s") { + if (i >= argc_ - USER_TEST_COMMAND_PARAMS_NUM) { + return TestCommandError( + "error: option Should be [-s unittest ] or [-s class ].\n"); + } + std::string argKey = argv_[++i]; + std::string argValue = argv_[++i]; + if (!(argKey == "unittest" || argKey == "class")) { + return TestCommandError("error: option Should be [-s unittest] or [-s class].\n"); + } + params[opt + " " + argKey] = argValue; + } else if (opt.at(0) == '-') { + return TestCommandError("error: unknown option: " + opt + "\n"); + } + } + + if (!IsTestCommandIntegrity(params)) { + return OHOS::ERR_INVALID_VALUE; + } + + return StartUserTest(params); +} + +bool AbilityManagerShellCommand::IsTestCommandIntegrity(const std::map ¶ms) +{ + HILOG_INFO("enter"); + + std::vector opts = {"-p", "-s unittest", "-s class"}; + for (auto opt : opts) { + auto it = params.find(opt); + if (it == params.end()) { + TestCommandError("error: the option [" + opt + "] is expected.\n"); + return false; + } + } + return true; +} + +ErrCode AbilityManagerShellCommand::TestCommandError(const std::string &info) +{ + resultReceiver_.append(info); + resultReceiver_.append(HELP_MSG_TEST); + return OHOS::ERR_INVALID_VALUE; +} + +ErrCode AbilityManagerShellCommand::StartUserTest(const std::map ¶ms) +{ + HILOG_INFO("enter"); + + Want want; + for (auto param : params) { + want.SetParam(param.first, param.second); + } + + sptr observer = new (std::nothrow) TestObserver(); + if (!observer) { + HILOG_ERROR("Failed: the TestObserver is null"); + return OHOS::ERR_INVALID_VALUE; + } + + int result = AbilityManagerClient::GetInstance()->StartUserTest(want, observer->AsObject()); + if (result != OHOS::ERR_OK) { + HILOG_INFO("%{public}s result = %{public}d", STRING_START_USER_TEST_NG.c_str(), result); + resultReceiver_ = STRING_START_USER_TEST_NG + "\n"; + resultReceiver_.append(GetMessageFromCode(result)); + return result; + } + HILOG_INFO("%{public}s", STRING_START_USER_TEST_OK.c_str()); + + int64_t timeMs = 0; + if (!want.GetStringParam("-w").empty()) { + int time = std::stoi(want.GetStringParam("-w")); + timeMs = time * TIME_RATE_MS; + } + if (!observer->waitForFinish(timeMs)) { + resultReceiver_ = "Timeout: user test is not completed within the specified time.\n"; + return OHOS::ERR_INVALID_VALUE; + } + resultReceiver_ = STRING_START_USER_TEST_OK + "\n"; + + return result; +} } // namespace AAFwk } // namespace OHOS diff --git a/tools/aa/src/shell_command_result.cpp b/tools/aa/src/shell_command_result.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abfc204c3cf275871e6b2e43c2fdbae291c36ae7 --- /dev/null +++ b/tools/aa/src/shell_command_result.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "shell_command_result.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +bool ShellCommandResult::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(exitCode)) { + HILOG_ERROR("Failed to write exitCode"); + return false; + } + + if (!parcel.WriteString(stdResult)) { + HILOG_ERROR("Failed to write stdResult"); + return false; + } + + return true; +} + +bool ShellCommandResult::ReadFromParcel(Parcel &parcel) +{ + exitCode = parcel.ReadInt32(); + stdResult = parcel.ReadString(); + return true; +} + +ShellCommandResult *ShellCommandResult::Unmarshalling(Parcel &parcel) +{ + ShellCommandResult *result = new (std::nothrow) ShellCommandResult(); + if (result && !result->ReadFromParcel(parcel)) { + delete result; + result = nullptr; + } + return result; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/tools/aa/src/system_time.cpp b/tools/aa/src/system_time.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb0f0e20205f887ce7fda2ae9458e9a3bf28c236 --- /dev/null +++ b/tools/aa/src/system_time.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "system_time.h" + +#include "hilog_wrapper.h" +#include "inner_event.h" + +namespace OHOS { +namespace AAFwk { +using namespace OHOS::AppExecFwk; + +int64_t SystemTime::GetNowSysTime() +{ + HILOG_INFO("enter"); + + InnerEvent::TimePoint nowSys = InnerEvent::Clock::now(); + auto epoch = nowSys.time_since_epoch(); + auto value = std::chrono::duration_cast(epoch); + int64_t duration = value.count(); + + return duration; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/tools/aa/src/test_observer.cpp b/tools/aa/src/test_observer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..293d6043cd286a6edb1ec2f165b8a5258f4d8d31 --- /dev/null +++ b/tools/aa/src/test_observer.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_observer.h" + +#include +#include +#include + +#include "hilog_wrapper.h" +#include "system_time.h" + +namespace OHOS { +namespace AAFwk { +TestObserver::TestObserver() + : isFinished_(false) +{} + +TestObserver::~TestObserver() +{} + +void TestObserver::TestStatus(const std::string &msg, const int &resultCode) +{ + HILOG_INFO("enter"); + std::cout << "TestStatus-resultCode: " + std::to_string(resultCode) << std::endl; + std::cout << "TestStatus-resultMsg: " + msg << std::endl; +} + +void TestObserver::TestFinished(const std::string &msg, const int &resultCode) +{ + HILOG_INFO("enter"); + std::cout << "TestFinished-resultCode: " + std::to_string(resultCode) << std::endl; + std::cout << "TestFinished-resultMsg: " + msg << std::endl; + isFinished_ = true; +} + +ShellCommandResult TestObserver::ExecuteShellCommand(const std::string &cmd, const int64_t timeoutMs) +{ + HILOG_INFO("enter"); + ShellCommandResult result; + if (cmd.empty()) { + return result; + } + FILE *file = popen(cmd.c_str(), "r"); + if (!file) { + return result; + } + + int64_t timeout = (timeoutMs <= 0) ? SHELL_COMMAND_TIMEOUT_MAX : timeoutMs; + std::this_thread::sleep_for(std::chrono::microseconds(timeout)); + + char commandResult[1024] = {0}; + while ((fgets(commandResult, sizeof(commandResult), file)) != nullptr) { + result.stdResult.append(commandResult); + std::cout << commandResult; + } + result.exitCode = pclose(file); + file = nullptr; + + return result; +} + +bool TestObserver::waitForFinish(const int64_t &timeoutMs) +{ + HILOG_INFO("enter"); + int64_t startTime = SystemTime::GetNowSysTime(); + while (!isFinished_) { + int64_t nowSysTime = SystemTime::GetNowSysTime(); + if (timeoutMs && (nowSysTime - startTime > timeoutMs)) { + return false; + } + sleep(1); + } + return true; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/tools/aa/src/test_observer_proxy.cpp b/tools/aa/src/test_observer_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc02253e6b2b2b099b6e88341a5646d5dbd99cf2 --- /dev/null +++ b/tools/aa/src/test_observer_proxy.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_observer_proxy.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +TestObserverProxy::TestObserverProxy(const sptr &object) : IRemoteProxy(object) +{ + HILOG_INFO("test observer proxy instance is created"); +} + +TestObserverProxy::~TestObserverProxy() +{ + HILOG_INFO("test observer proxy is destoryed"); +} + +void TestObserverProxy::TestStatus(const std::string &msg, const int &resultCode) +{ + HILOG_INFO("start"); + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + + sptr remote = Remote(); + if (remote == nullptr) { + HILOG_ERROR("Failed to send cmd to service due to remote objetc is null"); + return; + } + + if (!data.WriteString(msg)) { + HILOG_ERROR("Failed to write string msg"); + return; + } + + if (!data.WriteInt32(resultCode)) { + HILOG_ERROR("Failed to write resultCode"); + return; + } + + int32_t result = remote->SendRequest( + static_cast(ITestObserver::Message::AA_TEST_STATUS), data, reply, option); + if (result != OHOS::NO_ERROR) { + HILOG_ERROR("Failed to SendRequest, error code: %{public}d", result); + return; + } +} + +void TestObserverProxy::TestFinished(const std::string &msg, const int &resultCode) +{ + HILOG_INFO("start"); + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + + sptr remote = Remote(); + if (remote == nullptr) { + HILOG_ERROR("Failed to send cmd to service due to remote objetc is null"); + return; + } + + if (!data.WriteString(msg)) { + HILOG_ERROR("Failed to write string msg"); + return; + } + + if (!data.WriteInt32(resultCode)) { + HILOG_ERROR("Failed to write resultCode"); + return; + } + + int32_t result = remote->SendRequest( + static_cast(ITestObserver::Message::AA_TEST_FINISHED), data, reply, option); + if (result != OHOS::NO_ERROR) { + HILOG_ERROR("Failed to SendRequest, error code: %{public}d", result); + return; + } +} + +ShellCommandResult TestObserverProxy::ExecuteShellCommand( + const std::string &cmd, const int64_t timeoutMs) +{ + HILOG_INFO("start"); + + ShellCommandResult result; + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + + sptr remote = Remote(); + if (remote == nullptr) { + HILOG_ERROR("Failed to send cmd to service due to remote objetc is null"); + return result; + } + + if (!data.WriteString(cmd)) { + HILOG_ERROR("Failed to write string cmd"); + return result; + } + + if (!data.WriteInt64(timeoutMs)) { + HILOG_ERROR("Failed to write timeoutMs"); + return result; + } + + int32_t ret = remote->SendRequest( + static_cast(ITestObserver::Message::AA_EXECUTE_SHELL_COMMAND), data, reply, option); + if (ret != OHOS::NO_ERROR) { + HILOG_ERROR("Failed to SendRequest, error code: %{public}d", ret); + return result; + } + ShellCommandResult *resultPtr = reply.ReadParcelable(); + if (!resultPtr) { + HILOG_ERROR("Failed to read result"); + return result; + } + result = *resultPtr; + return result; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/tools/aa/src/test_observer_stub.cpp b/tools/aa/src/test_observer_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d338f2d4f1b6b5b2353a9874ce81b67e4dec108 --- /dev/null +++ b/tools/aa/src/test_observer_stub.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "test_observer_stub.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +TestObserverStub::TestObserverStub() +{ + HILOG_INFO("test observer stub instance is created"); +} + +TestObserverStub::~TestObserverStub() +{ + HILOG_INFO("test observer stub instance is destroyed"); +} + +int TestObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + switch (code) { + case static_cast(ITestObserver::Message::AA_TEST_STATUS): { + std::string msg = data.ReadString(); + int resultCode = data.ReadInt32(); + TestStatus(msg, resultCode); + break; + } + case static_cast(ITestObserver::Message::AA_TEST_FINISHED): { + std::string msg = data.ReadString(); + int resultCode = data.ReadInt32(); + TestFinished(msg, resultCode); + break; + } + case static_cast(ITestObserver::Message::AA_EXECUTE_SHELL_COMMAND): { + std::string cmd = data.ReadString(); + int64_t timeoutMs = data.ReadInt64(); + ShellCommandResult result = ExecuteShellCommand(cmd, timeoutMs); + if (!reply.WriteParcelable(&result)) { + HILOG_ERROR("Failed to write reply ShellCommandResult!"); + return ERR_INVALID_VALUE; + } + break; + } + default: + HILOG_WARN("event receive stub receives unknown code, code = %{public}u", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + + return NO_ERROR; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/tools/bundle.json b/tools/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..c3a7268820138a4ebc32632ef81b227c0e90c709 --- /dev/null +++ b/tools/bundle.json @@ -0,0 +1,44 @@ +{ + "name": "@ohos/ability_tools", + "description": "元能力命令行工具 : 提供命令行中启动Ability, 打印Aility栈信息的能力", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "foundation/aafwk/standard/tools" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "ability_tools", + "subsystem": "aafwk", + "syscap": [], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "100KB", + "ram": "100KB", + "deps": { + "components": [ + "ability_runtime", + "hiviewdfx_hilog_native", + "ipc", + "samgr_standard", + "utils_base" + ], + "third_party": [] + }, + "build": { + "sub_component": [ + "//foundation/aafwk/standard/tools:tools_target" + ], + "inner_kits": [], + "test": [ + "//foundation/aafwk/standard/tools/test:moduletest", + "//foundation/aafwk/standard/tools/test:systemtest", + "//foundation/aafwk/standard/tools/test:unittest" + ] + } + } +} \ No newline at end of file diff --git a/tools/fm/BUILD.gn b/tools/fm/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..b538835ec62d1a39e99541c49f2f06772e301be1 --- /dev/null +++ b/tools/fm/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("tools_fm_config") { + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/want/include", + "${aafwk_path}/interfaces/innerkits/base/include", + "${aafwk_path}/services/common/include", + "${aafwk_path}/tools/aa/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "include", + ] +} + +ohos_source_set("tools_fm_source_set") { + sources = [ + "${aafwk_path}/tools/aa/src/shell_command.cpp", + "src/fms_command.cpp", + "src/main.cpp", + ] + + defines = [ + "APP_LOG_TAG = \"FmsTool\"", + "LOG_DOMAIN = 0xD001152", + ] + + public_configs = [ ":tools_fm_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/form_manager:form_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_executable("fm") { + deps = [ ":tools_fm_source_set" ] + + install_enable = true + + subsystem_name = "aafwk" + part_name = "ability_tools" +} + +group("tools_fm") { + deps = [ ":fm" ] +} diff --git a/tools/fm/include/fms_command.h b/tools/fm/include/fms_command.h new file mode 100755 index 0000000000000000000000000000000000000000..e6efe82372aac5dcf1d94d0b5b1a499dc58198a6 --- /dev/null +++ b/tools/fm/include/fms_command.h @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H +#define FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H + +#include "shell_command.h" +#include "form_mgr_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string FM_TOOL_NAME = "fm"; + +const std::string FM_HELP_MSG = "usage: fm \n" + "These are common fm commands list:\n" + " help list available commands\n" + " query query form info with options\n"; + +const std::string HELP_MSG_QUERY = + "usage: fm query \n" + "options list:\n" + " -h, --help list available commands\n" + " -s, --storage query form storage info\n" + " -n query form info by a bundle name\n" + " -i query form info by a form id\n"; + + +const std::string HELP_MSG_NO_BUNDLE_PATH_OPTION = + "error: you must specify a form id with '-1' or '--formid'."; + +const std::string HELP_MSG_NO_BUNDLE_NAME_OPTION = + "error: you must specify a bundle name with '-n' or '--name'."; + +const std::string STRING_QUERY_FORM_INFO_OK = "query form info successfully."; +const std::string STRING_QUERY_FORM_INFO_NG = "error: failed to query form info."; +} // namespace + +class FormMgrShellCommand : public OHOS::AAFwk::ShellCommand { +public: + FormMgrShellCommand(int argc, char *argv[]); + ~FormMgrShellCommand() override + {} + +private: + /** + * @brief Create command map. + */ + ErrCode CreateCommandMap() override; + /** + * @brief Create message map. + */ + ErrCode CreateMessageMap() override; + /** + * @brief init. + */ + ErrCode init() override; + /** + * @brief Run help command. + */ + ErrCode RunAsHelpCommand(); + /** + * @brief Run query form info command. + */ + ErrCode RunAsQueryCommand(); + // ErrCode RunAsDumpCommand(); + + /** + * @brief Query all of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t QueryStorageFormInfos(); + /** + * @brief Query form infos by bundleName. + * @param bundleName BundleName. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t QueryFormInfoByBundleName(const std::string& bundleName); + /** + * @brief Query form infos by form id. + * @param formId The id of the form. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t QueryFormInfoByFormId(const std::int64_t formId); + /** + * @brief Handle command args. + * @param optopt Command optopt. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleUnknownOption(const char optopt); + /** + * @brief Handle command args. + * @param option Command option. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleNormalOption(const int option, std::string &bundleName, int64_t &formId, int32_t &cmdFlag); + + /** + * @brief Execute query form info command. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t ExecuteQuery(const std::string &bundleName, const int64_t formId, const int32_t cmdFlag); + + /** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t ConnectFms(); + + bool WriteInterfaceToken(MessageParcel &data); + int GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo); + int SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply); +private: + sptr remoteObject_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H \ No newline at end of file diff --git a/tools/fm/src/fms_command.cpp b/tools/fm/src/fms_command.cpp new file mode 100755 index 0000000000000000000000000000000000000000..c7b914c7fb56ad2a6a17568eb6b3ffbc02c44437 --- /dev/null +++ b/tools/fm/src/fms_command.cpp @@ -0,0 +1,499 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include + +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "fms_command.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +using namespace OHOS::AAFwk; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int COMMAND_QUERY_INVALID = -1; +const int COMMAND_QUERY_STORAGE = 0; +const int COMMAND_QUERY_NAME = 1; +const int COMMAND_QUERY_ID = 2; + +// const std::string BUNDLE_NAME_EMPTY = ""; + +const std::string SHORT_OPTIONS = "hsn:i:"; +const struct option LONG_OPTIONS[] = { + {"help", no_argument, nullptr, 'h'}, + {"storage", no_argument, nullptr, 's'}, + {"bundle-name", required_argument, nullptr, 'n'}, + {"form-id", required_argument, nullptr, 'i'}, + {0, 0, 0, 0}, +}; +} // namespace + +FormMgrShellCommand::FormMgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, FM_TOOL_NAME) +{ +} +ErrCode FormMgrShellCommand::init() +{ + return ERR_OK; +} +/** + * @brief Create command map. + */ +ErrCode FormMgrShellCommand::CreateCommandMap() +{ + commandMap_ = { + {"help", std::bind(&FormMgrShellCommand::RunAsHelpCommand, this)}, + {"query", std::bind(&FormMgrShellCommand::RunAsQueryCommand, this)}, + // {"dump", std::bind(&FormMgrShellCommand::RunAsDumpCommand, this)}, + }; + + return OHOS::ERR_OK; +} +/** + * @brief Create message map. + */ +ErrCode FormMgrShellCommand::CreateMessageMap() +{ + messageMap_ = { + // error + message + { + ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR, + "error: fm query internal error.", + }, + { + ERR_APPEXECFWK_FORM_INVALID_PARAM, + "error: fm query param error.", + }, + { + ERR_APPEXECFWK_FORM_PERMISSION_DENY, + "error: fm query permission denied.", + }, + { + ERR_APPEXECFWK_FORM_NOT_EXIST_ID, + "warning: fm query no form info.", + }, + { + ERR_APPEXECFWK_FORM_COMMON_CODE, + "error: unknown.", + }, + }; + + return OHOS::ERR_OK; +} +/** + * @brief Run help command. + */ +ErrCode FormMgrShellCommand::RunAsHelpCommand() +{ + resultReceiver_.append(FM_HELP_MSG); + + return OHOS::ERR_OK; +} +/** + * @brief Run query form info command. + */ +ErrCode FormMgrShellCommand::RunAsQueryCommand() +{ + int32_t result = OHOS::ERR_OK; + int32_t cmdFlag = COMMAND_QUERY_INVALID; + int option = -1; + int counter = 0; + std::string bundleName = ""; + int64_t formId = 0; + + while (true) { + counter++; + option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr); + APP_LOGI("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind); + if (optind < 0 || optind > argc_) { + return OHOS::ERR_INVALID_VALUE; + } + + for (int i = 0; i < argc_; i++) { + APP_LOGI("argv_[%{public}d]: %{public}s", i, argv_[i]); + } + + if (option == -1) { + if (counter == 1) { + // When scanning the first argument + if (strcmp(argv_[optind], cmd_.c_str()) == 0) { + // 'fm query' with no option: fm query + // 'fm query' with a wrong argument: fm query xxx + APP_LOGE("'fm query' with no option."); + resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); + result = OHOS::ERR_INVALID_VALUE; + } + } + break; + } + + if (option == '?') { + result = HandleUnknownOption(optopt); + break; + } + + result = HandleNormalOption(option, bundleName, formId, cmdFlag); + // if (result == OHOS::ERR_OK) { + // break; + // } + } + + if (result == OHOS::ERR_OK) { + result = ExecuteQuery(bundleName, formId, cmdFlag); + } else { + resultReceiver_.append(HELP_MSG_QUERY); + } + + return result; +} +/** + * @brief Handle command args. + * @param optopt Command optopt. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::HandleUnknownOption(const char optopt) +{ + int32_t result = OHOS::ERR_OK; + switch (optopt) { + case 'n': + case 'i': { + // 'fm query -n' with no argument: fm query -n + // 'fm query --bundle-name' with no argument: fm query --bundle-name + // 'fm query -i' with no argument: fm query -i + // 'fm query --form-id' with no argument: fm query --form-id + APP_LOGE("'fm query' %{public}s with no argument.", argv_[optind - 1]); + resultReceiver_.append("error: option '"); + resultReceiver_.append(argv_[optind - 1]); + resultReceiver_.append("' requires a value.\n"); + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 0: { + // 'fm query' with a unknown option: fm query --x + // 'fm query' with a unknown option: fm query --xxx + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + APP_LOGE("'fm query' with a unknown option: %{public}s", unknownOption.c_str()); + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + default: { + // 'fm query' with a unknown option: fm query -x + // 'fm query' with a unknown option: fm query -xxx + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + APP_LOGE("'fm query' with a unknown option: %{public}s", unknownOption.c_str()); + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + } + + return result; +} +/** + * @brief Handle command args. + * @param option Command option. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::HandleNormalOption(const int option, std::string &bundleName, int64_t &formId, int32_t &cmdFlag) +{ + APP_LOGI("%{public}s start, option: %{public}d", __func__, option); + int32_t result = OHOS::ERR_OK; + switch (option) { + case 'h': { + // 'fm query -h' + // 'fm query --help' + APP_LOGI("'fm query' %{public}s", argv_[optind - 1]); + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 's': { + // 'fm query -s' + // 'fm query --storage' + cmdFlag = COMMAND_QUERY_STORAGE; + break; + } + case 'n': { + // 'fm query -n ' + // 'fm query --bundle-name ' + if (optarg == nullptr) { + resultReceiver_.append("error: option "); + resultReceiver_.append("'-n'"); + resultReceiver_.append(" requires a value.\n"); + result = OHOS::ERR_INVALID_VALUE; + break; + } + cmdFlag = COMMAND_QUERY_NAME; + bundleName = optarg; + break; + } + case 'i': { + // 'fm query -i ' + // 'fm query --form-id ' + if (optarg == nullptr) { + resultReceiver_.append("error: option "); + resultReceiver_.append("'-i'"); + resultReceiver_.append(" requires a value.\n"); + result = OHOS::ERR_INVALID_VALUE; + break; + } + cmdFlag = COMMAND_QUERY_ID; + formId = std::stoll(optarg); + break; + } + default: { + result = OHOS::ERR_INVALID_VALUE; + APP_LOGI("'fm query' invalid option."); + break; + } + } + APP_LOGI("%{public}s end, result: %{public}d", __func__, result); + return result; +} +/** + * @brief Execute query form info command. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::ExecuteQuery(const std::string &bundleName, const int64_t formId, const int32_t cmdFlag) +{ + APP_LOGI("%{public}s start, bundleName: %{public}s, formId:%{public}" PRId64 "", __func__, bundleName.c_str(), formId); + int32_t result = OHOS::ERR_OK; + switch (cmdFlag) { + case COMMAND_QUERY_STORAGE: { + result = QueryStorageFormInfos(); + break; + } + case COMMAND_QUERY_NAME: { + result = QueryFormInfoByBundleName(bundleName); + break; + } + case COMMAND_QUERY_ID: { + result = QueryFormInfoByFormId(formId); + break; + } + default: { + APP_LOGI("'fm query' invalid command."); + break; + } + APP_LOGI("%{public}s end, cmdFlag: %{public}d", __func__, cmdFlag); + } + + if (result == OHOS::ERR_OK) { + resultReceiver_ = STRING_QUERY_FORM_INFO_OK + "\n" + resultReceiver_; + } else if (result == OHOS::ERR_APPEXECFWK_FORM_NOT_EXIST_ID) { + resultReceiver_ = STRING_QUERY_FORM_INFO_OK + "\n"; + resultReceiver_.append(GetMessageFromCode(result)); + } else { + resultReceiver_ = STRING_QUERY_FORM_INFO_NG + "\n"; + resultReceiver_.append(GetMessageFromCode(result)); + } + + return result; +} +/** + * @brief Query all of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::QueryStorageFormInfos() +{ + APP_LOGI("%{public}s start", __func__); + + int errCode = ConnectFms(); + if (errCode != OHOS::ERR_OK) { + return errCode; + } + + std::string formInfos; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int result = GetStringInfo(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS, data, formInfos); + if (result == ERR_OK) { + resultReceiver_= formInfos; + } else { + APP_LOGE("'fm query' failed to query form info."); + } + APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); + + return result; +} +/** + * @brief Query form infos by bundleName. + * @param bundleName BundleName. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::QueryFormInfoByBundleName(const std::string& bundleName) +{ + APP_LOGI("%{public}s start, bundleName: %{public}s", __func__, bundleName.c_str()); + + int errCode = ConnectFms(); + if (errCode != OHOS::ERR_OK) { + return errCode; + } + + std::string formInfos; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int result = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME, data, formInfos); + if (result == ERR_OK) { + APP_LOGI("%{public}s, DumpFormInfoByBundleName success", __func__); + resultReceiver_ = formInfos; + } else { + APP_LOGE("'fm query' failed to query form info."); + } + APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); + + return result; +} +/** + * @brief Query form infos by form id. + * @param formId The id of the form. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::QueryFormInfoByFormId(const std::int64_t formId) +{ + APP_LOGI("%{public}s start, formId: %{public}" PRId64 "", __func__, formId); + + int errCode = ConnectFms(); + if (errCode != OHOS::ERR_OK) { + return errCode; + } + + std::string formInfo; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int result = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo); + if (result == ERR_OK) { + resultReceiver_ = formInfo; + } else if (result == OHOS::ERR_APPEXECFWK_FORM_NOT_EXIST_ID) { + APP_LOGW("'fm query' no form info."); + } else { + APP_LOGE("'fm query' failed to query form info."); + } + APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); + + return result; +} +bool FormMgrShellCommand::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(IFormMgr::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +int FormMgrShellCommand::GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to read reply result: %{public}d", __func__, error); + return error; + } + std::vector stringInfoList; + if (!reply.ReadStringVector(&stringInfoList)) { + APP_LOGE("%{public}s, failed to read string vector from reply", __func__); + return false; + } + if (stringInfoList.empty()) { + APP_LOGI("%{public}s, No string info", __func__); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + for (auto &info : stringInfoList) { + stringInfo += info; + } + APP_LOGD("%{public}s, get string info success", __func__); + return ERR_OK; +} +int FormMgrShellCommand::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + MessageOption option(MessageOption::TF_SYNC); + + if (!remoteObject_) { + APP_LOGE("%{public}s, failed to get remote object, cmd: %{public}d", __func__, code); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + int32_t result = remoteObject_->SendRequest(static_cast(code), data, reply, option); + if (result != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code); + return result; + } + return ERR_OK; +} +/** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::ConnectFms() +{ + if (remoteObject_ != nullptr) { + return OHOS::ERR_OK; + } + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + APP_LOGE("%{private}s:fail to get system ability manager", __func__); + return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; + } + remoteObject_ = systemManager->GetSystemAbility(FORM_MGR_SERVICE_ID); + if (remoteObject_ == nullptr) { + APP_LOGE("%{private}s:fail to connect FormMgrService", __func__); + return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; + } + + APP_LOGI("%{public}s end, get fms proxy success", __func__); + return OHOS::ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/tools/fm/src/main.cpp b/tools/fm/src/main.cpp new file mode 100755 index 0000000000000000000000000000000000000000..7b2115dbeb15dcef0e3e4d24350e40a4c1086b44 --- /dev/null +++ b/tools/fm/src/main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 "fms_command.h" + +int main(int argc, char *argv[]) +{ + OHOS::AppExecFwk::FormMgrShellCommand cmd(argc, argv); + std::cout << cmd.ExecCommand(); + return 0; +} diff --git a/tools/test/mock/mock_ability_manager_stub.cpp b/tools/test/mock/mock_ability_manager_stub.cpp index b72aa78678b7312985c1128ff55fe96e2c6736e5..03583d81739c4d1a9398feba76d19822c28642a6 100644 --- a/tools/test/mock/mock_ability_manager_stub.cpp +++ b/tools/test/mock/mock_ability_manager_stub.cpp @@ -18,7 +18,7 @@ using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; -int MockAbilityManagerStub::StartAbility(const Want &want, int requestCode) +int MockAbilityManagerStub::StartAbility(const Want &want, int32_t userId, int requestCode) { HILOG_INFO("[%{public}s(%{public}s)] enter", __FILE__, __FUNCTION__); @@ -63,7 +63,7 @@ void MockAbilityManagerStub::DumpState(const std::string &args, std::vector &callerToken, int requestCode)); + MOCK_METHOD4(StartAbility, int(const Want &want, const sptr &callerToken, + int32_t userId, int requestCode)); MOCK_METHOD3(TerminateAbility, int(const sptr &token, int resultCode, const Want *resultWant)); MOCK_METHOD1(MinimizeAbility, int(const sptr &token)); - MOCK_METHOD3(ConnectAbility, - int(const Want &want, const sptr &connect, const sptr &callerToken)); + MOCK_METHOD4(ConnectAbility, int(const Want &want, const sptr &connect, + const sptr &callerToken, int32_t userId)); MOCK_METHOD1(DisconnectAbility, int(const sptr &connect)); MOCK_METHOD3(AcquireDataAbility, sptr(const Uri &uri, bool tryBind, const sptr &callerToken)); @@ -65,7 +66,7 @@ public: MOCK_METHOD2(TerminateAbilityResult, int(const sptr &token, int startId)); - int StopServiceAbility(const Want &want); + int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE); MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); @@ -100,8 +101,8 @@ public: MOCK_METHOD2(SetMissionDescriptionInfo, int(const sptr &token, const MissionDescriptionInfo &info)); MOCK_METHOD0(GetMissionLockModeState, int()); MOCK_METHOD1(UpdateConfiguration, int(const AppExecFwk::Configuration &)); - MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, - const sptr &callerToken, int requestCode)); + MOCK_METHOD5(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int32_t userId, int requestCode)); MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); MOCK_METHOD2(MoveMissionToSplitScreenStack, int(const MissionOption &primary, const MissionOption &secondary)); MOCK_METHOD2( @@ -131,9 +132,25 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); + + virtual int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int StartUser(int userId) override { return 0; @@ -161,10 +178,72 @@ public: { return 0; } + + virtual int StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) + { + return 0; + } + virtual int ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) + { + return 0; + } + + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + virtual bool SendANRProcessID(int pid) + { + return true; + } + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + virtual bool IsRunningInStabilityTest() override + { + return true; + } + virtual void DumpSysState( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int UserID) override + {} + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, + const std::string &bundleName, const sptr &observer) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } + public: std::string powerState_; }; - } // namespace AAFwk } // namespace OHOS diff --git a/tools/test/moduletest/aa/BUILD.gn b/tools/test/moduletest/aa/BUILD.gn index 3061a85fb3871a7f3d0336b1ae2e74dd266cb9e9..3042dc184f26037dff7c1947e35f538215ae46c0 100644 --- a/tools/test/moduletest/aa/BUILD.gn +++ b/tools/test/moduletest/aa/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/tools" +module_output_path = "ability_tools/tools" config("tools_aa_config_mock") { include_dirs = [ @@ -46,7 +46,7 @@ ohos_moduletest("aa_command_start_module_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -72,7 +72,7 @@ ohos_moduletest("aa_command_stop_service_module_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -98,7 +98,7 @@ ohos_moduletest("aa_command_dump_module_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/tools/test/systemtest/aa/BUILD.gn b/tools/test/systemtest/aa/BUILD.gn index 1da41815e85567095136959f8a16d4d2c961c71d..9745608585ebf6b00101f7a1f8ba670655d12a63 100644 --- a/tools/test/systemtest/aa/BUILD.gn +++ b/tools/test/systemtest/aa/BUILD.gn @@ -14,7 +14,18 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/tools" +module_output_path = "ability_tools/tools" + +config("tools_aa_test_config") { + include_dirs = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/include", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "${appexecfwk_path}/tools/bm/include", + "//utils/system/safwk/native/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//base/security/appverify/interfaces/innerkits/appverify/include", + ] +} ohos_systemtest("aa_command_start_system_test") { module_out_path = module_output_path @@ -26,7 +37,7 @@ ohos_systemtest("aa_command_start_system_test") { "tool_system_test.cpp", ] - configs = [ "${appexecfwk_path}/tools/bm:tools_bm_config" ] + configs = [ ":tools_aa_test_config" ] cflags = [] if (target_cpu == "arm") { @@ -40,7 +51,7 @@ ohos_systemtest("aa_command_start_system_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -54,7 +65,7 @@ ohos_systemtest("aa_command_stop_service_system_test") { "tool_system_test.cpp", ] - configs = [ "${appexecfwk_path}/tools/bm:tools_bm_config" ] + configs = [ ":tools_aa_test_config" ] cflags = [] if (target_cpu == "arm") { @@ -68,7 +79,7 @@ ohos_systemtest("aa_command_stop_service_system_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -84,7 +95,7 @@ ohos_systemtest("aa_command_dump_system_test") { "tool_system_test.cpp", ] - configs = [ "${appexecfwk_path}/tools/bm:tools_bm_config" ] + configs = [ ":tools_aa_test_config" ] cflags = [] if (target_cpu == "arm") { @@ -98,7 +109,7 @@ ohos_systemtest("aa_command_dump_system_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/tools/test/unittest/aa/BUILD.gn b/tools/test/unittest/aa/BUILD.gn index 7db74972838ab65e9f8173cfdff9ab3d05168c8c..d2e66aed3d54728c1b874085358ef9e4aeeef20f 100644 --- a/tools/test/unittest/aa/BUILD.gn +++ b/tools/test/unittest/aa/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "aafwk_standard/tools" +module_output_path = "ability_tools/tools" config("tools_aa_config_mock") { include_dirs = [ @@ -46,7 +46,7 @@ ohos_unittest("aa_command_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -72,7 +72,7 @@ ohos_unittest("aa_command_start_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -98,7 +98,7 @@ ohos_unittest("aa_command_stop_service_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -124,7 +124,7 @@ ohos_unittest("aa_command_dump_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -150,7 +150,7 @@ ohos_unittest("aa_command_screen_test") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/tools/test/unittest/aa/aa_command_screen_test.cpp b/tools/test/unittest/aa/aa_command_screen_test.cpp index 7ed8775cde1d62674fa8b8c4e44c2f28b69ad1a7..683addbb9b4f4a6957e64c3cbcbef8e26815f194 100644 --- a/tools/test/unittest/aa/aa_command_screen_test.cpp +++ b/tools/test/unittest/aa/aa_command_screen_test.cpp @@ -197,7 +197,7 @@ HWTEST_F(AaCommandScreenTest, Aa_Command_Screen_0700, Function | MediumTest | Le int argc = sizeof(argv) / sizeof(argv[0]) - 1; AbilityManagerShellCommand cmd(argc, argv); - EXPECT_EQ(cmd.ExecCommand(), HELP_MSG_SCREEN); + EXPECT_EQ(cmd.ExecCommand(), "error: unknown option.\n" + HELP_MSG_SCREEN); } /** diff --git a/tools/zip/include/checked_cast.h b/tools/zip/include/checked_cast.h deleted file mode 100644 index 76e1cc60eed79e365c896048abafd255910f9db9..0000000000000000000000000000000000000000 --- a/tools/zip/include/checked_cast.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_CHECKED_CAST_H -#define FOUNDATION_AAFWK_STANDARD_TOOLS_CHECKED_CAST_H - -#include -#include -#include -#include "hilog_wrapper.h" - -namespace hidden { -// workaroud for T& equally matching f(T&) and f(T const&) -// so we do the following: T const& never matches f(T&), therefore: -// f(T&, LookUpHelper2 const&) and f(T const&, LookUpHelper const&) -// f(T&, LookUpHelper2 const&) does match both but f(T&, LookUpHelper2 const&) is a -// perfect match (no upcast for LookUpHelper needed) - -struct LookUpHelper {}; -struct LookUpHelper2 : public hidden::LookUpHelper {}; - -// IsPtr - partial specialization only -template -struct IsPtr { - enum { value = false }; -}; -template -struct IsPtr { - enum { value = true }; -}; -} // namespace hidden - -// bad_checked_cast is thrown if cast is bad -// see boost::lexical_cast -class bad_checked_cast : std::bad_cast { -public: - bad_checked_cast() : from(0), to(0) - {} - - bad_checked_cast(std::type_info const &from, std::type_info const &to) : from(&from), to(&to) - {} - virtual ~bad_checked_cast() - {} - std::type_info const &source_type() const - { - return *from; - } - - std::type_info const &target_type() const - { - return *to; - } - - char const *what() const throw() - { - return "bad checked cast: source is not a target type"; - } - -private: - std::type_info const *from; - std::type_info const *to; -}; -#ifdef CHECKED_CAST_DO_ASSERT -#define BAD_CHECKED_CAST(from, to) assert(false) -#else -#define BAD_CHECKED_CAST(from, to) -#endif - -// implementation -namespace hidden { -template -struct checked_cast_impl; - -// pointer variant -template -struct checked_cast_impl { - static T cast(X &x, hidden::LookUpHelper2 const &) - { -#ifdef CHECKED_CAST_SAFE_CONVERSATION - T t = dynamic_cast(x); - // check cross cast - if (t != static_cast(x)) { - BAD_CHECKED_CAST(x, T); - } - return t; -#else - return static_cast(x); -#endif - } - - static T cast(X const &x, hidden::LookUpHelper const &) - { -#ifdef CHECKED_CAST_SAFE_CONVERSATION - T t = dynamic_cast(x); - - // check cross cast - if (t != static_cast(x)) { - BAD_CHECKED_CAST(x, T); - } - return t; -#else - return static_cast(x); -#endif - } -}; - -template -struct checked_cast_impl { - static T cast(X &x, hidden::LookUpHelper2 const &) - { -#ifdef CHECKED_CAST_SAFE_CONVERSATION - T t = dynamic_cast(x); - // check cross cast - if (&t != &static_cast(x)) { - HILOG_ERROR("!!!bad cast!!!"); - } - return t; -#else - return static_cast(x); -#endif - } - - static T cast(X const &x, hidden::LookUpHelper const &) - { -#ifdef CHECKED_CAST_SAFE_CONVERSATION - T t = dynamic_cast(x); - // check cross cast - if (&t != &static_cast(x)) { - std::bad_cast(); - } - return t; -#else - return static_cast(x); -#endif - } -}; - -} // namespace hidden - -template -inline T checked_cast(X &x) -{ - return hidden::checked_cast_impl::value>::cast(x, hidden::LookUpHelper2()); -} -template -inline T checked_cast(X const &x) -{ - return hidden::checked_cast_impl::value>::cast(x, hidden::LookUpHelper2()); -} - -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_CHECKED_CAST_H diff --git a/tools/zip/include/file_path.h b/tools/zip/include/file_path.h deleted file mode 100644 index 6019be5c24a05bbb96957df284cd8ffc1db2ed53..0000000000000000000000000000000000000000 --- a/tools/zip/include/file_path.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_FILE_PATH_H -#define FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_FILE_PATH_H -#include -#include -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -#define FILE_PATH_LITERAL(x) x -#define PRFilePath "s" - -template -char (&ArraySizeHelper(T (&array)[N]))[N]; -#define arraysize(array) (sizeof(ArraySizeHelper(array))) - -class FilePath { -public: - using CharType = std::string::value_type; - - FilePath(); - FilePath(const FilePath &that); - explicit FilePath(const std::string &path); - ~FilePath(); - FilePath &operator=(const FilePath &that); - bool operator==(const FilePath &that) const; - bool operator!=(const FilePath &that) const; - bool operator<(const FilePath &that) const; - - static const CharType kSeparators[]; - static const size_t kSeparatorsLength; - static const CharType kCurrentDirectory[]; - static const CharType kParentDirectory[]; - static const CharType kExtensionSeparator; - - static FilePath FromUTF8Unsafe(const std::string &utf8); - static bool IsSeparator(CharType character); - static bool CreateDirectory(const FilePath &fullPath); - static bool DirectoryExists(const FilePath &path); - static bool PathIsValid(const FilePath &path); - - // Returns a FilePath by appending a separator and the supplied path - // component to this object's path. Append takes care to avoid adding - // excessive separators if this object's path already ends with a separator. - // If this object's path is kCurrentDirectory, a new FilePath corresponding - // only to |component| is returned. |component| must be a relative path; - // it is an error to pass an absolute path. - FilePath Append(const std::string &component); - FilePath Append(FilePath &component); - // If IsParent(child) holds, appends to path (if non-NULL) the - // relative path to child and returns true. - bool AppendRelativePath(const FilePath &child, FilePath *path); - - bool ReferencesParent(); - void GetComponents(std::vector &components); - FilePath DirName(); - FilePath BaseName(); - bool IsAbsolute(); - std::string Value(); - -private: - std::string path_; - - void StripTrailingSeparatorsInternal(); - bool AreAllSeparators(const std::string &input); -}; -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS - -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_FILE_PATH_H diff --git a/tools/zip/include/zip.h b/tools/zip/include/zip.h deleted file mode 100644 index c741542ffa40c02e1e04492e02bb0cb89f9cccec..0000000000000000000000000000000000000000 --- a/tools/zip/include/zip.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_H -#define FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_H - -#include -#include -#include -#include -#include -#include "zip_utils.h" -#include "file_path.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -class WriterDelegate; -// Abstraction for file access operation required by Zip(). -// Can be passed to the ZipParams for providing custom access to the files, -// for example over IPC. -// If none is provided, the files are accessed directly. -// All parameters paths are expected to be absolute. -class FileAccessor { -public: - virtual ~FileAccessor() = default; - - struct DirectoryContentEntry { - DirectoryContentEntry(const FilePath &path, bool directory) : path(path), isDirectory(directory) - {} - FilePath path; - bool isDirectory = false; - }; -}; - -class ZipParams { -public: - ZipParams(const FilePath &srcDir, const FilePath &destFile); - - // Does not take ownership of |destFd|. - ZipParams(const FilePath &srcDir, int destFd); - virtual ~ZipParams() - {} - int DestFd() const - { - return destFd_; - } - - const FilePath &SrcDir() const - { - return srcDir_; - } - - const FilePath &DestFile() const - { - return destFile_; - } - - // Restricts the files actually zipped to the paths listed in - // |srcRelativePaths|. They must be relative to the |srcDir| passed in the - // constructor and will be used as the file names in the created zip file. All - // source paths must be under |srcDir| in the file system hierarchy. - void SetFilesTozip(const std::vector &srcRelativePaths) - { - srcFiles_ = srcRelativePaths; - } - const std::vector &GetFilesTozip() const - { - return srcFiles_; - } - - using FilterCallback = std::function; - void SetFilterCallback(FilterCallback filterCallback) - { - filterCallback_ = filterCallback; - } - const FilterCallback &GetFilterCallback() const - { - return filterCallback_; - } - - void SetIncludeHiddenFiles(bool includeHiddenFiles) - { - includeHiddenFiles_ = includeHiddenFiles; - } - bool GetIncludeHiddenFiles() const - { - return includeHiddenFiles_; - } - - // Sets a custom file accessor for file operations. Default is to directly - // access the files (with fopen and the rest). - // Useful in cases where running in a sandbox process and file access has to - // go through IPC, for example. - void SetFileAccessor(std::unique_ptr file_accessor) - { - fileAccessor_ = std::move(file_accessor); - } - FileAccessor *GetFileAccessor() const - { - return fileAccessor_.get(); - } - -private: - FilePath srcDir_; - - FilePath destFile_; - - int destFd_ = kInvalidPlatformFile; - - // The relative paths to the files that should be included in the zip file. If - // this is empty, all files in |srcDir_| are included. - std::vector srcFiles_; - - // Filter used to exclude files from the ZIP file. Only effective when - // |srcFiles_| is empty. - FilterCallback filterCallback_; - - // Whether hidden files should be included in the ZIP file. Only effective - // when |srcFiles_| is empty. - bool includeHiddenFiles_ = true; - - // Abstraction around file system access used to read files. An implementation - // that accesses files directly is provided by default. - std::unique_ptr fileAccessor_; -}; - -// Convenience method for callers who don't need to set up the filter callback. -// If |includeHiddenFiles| is true, files starting with "." are included. -// Otherwise they are omitted. -// example No1 -// srcDir = /ziptest/zipdata/ -// destFile = /ziptest/hapresult/hapfourfile.zip -// example No2 -// srcDir = /ziptest/zipdata/zip1/zip1-1.cpp -// destFile = /ziptest/hapresult/singlefile.zip -// options is default value. -bool Zip(const FilePath &srcDir, const FilePath &destFile, const OPTIONS &options, CALLBACK callback, - bool includeHiddenFiles); - -// Unzip the contents of zipFile into destDir. -// example No1 -// srcDir = /ziptest/hapresult/hapfourfile.zip -// destFile = /ziptest/hapunzipdir/01 -// example No2 -// srcDir = /ziptest/hapresult/singlefile.zip -// destFile = /ziptest/hapunzipdir/single -// options is default value. -bool Unzip(const FilePath &zipFile, const FilePath &destDir, const OPTIONS &options, CALLBACK callback); - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_H diff --git a/tools/zip/include/zip_internal.h b/tools/zip/include/zip_internal.h deleted file mode 100644 index 6e174da10e6b5b335d81d08ed3bbc5b5fd180995..0000000000000000000000000000000000000000 --- a/tools/zip/include/zip_internal.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_INTERNAL_H -#define FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_INTERNAL_H - -#include -#include -#include "contrib/minizip/unzip.h" -#include "contrib/minizip/zip.h" -#include "zip_utils.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -namespace { -const int kZipMaxPath = 256; -const int kZipBufSize = 8192; -} // namespace - -// Callback function for zlib that opens a file stream from a file descriptor. -// Since we do not own the file descriptor, dup it so that we can fdopen/fclose -// a file stream. -void *FdOpenFileFunc(void *opaque, const char *filename, int mode); - -int FdCloseFileFunc(void *opaque, void *stream); - -// Fills |pzlib_filecunc_def| appropriately to handle the zip file -// referred to by |fd|. -void FillFdOpenFileFunc(zlib_filefunc_def *pzlibFilefuncDef, PlatformFile fd); - -unzFile OpenFdForUnzipping(PlatformFile zipFD); - -struct tm GetTmDataFromTickts(int64_t ticks); - -unzFile OpenForUnzipping(std::string &fileNameUtf8); - -// Opens the file referred to by |zipFD| for unzipping. -unzFile OpenFdForUnzipping(int zipFD); - -// Creates a custom unzFile object which reads data from the specified string. -// This custom unzFile object overrides the I/O API functions of zlib so it can -// read data from the specified string. -unzFile PrepareMemoryForUnzipping(const std::string &data); - -// Opens the given file name in UTF-8 for zipping, with some setup for -// Windows. |append_flag| will be passed to zipOpen2(). -zipFile OpenForZipping(const std::string &fileNameUtf8, int appendFlag); - -// Opens the file referred to by |zipFD| for zipping. |append_flag| will be -// passed to zipOpen2(). -zipFile OpenFdForZipping(PlatformFile zipFd, int appendFlag); - -bool ZipOpenNewFileInZip( - zipFile zipFile, const std::string &strPath, const OPTIONS &options, const struct tm *lastModifiedTime); - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS - -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_INTERNAL_H diff --git a/tools/zip/include/zip_reader.h b/tools/zip/include/zip_reader.h deleted file mode 100644 index f2da18cad56c9369c80619c54b8c0c969e79bf69..0000000000000000000000000000000000000000 --- a/tools/zip/include/zip_reader.h +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_READER_H_ -#define FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_READER_H_ - -#include -#include -#include -#include -#include -#include -#include -#include "file_path.h" -#include "zip_utils.h" -#include "contrib/minizip/unzip.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -// A delegate interface used to stream out an entry; see -// ZipReader::ExtractCurrentEntry. -class WriterDelegate { -public: - virtual ~WriterDelegate() - {} - - // Invoked once before any data is streamed out to pave the way (e.g., to open - // the output file). Return false on failure to cancel extraction. - virtual bool PrepareOutput() = 0; - - // Invoked to write the next chunk of data. Return false on failure to cancel - // extraction. - virtual bool WriteBytes(const char *data, int numBytes) = 0; - - // Sets the last-modified time of the data. - virtual void SetTimeModified(const struct tm *modifiedTime) = 0; -}; - -// This class is used for reading zip files. -class ZipReader { -public: - // A callback that is called when the operation is successful. - using SuccessCallback = std::function; - // A callback that is called when the operation fails. - using FailureCallback = std::function; - - using ProgressCallback = std::function; - - // This class represents information of an entry (file or directory) in - // a zip file. - class EntryInfo { - public: - EntryInfo(const std::string &fileNameInZip, const unz_file_info &rawFileInfo); - virtual ~EntryInfo() - {} - // Returns the file path. The path is usually relative like - // "foo/bar.txt", but if it's absolute, is_unsafe() returns true. - const FilePath &GetFilePath() const - { - return filePath_; - } - - // Returns the size of the original file (i.e. after uncompressed). - // Returns 0 if the entry is a directory. - // Note: this value should not be trusted, because it is stored as metadata - // in the zip archive and can be different from the real uncompressed size. - int64_t GetOriginalSize() const - { - return originalSize_; - } - - // Returns the last modified time. If the time stored in the zip file was - // not valid, the unix epoch will be returned. - struct tm GetLastModified() const - { - return lastModified_; - } - - // Returns true if the entry is a directory. - bool IsDirectory() const - { - return isDirectory_; - } - - // Returns true if the entry is unsafe, like having ".." or invalid - // UTF-8 characters in its file name, or the file path is absolute. - bool IsUnsafe() const - { - return isUnsafe_; - } - - // Returns true if the entry is encrypted. - bool IsEncrypted() const - { - return isEncrypted_; - } - - private: - FilePath filePath_; - int64_t originalSize_ = 0; - struct tm lastModified_ { - .tm_year = 0, - .tm_mon = 0, - .tm_mday = 0, - .tm_hour = 0, - .tm_min = 0, - .tm_sec = 0 - }; - bool isDirectory_ = false; - bool isUnsafe_ = false; - bool isEncrypted_ = false; - DISALLOW_COPY_AND_ASSIGN(EntryInfo); - }; - - ZipReader(); - ~ZipReader(); - - // Opens the zip file specified by |zipFilePath|. Returns true on - // success. - bool Open(FilePath &zipFilePath); - - // Opens the zip file referred to by the platform file |zipFd|, without - // taking ownership of |zipFd|. Returns true on success. - bool OpenFromPlatformFile(PlatformFile zipFd); - - // Opens the zip data stored in |data|. This class uses a weak reference to - // the given sring while extracting files, i.e. the caller should keep the - // string until it finishes extracting files. - bool OpenFromString(const std::string &data); - - // Closes the currently opened zip file. This function is called in the - // destructor of the class, so you usually don't need to call this. - void Close(); - - // Returns true if there is at least one entry to read. This function is - // used to scan entries with AdvanceToNextEntry(), like: - // - // while (reader.HasMore()) { - // // Do something with the current file here. - // reader.AdvanceToNextEntry(); - // } - bool HasMore(); - - // Advances the next entry. Returns true on success. - bool AdvanceToNextEntry(); - - // Opens the current entry in the zip file. On success, returns true and - // updates the the current entry state (i.e. CurrentEntryInfo() is - // updated). This function should be called before operations over the - // current entry like ExtractCurrentEntryToFile(). - // - // Note that there is no CloseCurrentEntryInZip(). The the current entry - // state is reset automatically as needed. - bool OpenCurrentEntryInZip(); - - // Extracts |numBytesToExtract| bytes of the current entry to |delegate|, - // starting from the beginning of the entry. Return value specifies whether - // the entire file was extracted. - bool ExtractCurrentEntry(WriterDelegate *delegate, uint64_t numBytesToExtract) const; - - // Returns the current entry info. Returns NULL if the current entry is - // not yet opened. OpenCurrentEntryInZip() must be called beforehand. - EntryInfo *CurrentEntryInfo() const - { - return currentEntryInfo_.get(); - } - - // Returns the number of entries in the zip file. - // Open() must be called beforehand. - int num_entries() const - { - return numEntries_; - } - -private: - // Common code used both in Open and OpenFromFd. - bool OpenInternal(); - - // Resets the internal state. - void Reset(); - - unzFile zipFile_; - int numEntries_; - bool reachedEnd_; - std::unique_ptr currentEntryInfo_; - - DISALLOW_COPY_AND_ASSIGN(ZipReader); -}; - -// A writer delegate that writes a file at a given path. -class FilePathWriterDelegate : public WriterDelegate { -public: - explicit FilePathWriterDelegate(const FilePath &outputFilePath); - ~FilePathWriterDelegate() override; - - // WriterDelegate methods: - - // Creates the output file and any necessary intermediate directories. - bool PrepareOutput() override; - - // Writes |numBytes| bytes of |data| to the file, returning false if not all - // bytes could be written. - bool WriteBytes(const char *data, int numBytes) override; - - // Sets the last-modified time of the data. - void SetTimeModified(const struct tm *time) override; - -private: - FilePath outputFilePath_ = FilePath(std::string()); - FILE *file_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(FilePathWriterDelegate); -}; - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_READER_H_ diff --git a/tools/zip/include/zip_utils.h b/tools/zip/include/zip_utils.h deleted file mode 100644 index b842fe810ae221d3fa9c27e75dbdab6dec09f673..0000000000000000000000000000000000000000 --- a/tools/zip/include/zip_utils.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_UTILS_H -#define FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_UTILS_H -#include -#include -#include -#include -#include -#include -#include -#include "runnable.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -using Runnable = OHOS::AppExecFwk::Runnable; -using CALLBACK = std::function; - -#if !defined(DISALLOW_ASSIGN) -// Put this in the declarations for a class to be unassignable. -#define DISALLOW_ASSIGN(TypeName) void operator=(const TypeName &) = delete -#endif - -// A macro to disallow the copy constructor and operator= functions -// This should be used in the private: declarations for a class -// We define this macro conditionally as it may be defined by another libraries. -#if !defined(DISALLOW_COPY_AND_ASSIGN) -#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName &); \ - void operator = (const TypeName &) -#endif - -using PlatformFile = int; -using char16 = wchar_t; -using string16 = std::wstring; - -// zip Error -enum ErrorCode { - ERROR_CODE_OK = 0, - ERROR_CODE_STREAM_END = 1, - ERROR_CODE_NEED_DICT = 2, - ERROR_CODE_ERRNO = -1, - ERROR_CODE_STREAM_ERROR = -2, - ERROR_CODE_DATA_ERROR = -3, - ERROR_CODE_MEM_ERROR = -4, - ERROR_CODE_BUF_ERROR = -5, - ERROR_CODE_VERSION_ERROR = -6 -}; - -// Constant definitions related to zlib Library -enum FlushType { - FLUSH_TYPE_NO_FLUSH = 0, - FLUSH_TYPE_PARTIAL_FLUSH = 1, - FLUSH_TYPE_SYNC_FLUSH = 2, - FLUSH_TYPE_FULL_FLUSH = 3, - FLUSH_TYPE_FINISH = 4, - FLUSH_TYPE_BLOCK = 5, - FLUSH_TYPE_TREES = 6 -}; -using FLUSH_TYPE = enum FlushType; - -// Compress Level -enum CompressLevel { - COMPRESS_LEVEL_NO_COMPRESSION = 0, - COMPRESS_LEVEL_BEST_SPEED = 1, - COMPRESS_LEVEL_BEST_COMPRESSION = 9, - COMPRESS_LEVEL_DEFAULT_COMPRESSION = -1 -}; -using COMPRESS_LEVEL = enum CompressLevel; - -// Compress Strategy -enum CompressStrategy { - COMPRESS_STRATEGY_DEFAULT_STRATEGY = 0, - COMPRESS_STRATEGY_FILTERED = 1, - COMPRESS_STRATEGY_HUFFMAN_ONLY = 2, - COMPRESS_STRATEGY_RLE = 3, - COMPRESS_STRATEGY_FIXED = 4 -}; -using COMPRESS_STRATEGY = enum CompressStrategy; - -// Memory Level -enum MemoryLevel { MEM_LEVEL_MIN_MEMLEVEL = 1, MEM_LEVEL_DEFAULT_MEMLEVEL = 8, MEM_LEVEL_MAX_MEMLEVEL = 9 }; -using MEMORY_LEVEL = enum MemoryLevel; - -// Compression Options -struct Options { - FLUSH_TYPE flush; - FLUSH_TYPE finishFlush; - int chunkSize; // Buffer size, > 64 - COMPRESS_LEVEL level; // Compression level. The compression level is a number from 0 to 9. 0 has the fastest - // compression speed (compression process), 9 has the slowest compression speed, the largest - // compression rate, and 0 does not compress - MEMORY_LEVEL memLevel; // Internal compression status, how much memory should be allocated - COMPRESS_STRATEGY strategy; // CompressStrategy - - // default constructor - Options() - { - CompressDefaultValue(); - } - - // compression default options - void CompressDefaultValue() - { - flush = FLUSH_TYPE_NO_FLUSH; - finishFlush = FLUSH_TYPE_SYNC_FLUSH; - chunkSize = 128; - level = COMPRESS_LEVEL_DEFAULT_COMPRESSION; - memLevel = MEM_LEVEL_DEFAULT_MEMLEVEL; - strategy = COMPRESS_STRATEGY_DEFAULT_STRATEGY; - } -}; -using OPTIONS = struct Options; - -constexpr PlatformFile kInvalidPlatformFile = -1; - -struct tm *GetCurrentSystemTime(void); -bool StartsWith(const std::string &str, const std::string &searchFor); -bool EndsWith(const std::string &str, const std::string &searchFor); -void PostTask(const std::shared_ptr &runnable); -bool FilePathCheckValid(const std::string &str); -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS - -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_UTILS_H \ No newline at end of file diff --git a/tools/zip/include/zip_writer.h b/tools/zip/include/zip_writer.h deleted file mode 100644 index 7af56b7cb212f19035fca80e2a6579f0b1e60cbe..0000000000000000000000000000000000000000 --- a/tools/zip/include/zip_writer.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_WRITER_H -#define FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_WRITER_H - -#include -#include -#include "file_path.h" -#include "zip_utils.h" -#include "contrib/minizip/unzip.h" -#include "contrib/minizip/zip.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -// A class used to write entries to a ZIP file and buffering the reading of -// files to limit the number of calls to the FileAccessor. This is for -// performance reasons as these calls may be expensive when IPC based). -// This class is so far internal and only used by zip.cpp, but could be made -// public if needed. -class ZipWriter { -public: - // Creates a writer that will write a ZIP file to |zipFilefd|/|zip_file| - // and which entries (specifies with AddEntries) are relative to |rootDir|. - // All file reads are performed using |file_accessor|. - static std::unique_ptr CreateWithFd(PlatformFile zipFilefd, const FilePath &rootDir); - static std::unique_ptr Create(const FilePath &zip_file, const FilePath &rootDir); - ~ZipWriter(); - - // Writes the files at |paths| to the ZIP file and closes this Zip file. - // Note that the the FilePaths must be relative to |rootDir| specified in the - // Create method. - // Returns true if all entries were written successfuly. - bool WriteEntries(const std::vector &paths, const OPTIONS &options, CALLBACK callback); - -private: - ZipWriter(zipFile zip_file, const FilePath &rootDir); - - // Writes the pending entries to the ZIP file if there are at least - // |g_MaxPendingEntriesCount| of them. If |force| is true, all pending entries - // are written regardless of how many there are. - // Returns false if writing an entry fails, true if no entry was written or - // there was no error writing entries. - bool FlushEntriesIfNeeded(bool force, const OPTIONS &options, CALLBACK callback); - - // Adds the files at |paths| to the ZIP file. These FilePaths must be relative - // to |rootDir| specified in the Create method. - bool AddEntries(const std::vector &paths, const OPTIONS &options, CALLBACK callback); - - // Closes the ZIP file. - // Returns true if successful, false otherwise (typically if an entry failed - // to be written). - bool Close(const OPTIONS &options, CALLBACK callback); - - // The entries that have been added but not yet written to the ZIP file. - std::vector pendingEntries_; - - // The actual zip file. - zipFile zipFile_; - - // Path to the directory entry paths are relative to. - FilePath rootDir_; - - DISALLOW_COPY_AND_ASSIGN(ZipWriter); -}; -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS - -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_ZIP_WRITER_H \ No newline at end of file diff --git a/tools/zip/kits/js/@ohos.zlib.d.ts b/tools/zip/kits/js/@ohos.zlib.d.ts deleted file mode 100644 index abb974b2b034af961083197cdc467fab404de228..0000000000000000000000000000000000000000 --- a/tools/zip/kits/js/@ohos.zlib.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"), - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { AsyncCallback } from './basic'; - -declare namespace zlib { -/** - * @name ErrorCode - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ - export enum ErrorCode { - ERROR_CODE_OK = 0, - ERROR_CODE_ERRNO = -1 - } - -/** - * @name CompressLevel - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ - export enum CompressLevel { - COMPRESS_LEVEL_NO_COMPRESSION = 0, - COMPRESS_LEVEL_BEST_SPEED = 1, - COMPRESS_LEVEL_BEST_COMPRESSION = 9, - COMPRESS_LEVEL_DEFAULT_COMPRESSION = -1 - } - -/** - * @name CompressStrategy - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ - export enum CompressStrategy { - COMPRESS_STRATEGY_DEFAULT_STRATEGY = 0, - COMPRESS_STRATEGY_FILTERED = 1, - COMPRESS_STRATEGY_HUFFMAN_ONLY = 2, - COMPRESS_STRATEGY_RLE = 3, - COMPRESS_STRATEGY_FIXED = 4 - } - -/** - * @name MemLevel - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ - export enum MemLevel { - MEM_LEVEL_MIN = 1, - MEM_LEVEL_MAX = 9, - MEM_LEVEL_DEFAULT = 8 - } - -/** - * @name Options - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ - interface Options { - level?: CompressLevel; - memLevel?: MemLevel; - strategy?: CompressStrategy; - } - - /** - * Compress the specified file. - * - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param inFile Indicates the path of the file to be compressed. - * @param outFile Indicates the path of the output compressed file. - * @return Returns error code. - */ - function zipFile(inFile:string, outFile:string, options: Options): Promise; - - /** - * Decompress the specified file. - * - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param inFile Indicates the path of the file to be decompressed. - * @param outFile Indicates the path of the decompressed file. - * @return Returns error code. - */ - function unzipFile(inFile:string, outFile:string, options: Options): Promise; -} diff --git a/tools/zip/kits/napi/napi_zlib.cpp b/tools/zip/kits/napi/napi_zlib.cpp deleted file mode 100644 index 36bcdaa5d11a211120b92344056af057b061ed91..0000000000000000000000000000000000000000 --- a/tools/zip/kits/napi/napi_zlib.cpp +++ /dev/null @@ -1,893 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "napi_zlib.h" - -#include -#include -#include - -#include "file_path.h" -#include "hilog_wrapper.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "napi_zlib_common.h" -#include "zip.h" -#include "zip_utils.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -#define NO_ERROR 0 - -#define COMPRESS_LEVE_CHECK(level, ret) \ - if (!(level == COMPRESS_LEVEL_NO_COMPRESSION || level == COMPRESS_LEVEL_DEFAULT_COMPRESSION || \ - level == COMPRESS_LEVEL_BEST_SPEED || level == COMPRESS_LEVEL_BEST_COMPRESSION)) { \ - HILOG_ERROR("level parameter =[%{public}d] value is incorrect", (int)level); \ - return ret; \ - } - -#define COMPRESS_STRATEGY_CHECK(strategy, false) \ - if (!(strategy == COMPRESS_STRATEGY_DEFAULT_STRATEGY || strategy == COMPRESS_STRATEGY_FILTERED || \ - strategy == COMPRESS_STRATEGY_HUFFMAN_ONLY || strategy == COMPRESS_STRATEGY_RLE || \ - strategy == COMPRESS_STRATEGY_FIXED)) { \ - HILOG_ERROR("strategy parameter= [%{public}d] value is incorrect", (int)strategy); \ - return ret; \ - } - -#define COMPRESS_MEM_CHECK(mem, false) \ - if (!(mem == MEM_LEVEL_MIN_MEMLEVEL || mem == MEM_LEVEL_DEFAULT_MEMLEVEL || mem == MEM_LEVEL_MAX_MEMLEVEL)) { \ - HILOG_ERROR("memLevel parameter =[%{public}d] value is incorrect", (int)mem); \ - return ret; \ - } - -std::shared_ptr g_zipAceCallbackInfo = nullptr; -std::shared_ptr g_unzipAceCallbackInfo = nullptr; -void ZipFileAsyncCallBack(int result); -void ZipFilePromiseCallBack(int result); -void UnzipFileAsyncCallBack(int result); -void UnzipFilePromiseCallBack(int result); -napi_value UnwrapZipParam(CallZipUnzipParam ¶m, napi_env env, napi_value *args, size_t argc); -napi_value UnwrapUnZipParam(CallZipUnzipParam ¶m, napi_env env, napi_value *args, size_t argc); -napi_value ZipFileWrap(napi_env env, napi_callback_info info, AsyncZipCallbackInfo *asyncZipCallbackInfo); -napi_value UnwrapStringParam(std::string &str, napi_env env, napi_value args); -bool UnwrapOptionsParams(OPTIONS &options, napi_env env, napi_value arg); -napi_value ZipFileAsync(napi_env env, napi_value *args, size_t argcAsync, AsyncZipCallbackInfo *asyncZipCallbackInfo); -napi_value UnzipFileAsync(napi_env env, napi_value *args, size_t argcAsync, AsyncZipCallbackInfo *asyncZipCallbackInfo); -void ZipAndUnzipFileAsyncCallBack(std::shared_ptr &zipAceCallbackInfo, int result); -napi_value ZipFilePromise(napi_env env, AsyncZipCallbackInfo *asyncZipCallbackInfo); -napi_value UnzipFilePromise(napi_env env, AsyncZipCallbackInfo *asyncZipCallbackInfo); -void ZipAndUnzipFileAsyncCallBackInnerJsThread(uv_work_t *work, int status); - -/** - * @brief FlushType data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value FlushTypeInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s called.", __func__); - const int FLUSH_TYPE_NO_FLUSH = 0; - const int FLUSH_TYPE_PARTIAL_FLUSH = 1; - const int FLUSH_TYPE_SYNC_FLUSH = 2; - const int FLUSH_TYPE_FULL_FLUSH = 3; - const int FLUSH_TYPE_FINISH = 4; - const int FLUSH_TYPE_BLOCK = 5; - const int FLUSH_TYPE_TREES = 6; - - napi_value flushType = nullptr; - napi_create_object(env, &flushType); - SetNamedProperty(env, flushType, "FLUSH_TYPE_NO_FLUSH", FLUSH_TYPE_NO_FLUSH); - SetNamedProperty(env, flushType, "FLUSH_TYPE_PARTIAL_FLUSH", FLUSH_TYPE_PARTIAL_FLUSH); - SetNamedProperty(env, flushType, "FLUSH_TYPE_SYNC_FLUSH", FLUSH_TYPE_SYNC_FLUSH); - SetNamedProperty(env, flushType, "FLUSH_TYPE_FULL_FLUSH", FLUSH_TYPE_FULL_FLUSH); - SetNamedProperty(env, flushType, "FLUSH_TYPE_FINISH", FLUSH_TYPE_FINISH); - SetNamedProperty(env, flushType, "FLUSH_TYPE_BLOCK", FLUSH_TYPE_BLOCK); - SetNamedProperty(env, flushType, "FLUSH_TYPE_TREES", FLUSH_TYPE_TREES); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("FlushType", flushType), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); - - return exports; -} -/** - * @brief CompressLevel data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value CompressLevelInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s called.", __func__); - const int COMPRESS_LEVEL_NO_COMPRESSION = 0; - const int COMPRESS_LEVEL_BEST_SPEED = 1; - const int COMPRESS_LEVEL_BEST_COMPRESSION = 9; - const int COMPRESS_LEVEL_DEFAULT_COMPRESSION = -1; - - napi_value compressLevel = nullptr; - napi_create_object(env, &compressLevel); - SetNamedProperty(env, compressLevel, "COMPRESS_LEVEL_NO_COMPRESSION", COMPRESS_LEVEL_NO_COMPRESSION); - SetNamedProperty(env, compressLevel, "COMPRESS_LEVEL_BEST_SPEED", COMPRESS_LEVEL_BEST_SPEED); - SetNamedProperty(env, compressLevel, "COMPRESS_LEVEL_BEST_COMPRESSION", COMPRESS_LEVEL_BEST_COMPRESSION); - SetNamedProperty(env, compressLevel, "COMPRESS_LEVEL_DEFAULT_COMPRESSION", COMPRESS_LEVEL_DEFAULT_COMPRESSION); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("CompressLevel", compressLevel), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); - - return exports; -} -/** - * @brief CompressStrategy data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value CompressStrategyInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s called.", __func__); - const int COMPRESS_STRATEGY_DEFAULT_STRATEGY = 0; - const int COMPRESS_STRATEGY_FILTERED = 1; - const int COMPRESS_STRATEGY_HUFFMAN_ONLY = 2; - const int COMPRESS_STRATEGY_RLE = 3; - const int COMPRESS_STRATEGY_FIXED = 4; - - napi_value compressStrategy = nullptr; - napi_create_object(env, &compressStrategy); - SetNamedProperty(env, compressStrategy, "COMPRESS_STRATEGY_DEFAULT_STRATEGY", COMPRESS_STRATEGY_DEFAULT_STRATEGY); - SetNamedProperty(env, compressStrategy, "COMPRESS_STRATEGY_FILTERED", COMPRESS_STRATEGY_FILTERED); - SetNamedProperty(env, compressStrategy, "COMPRESS_STRATEGY_HUFFMAN_ONLY", COMPRESS_STRATEGY_HUFFMAN_ONLY); - SetNamedProperty(env, compressStrategy, "COMPRESS_STRATEGY_RLE", COMPRESS_STRATEGY_RLE); - SetNamedProperty(env, compressStrategy, "COMPRESS_STRATEGY_FIXED", COMPRESS_STRATEGY_FIXED); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("CompressStrategy", compressStrategy), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); - - return exports; -} -/** - * @brief MemLevel data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value MemLevelInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s called.", __func__); - const int MEM_LEVEL_MIN_MEMLEVEL = 1; - const int MEM_LEVEL_DEFAULT_MEMLEVEL = 8; - const int MEM_LEVEL_MAX_MEMLEVEL = 9; - - napi_value memLevel = nullptr; - napi_create_object(env, &memLevel); - SetNamedProperty(env, memLevel, "MEM_LEVEL_MIN_MEMLEVEL", MEM_LEVEL_MIN_MEMLEVEL); - SetNamedProperty(env, memLevel, "MEM_LEVEL_DEFAULT_MEMLEVEL", MEM_LEVEL_DEFAULT_MEMLEVEL); - SetNamedProperty(env, memLevel, "MEM_LEVEL_MAX_MEMLEVEL", MEM_LEVEL_MAX_MEMLEVEL); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("MemLevel", memLevel), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); - - return exports; -} -/** - * @brief Errorcode data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value ErrorCodeInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s called.", __func__); - - const int ERROR_CODE_OK = 0; - const int ERROR_CODE_STREAM_END = 1; - const int ERROR_CODE_NEED_DICT = 2; - const int ERROR_CODE_ERRNO = -1; - const int ERROR_CODE_STREAM_ERROR = -2; - const int ERROR_CODE_DATA_ERROR = -3; - const int ERROR_CODE_MEM_ERROR = -4; - const int ERROR_CODE_BUF_ERROR = -5; - const int ERROR_CODE_VERSION_ERROR = -6; - - napi_value errorCode = nullptr; - napi_create_object(env, &errorCode); - SetNamedProperty(env, errorCode, "ERROR_CODE_OK", ERROR_CODE_OK); - SetNamedProperty(env, errorCode, "ERROR_CODE_STREAM_END", ERROR_CODE_STREAM_END); - SetNamedProperty(env, errorCode, "ERROR_CODE_NEED_DICT", ERROR_CODE_NEED_DICT); - SetNamedProperty(env, errorCode, "ERROR_CODE_ERRNO", ERROR_CODE_ERRNO); - SetNamedProperty(env, errorCode, "ERROR_CODE_STREAM_ERROR", ERROR_CODE_STREAM_ERROR); - SetNamedProperty(env, errorCode, "ERROR_CODE_DATA_ERROR", ERROR_CODE_DATA_ERROR); - SetNamedProperty(env, errorCode, "ERROR_CODE_MEM_ERROR", ERROR_CODE_MEM_ERROR); - SetNamedProperty(env, errorCode, "ERROR_CODE_BUF_ERROR", ERROR_CODE_BUF_ERROR); - SetNamedProperty(env, errorCode, "ERROR_CODE_VERSION_ERROR", ERROR_CODE_VERSION_ERROR); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_PROPERTY("ErrorCode", errorCode), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); - - return exports; -} - -/** - * @brief FeatureAbility NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value ZlibInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s,called", __func__); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("zipFile", NAPI_ZipFile), - DECLARE_NAPI_FUNCTION("unzipFile", NAPI_UnzipFile), - }; - - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); - - return exports; -} - -AsyncZipCallbackInfo *CreateZipAsyncCallbackInfo(napi_env env) -{ - HILOG_INFO("%{public}s called.", __func__); - napi_status ret; - napi_value global = 0; - const napi_extended_error_info *errorInfo = nullptr; - ret = napi_get_global(env, &global); - if (ret != napi_ok) { - napi_get_last_error_info(env, &errorInfo); - if (errorInfo == nullptr) { - HILOG_ERROR("%{public}s errorInfo is null", __func__); - return nullptr; - } - HILOG_ERROR("%{public}s get_global=%{public}d err:%{public}s", __func__, ret, errorInfo->error_message); - } - - AsyncZipCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncZipCallbackInfo { - .asyncWork = nullptr, - .aceCallback = nullptr, - }; - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s asyncCallbackInfo is null", __func__); - return nullptr; - } - HILOG_INFO("%{public}s end.", __func__); - return asyncCallbackInfo; -} - -/** - * @brief Zlib NAPI method : zipFile. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_ZipFile(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called env=%{public}p", __func__, env); - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - size_t argcAsync = 4; - const size_t argcPromise = 3; - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync < argcPromise || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - AsyncZipCallbackInfo *asyncZipCallbackInfo = CreateZipAsyncCallbackInfo(env); - if (asyncZipCallbackInfo == nullptr) { - return nullptr; - } - - ret = ZipFileWrap(env, info, asyncZipCallbackInfo); - if (ret == nullptr) { - - if (g_zipAceCallbackInfo != nullptr) { - g_zipAceCallbackInfo.reset(); - g_zipAceCallbackInfo = nullptr; - } - if (asyncZipCallbackInfo != nullptr) { - delete asyncZipCallbackInfo; - asyncZipCallbackInfo = nullptr; - } - } - - return ret; -} - -napi_value ZipFileWrap(napi_env env, napi_callback_info info, AsyncZipCallbackInfo *asyncZipCallbackInfo) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - size_t argcAsync = 4; - const size_t argcPromise = 3; - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync < argcPromise || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - CallZipUnzipParam param; - if (UnwrapZipParam(param, env, args, argcAsync) == nullptr) { - HILOG_ERROR("%{public}s, call unwrapWant failed.", __func__); - return nullptr; - } - g_zipAceCallbackInfo = std::make_shared(); - if (g_zipAceCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, call param failed.", __func__); - return nullptr; - } - asyncZipCallbackInfo->aceCallback = g_zipAceCallbackInfo; - g_zipAceCallbackInfo->param = param; - g_zipAceCallbackInfo->env = env; - - if (argcAsync > PARAM3) { - ret = ZipFileAsync(env, args, argcAsync, asyncZipCallbackInfo); - } else { - ret = ZipFilePromise(env, asyncZipCallbackInfo); - } - return ret; -} -napi_value ZipFilePromise(napi_env env, AsyncZipCallbackInfo *asyncZipCallbackInfo) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (asyncZipCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, asyncZipCallbackInfo is nullptr.", __func__); - return nullptr; - } - - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - g_zipAceCallbackInfo->deferred = deferred; - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_ZipFile_Promise, worker pool thread execute."); - AsyncZipCallbackInfo *asyncCallbackInfo = static_cast(data); - if (asyncCallbackInfo != nullptr && asyncCallbackInfo->aceCallback != nullptr) { - Zip(FilePath(asyncCallbackInfo->aceCallback->param.src), - FilePath(asyncCallbackInfo->aceCallback->param.dest), - asyncCallbackInfo->aceCallback->param.options, - ZipFilePromiseCallBack, - false); - } - HILOG_INFO("NAPI_ZipFile_Promise, worker pool thread execute end."); - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_ZipFile_Promise, main event thread complete."); - AsyncZipCallbackInfo *asyncCallbackInfo = static_cast(data); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - HILOG_INFO("NAPI_ZipFile_Promise, main event thread complete end."); - }, - (void *)asyncZipCallbackInfo, - &asyncZipCallbackInfo->asyncWork); - - napi_queue_async_work(env, asyncZipCallbackInfo->asyncWork); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -napi_value UnwrapStringParam(std::string &str, napi_env env, napi_value argv) -{ - HILOG_INFO("%{public}s,called", __func__); - // unwrap the param[0] - napi_valuetype valueType = napi_valuetype::napi_undefined; - napi_status rev = napi_typeof(env, argv, &valueType); - if (rev != napi_ok) { - return nullptr; - } - - if (valueType != napi_valuetype::napi_string) { - HILOG_INFO("%{public}s called, Parameter type does not match", __func__); - return nullptr; - } - - size_t len; - napi_status status = napi_get_value_string_utf8(env, argv, nullptr, 0, &len); - if (status != napi_ok) { - HILOG_INFO("%{public}s called, Get locale tag length failed", __func__); - return nullptr; - } - std::vector buf(len + 1); - status = napi_get_value_string_utf8(env, argv, buf.data(), len + 1, &len); - if (status != napi_ok) { - HILOG_INFO("%{public}s called, Get locale tag failed", __func__); - return nullptr; - } - str = std::string(buf.data()); - - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -bool UnwrapOptionsParams(OPTIONS &options, napi_env env, napi_value arg) -{ - HILOG_INFO("%{public}s called.", __func__); - - if (!IsTypeForNapiValue(env, arg, napi_object)) { - return false; - } - napi_valuetype jsValueType = napi_undefined; - napi_value jsProNameList = nullptr; - uint32_t jsProCount = 0; - - NAPI_CALL_BASE(env, napi_get_property_names(env, arg, &jsProNameList), false); - NAPI_CALL_BASE(env, napi_get_array_length(env, jsProNameList, &jsProCount), false); - HILOG_INFO("%{public}s called. Property size=%{public}d.", __func__, jsProCount); - - napi_value jsProName = nullptr; - napi_value jsProValue = nullptr; - - for (uint32_t index = 0; index < jsProCount; index++) { - NAPI_CALL_BASE(env, napi_get_element(env, jsProNameList, index, &jsProName), false); - std::string strProName = UnwrapStringFromJS(env, jsProName, std::string()); - HILOG_INFO("%{public}s called. Property name=%{public}s.", __func__, strProName.c_str()); - NAPI_CALL_BASE(env, napi_get_named_property(env, arg, strProName.c_str(), &jsProValue), false); - NAPI_CALL_BASE(env, napi_typeof(env, jsProValue, &jsValueType), false); - - int ret = 0; - if (strProName == std::string("flush")) { - NAPI_CALL_BASE_BOOL(UnwrapIntValue(env, jsProValue, ret), false); - options.flush = static_cast(ret); - } else if (strProName == std::string("finishFlush")) { - NAPI_CALL_BASE_BOOL(UnwrapIntValue(env, jsProValue, ret), false); - options.finishFlush = static_cast(ret); - } else if (strProName == std::string("chunkSize")) { - NAPI_CALL_BASE_BOOL(UnwrapIntValue(env, jsProValue, ret), false); - options.chunkSize = ret; - } else if (strProName == std::string("level")) { - NAPI_CALL_BASE_BOOL(UnwrapIntValue(env, jsProValue, ret), false); - COMPRESS_LEVE_CHECK(ret, false) - options.level = static_cast(ret); - } else if (strProName == std::string("memLevel")) { - NAPI_CALL_BASE_BOOL(UnwrapIntValue(env, jsProValue, ret), false); - COMPRESS_MEM_CHECK(ret, false) - options.memLevel = static_cast(ret); - } else if (strProName == std::string("strategy")) { - NAPI_CALL_BASE_BOOL(UnwrapIntValue(env, jsProValue, ret), false); - COMPRESS_STRATEGY_CHECK(ret, false) - options.strategy = static_cast(ret); - } else if (strProName == std::string("dictionary")) { - continue; - } else { - continue; - } - } - return true; -} - -napi_value UnwrapZipParam(CallZipUnzipParam ¶m, napi_env env, napi_value *args, size_t argc) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcPromise = 3; - if (argc < argcPromise) { - HILOG_INFO("%{public}s called, param count is wrong", __func__); - return nullptr; - } - - // unwrap the param[0] - if (UnwrapStringParam(param.src, env, args[0]) == nullptr) { - HILOG_INFO("%{public}s called, args[0] error", __func__); - return nullptr; - } - - // unwrap the param[1] - if (UnwrapStringParam(param.dest, env, args[1]) == nullptr) { - HILOG_INFO("%{public}s called, args[1] error", __func__); - return nullptr; - } - - // unwrap the param[2] - if (!UnwrapOptionsParams(param.options, env, args[2])) { - HILOG_INFO("%{public}s called, args[2] error", __func__); - return nullptr; - } - // create reutrn - napi_value ret = 0; - NAPI_CALL_BASE(env, napi_create_int32(env, 0, &ret), nullptr); - return ret; -} - -napi_value UnwrapUnZipParam(CallZipUnzipParam ¶m, napi_env env, napi_value *args, size_t argc) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcPromise = 3; - if (argc < argcPromise) { - return nullptr; - } - // unwrap the param[0] - if (UnwrapStringParam(param.src, env, args[0]) == nullptr) { - return nullptr; - } - - // unwrap the param[1] - if (UnwrapStringParam(param.dest, env, args[1]) == nullptr) { - return nullptr; - } - - // create reutrn - napi_value ret = 0; - NAPI_CALL_BASE(env, napi_create_int32(env, 0, &ret), nullptr); - return ret; -} -/** - * @brief ZipFileAsync - * - * @param param Indicates the parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * - * @return The return value from NAPI C++ to JS for the module. - */ - -napi_value ZipFileAsync(napi_env env, napi_value *args, size_t argcAsync, AsyncZipCallbackInfo *asyncZipCallbackInfo) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || asyncZipCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, asyncZipCallbackInfo == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL_BASE(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName), nullptr); - - if (argcAsync > PARAM3) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL_BASE(env, napi_typeof(env, args[PARAM3], &valuetype), nullptr); - if (valuetype == napi_function) { - // resultCallback: AsyncCallback - napi_create_reference(env, args[PARAM3], 1, &g_zipAceCallbackInfo->callback); - } else { - HILOG_ERROR("%{public}s, args[3] error. It should be a function type.", __func__); - return nullptr; - } - } - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_ZipFile_callback, worker pool thread execute."); - AsyncZipCallbackInfo *asyncCallbackInfo = (AsyncZipCallbackInfo *)data; - if (asyncCallbackInfo != nullptr && asyncCallbackInfo->aceCallback != nullptr) { - Zip(FilePath(asyncCallbackInfo->aceCallback->param.src), - FilePath(asyncCallbackInfo->aceCallback->param.dest), - asyncCallbackInfo->aceCallback->param.options, - ZipFileAsyncCallBack, - false); - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_ZipFile_callback, main event thread complete."); - AsyncZipCallbackInfo *asyncCallbackInfo = (AsyncZipCallbackInfo *)data; - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - }, - (void *)asyncZipCallbackInfo, - &asyncZipCallbackInfo->asyncWork); - - napi_queue_async_work(env, asyncZipCallbackInfo->asyncWork); - napi_value result = 0; - napi_get_null(env, &result); - return result; -} - -/** - * @brief Zlib NAPI method : unzipFile. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_UnzipFile(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - size_t argcAsync = 4; - const size_t argcPromise = 3; - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync < argcPromise || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - // parse param - CallZipUnzipParam param; - if (UnwrapUnZipParam(param, env, args, argcAsync) == nullptr) { - HILOG_ERROR("%{public}s, call unwrap param failed.", __func__); - return nullptr; - } - - AsyncZipCallbackInfo *asyncZipCallbackInfo = CreateZipAsyncCallbackInfo(env); - if (asyncZipCallbackInfo == nullptr) { - return nullptr; - } - - g_unzipAceCallbackInfo = std::make_shared(); - asyncZipCallbackInfo->aceCallback = g_unzipAceCallbackInfo; - g_unzipAceCallbackInfo->param = param; - g_unzipAceCallbackInfo->env = env; - - if (argcAsync > PARAM3) { - ret = UnzipFileAsync(env, args, argcAsync, asyncZipCallbackInfo); - } else { - ret = UnzipFilePromise(env, asyncZipCallbackInfo); - } - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (g_unzipAceCallbackInfo != nullptr) { - g_unzipAceCallbackInfo.reset(); - g_unzipAceCallbackInfo = nullptr; - } - if (asyncZipCallbackInfo != nullptr) { - napi_delete_async_work(env, asyncZipCallbackInfo->asyncWork); - delete asyncZipCallbackInfo; - asyncZipCallbackInfo = nullptr; - } - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} -napi_value UnzipFilePromise(napi_env env, AsyncZipCallbackInfo *asyncZipCallbackInfo) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (asyncZipCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, asyncZipCallbackInfo is nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - g_unzipAceCallbackInfo->deferred = deferred; - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_UnzipFile_Promise, worker pool thread execute."); - AsyncZipCallbackInfo *asyncCallbackInfo = static_cast(data); - if (asyncCallbackInfo != nullptr && asyncCallbackInfo->aceCallback != nullptr) { - Unzip(FilePath(asyncCallbackInfo->aceCallback->param.src), - FilePath(asyncCallbackInfo->aceCallback->param.dest), - asyncCallbackInfo->aceCallback->param.options, - UnzipFilePromiseCallBack); - } - HILOG_INFO("NAPI_UnzipFile_Promise, worker pool thread execute end."); - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_UnzipFile_Promise, main event thread complete."); - AsyncZipCallbackInfo *asyncCallbackInfo = static_cast(data); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - HILOG_INFO("NAPI_UnzipFile_Promise, main event thread complete end."); - }, - (void *)asyncZipCallbackInfo, - &asyncZipCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncZipCallbackInfo->asyncWork); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} -napi_value UnzipFileAsync(napi_env env, napi_value *args, size_t argcAsync, AsyncZipCallbackInfo *asyncZipCallbackInfo) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || asyncZipCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - if (argcAsync > PARAM3) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL_BASE(env, napi_typeof(env, args[PARAM3], &valuetype), nullptr); - if (valuetype == napi_function) { - // resultCallback: AsyncCallback - napi_create_reference(env, args[PARAM3], 1, &g_unzipAceCallbackInfo->callback); - } else { - HILOG_ERROR("%{public}s, args[3] error. It should be a function type.", __func__); - return nullptr; - } - } - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_UnzipFile, worker pool thread execute."); - AsyncZipCallbackInfo *asyncCallbackInfo = (AsyncZipCallbackInfo *)data; - // Unzip - if (asyncCallbackInfo != nullptr && asyncCallbackInfo->aceCallback != nullptr) { - Unzip(FilePath(asyncCallbackInfo->aceCallback->param.src), - FilePath(asyncCallbackInfo->aceCallback->param.dest), - asyncCallbackInfo->aceCallback->param.options, - UnzipFileAsyncCallBack); - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_UnzipFile, main event thread complete."); - AsyncZipCallbackInfo *asyncCallbackInfo = (AsyncZipCallbackInfo *)data; - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - }, - (void *)asyncZipCallbackInfo, - &asyncZipCallbackInfo->asyncWork); - - napi_queue_async_work(env, asyncZipCallbackInfo->asyncWork); - napi_value result = 0; - napi_get_null(env, &result); - return result; -} -// ZipFile callback -void ZipFileAsyncCallBack(int result) -{ - if (g_zipAceCallbackInfo != nullptr) { - g_zipAceCallbackInfo->isCallBack = true; - } - ZipAndUnzipFileAsyncCallBack(g_zipAceCallbackInfo, result); -} -// ZipFile Promise -void ZipFilePromiseCallBack(int result) -{ - if (g_zipAceCallbackInfo != nullptr) { - g_zipAceCallbackInfo->isCallBack = false; - } - ZipAndUnzipFileAsyncCallBack(g_zipAceCallbackInfo, result); -} -// UnzipFile callback -void UnzipFileAsyncCallBack(int result) -{ - if (g_unzipAceCallbackInfo != nullptr) { - g_unzipAceCallbackInfo->isCallBack = true; - } - ZipAndUnzipFileAsyncCallBack(g_unzipAceCallbackInfo, result); -} -// UnzipFile Promise -void UnzipFilePromiseCallBack(int result) -{ - if (g_unzipAceCallbackInfo != nullptr) { - g_unzipAceCallbackInfo->isCallBack = false; - } - ZipAndUnzipFileAsyncCallBack(g_unzipAceCallbackInfo, result); -} -void ZipAndUnzipFileAsyncCallBackInnerJsThread(uv_work_t *work) -{ - // JS Thread - ZlibCallbackInfo *asyncCallbackInfo = (ZlibCallbackInfo *)work->data; - if (asyncCallbackInfo == nullptr) { - return; - } - napi_value result[ARGS_TWO] = {0}; - // callback result - napi_create_int32(asyncCallbackInfo->env, (int32_t)asyncCallbackInfo->callbackResult, &result[PARAM1]); - HILOG_INFO("%{public}s called, callbackResult =%{public}d", __func__, asyncCallbackInfo->callbackResult); - - if (asyncCallbackInfo->isCallBack) { - napi_value callback = 0; - napi_value undefined = 0; - // callback(err, data) errorInfo->error_code - result[PARAM0] = GetCallbackErrorValue(asyncCallbackInfo->env, NO_ERROR); - // get callback - napi_get_reference_value(asyncCallbackInfo->env, asyncCallbackInfo->callback, &callback); - napi_get_undefined(asyncCallbackInfo->env, &undefined); - // call callback - napi_value jsResult = 0; - napi_call_function(asyncCallbackInfo->env, undefined, callback, ARGS_TWO, &result[PARAM0], &jsResult); - // free data - if (asyncCallbackInfo->callback != nullptr) { - napi_delete_reference(asyncCallbackInfo->env, asyncCallbackInfo->callback); - } - } else { - // promise - napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result[PARAM1]); - } - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } -} -void ZipAndUnzipFileAsyncCallBack(std::shared_ptr &zipAceCallbackInfo, int result) -{ - if (zipAceCallbackInfo == nullptr) { - return; - } - HILOG_INFO("%{public}s,called env=%{public}p, result=%{public}d", __func__, zipAceCallbackInfo->env, result); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(zipAceCallbackInfo->env, &loop); - if (loop == nullptr) { - HILOG_ERROR("%{public}s, work == nullptr.", __func__); - return; - } - uv_work_t *work = new (std::nothrow) uv_work_t; - if (work == nullptr) { - HILOG_ERROR("%{public}s, work == nullptr.", __func__); - return; - } - ZlibCallbackInfo *asyncCallbackInfo = new (std::nothrow) ZlibCallbackInfo(); - if (asyncCallbackInfo == nullptr) { - delete work; - work = nullptr; - return; - } - *asyncCallbackInfo = *zipAceCallbackInfo; - asyncCallbackInfo->callbackResult = result; - zipAceCallbackInfo.reset(); - zipAceCallbackInfo = nullptr; - work->data = (void *)asyncCallbackInfo; - int rev = uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - HILOG_INFO("ZipAndUnzipFileAsyncCallBack, uv_queue_work"); - ZipAndUnzipFileAsyncCallBackInnerJsThread(work); - HILOG_INFO("ZipAndUnzipFileAsyncCallBack, uv_queue_work end."); - }); - if (rev != napi_ok) { - if (asyncCallbackInfo->isCallBack) { - if (asyncCallbackInfo->callback != nullptr) { - napi_delete_reference(asyncCallbackInfo->env, asyncCallbackInfo->callback); - } - } - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - } -} - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS diff --git a/tools/zip/kits/napi/napi_zlib.h b/tools/zip/kits/napi/napi_zlib.h deleted file mode 100644 index 2e8e6696e8c1488d9118510fa8873ac13511d94f..0000000000000000000000000000000000000000 --- a/tools/zip/kits/napi/napi_zlib.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef OHOS_AAFwk_LIBZIP_ZLIB_H -#define OHOS_AAFwk_LIBZIP_ZLIB_H -#include - -#include "napi/native_api.h" -#include "napi_zlib_common.h" -#include "zip_utils.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -/** - * @brief FlushType data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value FlushTypeInit(napi_env env, napi_value exports); -/** - * @brief CompressLevel data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value CompressLevelInit(napi_env env, napi_value exports); - -/** - * @brief CompressStrategy data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value CompressStrategyInit(napi_env env, napi_value exports); - -/** - * @brief MemLevel data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value MemLevelInit(napi_env env, napi_value exports); - -/** - * @brief Errorcode data initialization. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value ErrorCodeInit(napi_env env, napi_value exports); -/** - * @brief zlib NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value ZlibInit(napi_env env, napi_value exports); - -/** - * @brief Zlib NAPI method : zipFile. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - * - * NAPI_Zipfile interface supports promise and callback calls. - * - * example No1 - * var src ="/ziptest/zipdata/"; - * var dest ="/ziptest/hapresult/hapfourfile.zip"; - * var option = { - * flush:0, - * finishFlush:2, - * chunkSize:68, - * memLevel:8, - * level:-1, - * strategy:0 - * }; - * - * example No2 - * var src ="/ziptest/zipdata/zip1/zip1-1.cpp"; - * var dest ="/ziptest/hapresult/single.zip"; - * var option = { - * flush:0, - * finishFlush:2, - * chunkSize:68, - * memLevel:8, - * level:-1, - * strategy:0 - * }; - * - */ -napi_value NAPI_ZipFile(napi_env env, napi_callback_info info); - -/** - * @brief Zlib NAPI method : unzipFile. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - * - * NAPI_UnzipFile interface supports promise and callback calls. - * - * example No1 - * var src ="/ziptest/hapresult/hapfourfile.zip"; - * var dest ="/ziptest/hapunzipdir/01"; - * var option = { - * flush:0, - * finishFlush:2, - * chunkSize:68, - * memLevel:8, - * level:-1, - * strategy:0 - * }; - * - * example No2 - * var src ="/ziptest/hapresult/single.zip"; - * var dest ="/ziptest/hapunzipdir/single"; - * var option = { - * flush:0, - * finishFlush:2, - * chunkSize:68, - * memLevel:8, - * level:-1, - * strategy:0 - * }; - */ -napi_value NAPI_UnzipFile(napi_env env, napi_callback_info info); - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS - -#endif // OHOS_AAFwk_LIBZIP_ZLIB_H diff --git a/tools/zip/kits/napi/napi_zlib_common.cpp b/tools/zip/kits/napi/napi_zlib_common.cpp deleted file mode 100644 index d8e03126e667bf8912c32ad41f76c6e6dfa860f2..0000000000000000000000000000000000000000 --- a/tools/zip/kits/napi/napi_zlib_common.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "napi_zlib_common.h" - -#include "hilog_wrapper.h" -#include "securec.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -namespace { -const int E_OK = 0; -} - -bool IsTypeForNapiValue(napi_env env, napi_value param, napi_valuetype expectType) -{ - napi_valuetype valueType = napi_undefined; - - if (napi_typeof(env, param, &valueType) != napi_ok) { - return false; - } - - return valueType == expectType; -} - -std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue) -{ - size_t size = 0; - if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) { - return defaultValue; - } - - std::string value(""); - if (size == 0) { - return defaultValue; - } - - char *buf = new (std::nothrow) char[size + 1]; - if (buf == nullptr) { - return value; - } - if (memset_s(buf, size + 1, 0, size + 1) != E_OK) { - delete[] buf; - buf = nullptr; - return nullptr; - } - - bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok; - if (rev) { - value = buf; - } else { - value = defaultValue; - } - - delete[] buf; - buf = nullptr; - return value; -} - -bool UnwrapIntValue(napi_env env, napi_value jsValue, int &result) -{ - napi_valuetype jsValueType = napi_undefined; - NAPI_CALL_BASE(env, napi_typeof(env, jsValue, &jsValueType), false); - if (jsValueType != napi_number) { - return false; - } - int32_t natValue32 = 0; - NAPI_CALL_BASE(env, napi_get_value_int32(env, jsValue, &natValue32), false); - result = static_cast(natValue32); - return true; -} -napi_value GetCallbackErrorValue(napi_env env, int errCode) -{ - napi_value jsObject = nullptr; - napi_value jsValue = nullptr; - NAPI_CALL(env, napi_create_int32(env, errCode, &jsValue)); - NAPI_CALL(env, napi_create_object(env, &jsObject)); - NAPI_CALL(env, napi_set_named_property(env, jsObject, "code", jsValue)); - return jsObject; -} - -void SetNamedProperty(napi_env env, napi_value obj, const char *propName, const int propValue) -{ - napi_value prop = nullptr; - napi_create_int32(env, propValue, &prop); - napi_set_named_property(env, obj, propName, prop); -} -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS \ No newline at end of file diff --git a/tools/zip/kits/napi/napi_zlib_common.h b/tools/zip/kits/napi/napi_zlib_common.h deleted file mode 100644 index dfb7ca40485e62fa88bd0364e52263172cd799f0..0000000000000000000000000000000000000000 --- a/tools/zip/kits/napi/napi_zlib_common.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef OHOS_AAFwk_LIBZIP_COMMON_H -#define OHOS_AAFwk_LIBZIP_COMMON_H -#include -#include - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "zip_utils.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -#define NATIVE_C_BUFFER_SIZE 1024 /* Converted to C-style string buffer size */ -#define ARGS_MAX_COUNT 10 -#define ARGS_ASYNC_COUNT 1 - -#define ARGS_ONE 1 -#define ARGS_TWO 2 -#define ARGS_THREE 3 -#define ARGS_FOUR 4 -#define ARGS_FIVE 5 -#define ARGS_SIX 6 -#define ARGS_SEVEN 7 -#define ARGS_EIGHT 8 -#define ARGS_NINE 9 -#define ARGS_TEN 10 - -#define PARAM0 0 -#define PARAM1 1 -#define PARAM2 2 -#define PARAM3 3 -#define PARAM4 4 -#define PARAM5 5 -#define PARAM6 6 -#define PARAM7 7 -#define PARAM8 8 -#define PARAM9 9 -#define PARAM10 10 - -#define NAPI_CALL_BASE_BOOL(theCall, retVal) \ - do { \ - if ((theCall) == false) { \ - return retVal; \ - } \ - } while (0) - -struct CallZipUnzipParam { - std::string src; - std::string dest; - OPTIONS options; -}; - -struct ZlibCallbackInfo { - napi_env env; - napi_ref callback = 0; - napi_deferred deferred; - CallZipUnzipParam param; - bool isCallBack = false; - int callbackResult = 0; -}; - -struct AsyncZipCallbackInfo { - napi_async_work asyncWork; - std::shared_ptr aceCallback; -}; -bool UnwrapIntValue(napi_env env, napi_value jsValue, int &result); -bool IsTypeForNapiValue(napi_env env, napi_value param, napi_valuetype expectType); -std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue); -napi_value GetCallbackErrorValue(napi_env env, int errCode); -void SetNamedProperty(napi_env env, napi_value obj, const char *propName, const int propValue); - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS -#endif // OHOS_AAFwk_LIBZIP_COMMON_H \ No newline at end of file diff --git a/tools/zip/src/file_path.cpp b/tools/zip/src/file_path.cpp deleted file mode 100644 index 13a5361cfda54f7db2f0099403903bf9e4ea9613..0000000000000000000000000000000000000000 --- a/tools/zip/src/file_path.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "file_path.h" -#include -#include -#include -#include "zip_utils.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -#define F_OK 0 - -namespace { -const std::string SEPARATOR = "/"; -} -const FilePath::CharType FilePath::kSeparators[] = FILE_PATH_LITERAL("/"); -const size_t FilePath::kSeparatorsLength = arraysize(kSeparators); -const FilePath::CharType FilePath::kCurrentDirectory[] = FILE_PATH_LITERAL("."); -const FilePath::CharType FilePath::kParentDirectory[] = FILE_PATH_LITERAL(".."); -const FilePath::CharType FilePath::kExtensionSeparator = FILE_PATH_LITERAL('.'); - -FilePath::FilePath() -{} - -FilePath::FilePath(const FilePath &that) : path_(that.path_) -{} - -FilePath::FilePath(const std::string &path) : path_(path) -{} - -FilePath::~FilePath() -{} - -FilePath &FilePath::operator=(const FilePath &that) -{ - if (&that != this) { - path_ = that.path_; - } - return *this; -} - -bool FilePath::operator==(const FilePath &that) const -{ - return path_ == that.path_; -} - -bool FilePath::operator!=(const FilePath &that) const -{ - return path_ != that.path_; -} - -bool FilePath::operator<(const FilePath &that) const -{ - return path_ < that.path_; -} - -FilePath FilePath::FromUTF8Unsafe(const std::string &utf8) -{ - return FilePath(utf8); -} - -bool FilePath::ReferencesParent() -{ - std::vector components; - GetComponents(components); - - for (size_t i = 0; i < components.size(); i++) { - if (components[i].find_first_not_of(FILE_PATH_LITERAL(". \n\r\t")) == std::string::npos && - components[i].find(kParentDirectory) != std::string::npos) { - return true; - } - } - return false; -} - -void FilePath::GetComponents(std::vector &components) -{ - components.clear(); - if (path_.empty()) { - return; - } - - FilePath current = *this; - FilePath base; - // Capture path components. - while (current != current.DirName()) { - base = current.BaseName(); - if (!AreAllSeparators(base.path_)) - components.push_back(base.path_); - current = current.DirName(); - } - - // Capture root, if any. - base = current.BaseName(); - if (!base.path_.empty() && base.path_ != kCurrentDirectory) { - components.push_back(current.BaseName().path_); - } -} - -FilePath FilePath::DirName() -{ - FilePath newPath(path_); - newPath.StripTrailingSeparatorsInternal(); - - std::string::size_type lastSeparator = - newPath.path_.find_last_of(kSeparators, std::string::npos, kSeparatorsLength - 1); - std::string::size_type zero = 0; - std::string::size_type one = 1; - std::string::size_type two = 2; - - if (lastSeparator == std::string::npos) { - // path_ is in the current directory. - newPath.path_.resize(zero); - } else if (lastSeparator == zero) { - // path_ is in the root directory. - newPath.path_.resize(one); - } else if (lastSeparator == one && IsSeparator(newPath.path_[zero])) { - // path_ is in "//" (possibly with a drive letter); leave the double - // separator intact indicating alternate root. - newPath.path_.resize(two); - } else if (lastSeparator != 0) { - // path_ is somewhere else, trim the basename. - newPath.path_.resize(lastSeparator); - } - - newPath.StripTrailingSeparatorsInternal(); - if (!newPath.path_.length()) - newPath.path_ = kCurrentDirectory; - - return newPath; -} - -FilePath FilePath::BaseName() -{ - FilePath newPath(path_); - newPath.StripTrailingSeparatorsInternal(); - - // Keep everything after the final separator, but if the pathname is only - // one character and it's a separator, leave it alone. - std::string::size_type lastSeparator = - newPath.path_.find_last_of(kSeparators, std::string::npos, kSeparatorsLength - 1); - if (lastSeparator != std::string::npos && lastSeparator < newPath.path_.length() - 1) { - newPath.path_.erase(0, lastSeparator + 1); - } - - return newPath; -} - -void FilePath::StripTrailingSeparatorsInternal() -{ - if (path_.size() == 0) { - return; - } - int one = 1; - int two = 2; - int start = 1; - std::string::size_type lastStripped = std::string::npos; - for (std::string::size_type pos = path_.length(); pos > start && FilePath::IsSeparator(path_[pos - one]); --pos) { - if (pos != start + one || lastStripped == start + two || !FilePath::IsSeparator(path_[start - one])) { - path_.resize(pos - one); - lastStripped = pos; - } - } -} - -bool FilePath::AreAllSeparators(const std::string &input) -{ - for (std::string::const_iterator it = input.begin(); it != input.end(); ++it) { - if (!FilePath::IsSeparator(*it)) { - return false; - } - } - - return true; -} - -bool FilePath::IsAbsolute() -{ - return path_.length() > 0 && FilePath::IsSeparator(path_[0]); -} - -std::string FilePath::Value() -{ - return path_; -} -bool FilePath::IsSeparator(CharType character) -{ - for (size_t i = 0; i < kSeparatorsLength - 1; ++i) { - if (character == kSeparators[i]) { - return true; - } - } - return false; -} -bool FilePath::CreateDirectory(const FilePath &fullPath) -{ - std::vector subpaths; - - // Collect a list of all parent directories. - FilePath lastPath = fullPath; - subpaths.push_back(fullPath); - for (FilePath path = const_cast(fullPath).DirName(); path.Value() != lastPath.Value(); - path = path.DirName()) { - subpaths.push_back(path); - lastPath = path; - } - mode_t rootMode = 0777; - // Iterate through the parents and create the missing ones. - for (std::vector::reverse_iterator i = subpaths.rbegin(); i != subpaths.rend(); ++i) { - if (DirectoryExists(*i)) { - continue; - } - if (mkdir(i->Value().c_str(), rootMode) == 0) { - continue; - } - - if (!DirectoryExists(*i)) { - return false; - } - } - return true; -} -// static -bool FilePath::DirectoryExists(const FilePath &path) -{ - - struct stat fileInfo; - if (stat(const_cast(path).Value().c_str(), &fileInfo) == 0) { - return S_ISDIR(fileInfo.st_mode); - } - return false; -} - -bool FilePath::PathIsValid(const FilePath &path) -{ - return access(const_cast(path).Value().c_str(), F_OK) == 0; -} - -// Returns a FilePath by appending a separator and the supplied path -// component to this object's path. Append takes care to avoid adding -// excessive separators if this object's path already ends with a separator. -// If this object's path is kCurrentDirectory, a new FilePath corresponding -// only to |component| is returned. |component| must be a relative path; -// it is an error to pass an absolute path. -FilePath FilePath::Append(const std::string &component) -{ - if (component.empty()) { - FilePath pathOrg(path_); - return pathOrg; - } - - std::string newPathString; - // empty - if (Value().empty()) { - newPathString += component; - } else if (EndsWith(Value(), SEPARATOR)) { - if (StartsWith(component, SEPARATOR)) { - newPathString = component.substr(1, component.size()); - } else { - newPathString = path_ + SEPARATOR + component; - } - } else { - if (StartsWith(component, SEPARATOR)) { - newPathString = path_ + component; - } else { - newPathString = path_ + SEPARATOR + component; - } - } - - FilePath newPath(newPathString); - return newPath; -} - -FilePath FilePath::Append(FilePath &component) -{ - if (component.path_.empty()) { - FilePath pathOrg(path_); - return pathOrg; - } - - return Append(component.path_); -} - -// If IsParent(child) holds, appends to path (if non-NULL) the -// relative path to child and returns true. -bool FilePath::AppendRelativePath(const FilePath &child, FilePath *path) -{ - FilePath childPath = child; - std::vector parentComponents; - std::vector childComponents; - GetComponents(parentComponents); - childPath.GetComponents(childComponents); - - if (parentComponents.empty() || parentComponents.size() >= childComponents.size()) { - return false; - } - - std::vector parentComponentsReverse; - std::vector childComponentsReverse; - - std::vector::reverse_iterator riter; - for (riter = parentComponents.rbegin(); riter != parentComponents.rend(); riter++) { - parentComponentsReverse.push_back(*riter); - } - for (riter = childComponents.rbegin(); riter != childComponents.rend(); riter++) { - childComponentsReverse.push_back(*riter); - } - std::vector::const_iterator parentIt = parentComponentsReverse.begin(); - std::vector::const_iterator childIt = childComponentsReverse.begin(); - while (parentIt != parentComponentsReverse.end()) { - if (*parentIt != *childIt) - return false; - ++parentIt; - ++childIt; - } - - if (path != nullptr) { - // Relative paths do not include separator - if ((childIt != childComponentsReverse.end()) && (*childIt == SEPARATOR)) { - ++childIt; - } - - for (; childIt != childComponentsReverse.end(); childIt++) { - *path = path->Append(*childIt); - } - } - return true; -} - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS diff --git a/tools/zip/src/zip.cpp b/tools/zip/src/zip.cpp deleted file mode 100644 index a529cf1c96dac9aa165aa3f1d8c0fd631c90e830..0000000000000000000000000000000000000000 --- a/tools/zip/src/zip.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "zip.h" - -#include -#include -#include -#include -#include -#include - -#include "directory_ex.h" -#include "file_path.h" -#include "hilog_wrapper.h" -#include "runnable.h" -#include "zip_internal.h" -#include "zip_reader.h" -#include "zip_writer.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -namespace { -using FilterCallback = std::function; -using DirectoryCreator = std::function; -using WriterFactory = std::function(FilePath &, FilePath &)>; - -const std::string SEPARATOR = "/"; -const char HIDDEN_SEPARATOR = '.'; - -#define CALLING_CALL_BACK(callback, result) \ - if (callback != nullptr) { \ - callback(result); \ - } - -struct UnzipParam { - CALLBACK callback = nullptr; - FilterCallback filterCB = nullptr; - bool logSkippedFiles = false; -}; -bool IsHiddenFile(const FilePath &filePath) -{ - FilePath localFilePath = filePath; - std::string path = localFilePath.BaseName().Value(); - if (!localFilePath.Value().empty()) { - return localFilePath.Value().c_str()[0] == HIDDEN_SEPARATOR; - } else { - return false; - } -} -bool ExcludeNoFilesFilter(const FilePath &filePath) -{ - return true; -} - -bool ExcludeHiddenFilesFilter(const FilePath &filePath) -{ - return !IsHiddenFile(filePath); -} - -std::vector ListDirectoryContent(const FilePath &filePath) -{ - FilePath curPath = filePath; - std::vector fileDirectoryVector; - std::vector filelist; - GetDirFiles(curPath.Value(), filelist); - HILOG_INFO("filelist ========filelist.size=%{public}zu", filelist.size()); - for (size_t i = 0; i < filelist.size(); i++) { - std::string str(filelist[i]); - if (!str.empty()) { - fileDirectoryVector.push_back( - FileAccessor::DirectoryContentEntry(FilePath(str), FilePath::DirectoryExists(FilePath(str)))); - } - } - return fileDirectoryVector; -} - -// Creates a directory at |extractDir|/|entryPath|, including any parents. -bool CreateDirectory(FilePath &extractDir, FilePath &entryPath) -{ - std::string path = extractDir.Value(); - if (EndsWith(path, SEPARATOR)) { - return FilePath::CreateDirectory(FilePath(extractDir.Value() + entryPath.Value())); - } else { - return FilePath::CreateDirectory(FilePath(extractDir.Value() + "/" + entryPath.Value())); - } -} - -// Creates a WriterDelegate that can write a file at |extractDir|/|entryPath|. -std::unique_ptr CreateFilePathWriterDelegate(FilePath &extractDir, FilePath entryPath) -{ - if (EndsWith(extractDir.Value(), SEPARATOR)) { - return std::make_unique(FilePath(extractDir.Value() + entryPath.Value())); - } else { - return std::make_unique(FilePath(extractDir.Value() + "/" + entryPath.Value())); - } -} -} // namespace - -ZipParams::ZipParams(const FilePath &srcDir, const FilePath &destFile) : srcDir_(srcDir), destFile_(destFile) -{} - -// Does not take ownership of |fd|. -ZipParams::ZipParams(const FilePath &srcDir, int destFd) : srcDir_(srcDir), destFd_(destFd) -{} - -bool Zip(const ZipParams ¶ms, const OPTIONS &options, CALLBACK callback) -{ - const std::vector *filesToAdd = ¶ms.GetFilesTozip(); - std::vector allRelativeFiles; - FilePath paramPath = params.SrcDir(); - bool endIsSeparator = EndsWith(paramPath.Value(), SEPARATOR); - if (filesToAdd->empty()) { - filesToAdd = &allRelativeFiles; - std::list entries; - if (endIsSeparator) { - entries.push_back(FileAccessor::DirectoryContentEntry(params.SrcDir(), true)); - FilterCallback filterCallback = params.GetFilterCallback(); - for (auto iter = entries.begin(); iter != entries.end(); ++iter) { - const FilePath &constEntryPath = iter->path; - if (iter != entries.begin() && ((!params.GetIncludeHiddenFiles() && IsHiddenFile(constEntryPath)) || - (filterCallback && !filterCallback(constEntryPath)))) { - continue; - } - if (iter != entries.begin()) { - FilePath relativePath; - FilePath entryPath = constEntryPath; - FilePath paramsSrcPath = params.SrcDir(); - bool success = paramsSrcPath.AppendRelativePath(entryPath, &relativePath); - if (success) { - allRelativeFiles.push_back(relativePath); - } - } - if (iter->isDirectory) { - std::vector subEntries = ListDirectoryContent(constEntryPath); - entries.insert(entries.end(), subEntries.begin(), subEntries.end()); - } - } - } else { - allRelativeFiles.push_back(paramPath.BaseName()); - } - } - std::unique_ptr zipWriter = nullptr; - FilePath rootPath = (endIsSeparator == false) ? FilePath(paramPath.DirName().Value() + SEPARATOR) : params.SrcDir(); - if (params.DestFd() != kInvalidPlatformFile) { - zipWriter = ZipWriter::CreateWithFd(params.DestFd(), rootPath); - if (!zipWriter) { - CALLING_CALL_BACK(callback, ERROR_CODE_STREAM_ERROR) - return false; - } - } - if (!zipWriter) { - zipWriter = ZipWriter::Create(params.DestFile(), rootPath); - if (!zipWriter) { - CALLING_CALL_BACK(callback, ERROR_CODE_STREAM_ERROR) - return false; - } - } - return zipWriter->WriteEntries(*filesToAdd, options, callback); -} - -bool UnzipWithFilterAndWriters(const PlatformFile &srcFile, FilePath &destDir, WriterFactory writerFactory, - DirectoryCreator directoryCreator, UnzipParam &unzipParam) -{ - HILOG_INFO("%{public}s called, destDir=%{public}s", __func__, destDir.Value().c_str()); - ZipReader reader; - if (!reader.OpenFromPlatformFile(srcFile)) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_ERRNO) - HILOG_INFO("%{public}s called, Failed to open srcFile.", __func__); - return false; - } - while (reader.HasMore()) { - if (!reader.OpenCurrentEntryInZip()) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_ERRNO) - HILOG_INFO("%{public}s called, Failed to open the current file in zip.", __func__); - return false; - } - const FilePath &constEntryPath = reader.CurrentEntryInfo()->GetFilePath(); - FilePath entryPath = constEntryPath; - if (reader.CurrentEntryInfo()->IsUnsafe()) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_ERRNO) - HILOG_INFO("%{public}s called, Found an unsafe file in zip.", __func__); - return false; - } - // callback - if (unzipParam.filterCB(entryPath)) { - if (reader.CurrentEntryInfo()->IsDirectory()) { - if (!directoryCreator(destDir, entryPath)) { - HILOG_INFO("!!!directory_creator(%{public}s) Failed!!!.", entryPath.Value().c_str()); - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_ERRNO) - return false; - } - - } else { - std::unique_ptr writer = writerFactory(destDir, entryPath); - if (!reader.ExtractCurrentEntry(writer.get(), std::numeric_limits::max())) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_ERRNO) - HILOG_INFO("%{public}s called, Failed to extract.", __func__); - return false; - } - } - } else if (unzipParam.logSkippedFiles) { - HILOG_INFO("%{public}s called, Skipped file.", __func__); - } - - if (!reader.AdvanceToNextEntry()) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_ERRNO) - HILOG_INFO("%{public}s called, Failed to advance to the next file.", __func__); - return false; - } - } - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_OK) - return true; -} -bool UnzipWithFilterCallback( - const FilePath &srcFile, const FilePath &destDir, const OPTIONS &options, UnzipParam &unzipParam) -{ - FilePath src = srcFile; - if (!FilePathCheckValid(src.Value())) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_DATA_ERROR) - return false; - } - - FilePath dest = destDir; - - HILOG_INFO("%{public}s called, srcFile=%{public}s, destFile=%{public}s", - __func__, - src.Value().c_str(), - dest.Value().c_str()); - - if (!FilePath::PathIsValid(srcFile)) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_DATA_ERROR) - HILOG_INFO("%{public}s called, Failed to open.", __func__); - return false; - } - - PlatformFile zipFd = open(src.Value().c_str(), S_IREAD); - if (zipFd == kInvalidPlatformFile) { - CALLING_CALL_BACK(unzipParam.callback, ERROR_CODE_STREAM_ERROR) - HILOG_INFO("%{public}s called, Failed to open.", __func__); - return false; - } - bool ret = UnzipWithFilterAndWriters(zipFd, - dest, - std::bind(&CreateFilePathWriterDelegate, std::placeholders::_1, std::placeholders::_2), - std::bind(&CreateDirectory, std::placeholders::_1, std::placeholders::_2), - unzipParam); - - close(zipFd); - - return ret; -} -bool Unzip(const FilePath &srcFile, const FilePath &destDir, const OPTIONS &options, CALLBACK callback) -{ - FilePath srcFileDir = srcFile; - FilePath destDirTemp = destDir; - HILOG_INFO("%{public}s called, srcFile=%{public}s, destFile=%{public}s", - __func__, - srcFileDir.Value().c_str(), - destDirTemp.Value().c_str()); - - std::shared_ptr innerTask = std::make_shared([srcFile, destDir, options, callback]() { - UnzipParam unzipParam { - .callback = callback, - .filterCB = ExcludeNoFilesFilter, - .logSkippedFiles = true - }; - UnzipWithFilterCallback(srcFile, destDir, options, unzipParam); - }); - - PostTask(innerTask); - return true; -} - -bool ZipWithFilterCallback(const FilePath &srcDir, const FilePath &destFile, const OPTIONS &options, CALLBACK callback, - FilterCallback filterCB) -{ - FilePath srcPath = srcDir; - if (!EndsWith(srcPath.Value(), SEPARATOR)) { - if (!FilePath::DirectoryExists(srcPath.DirName())) { - CALLING_CALL_BACK(callback, ERROR_CODE_DATA_ERROR) - return false; - } - } else if (!FilePath::DirectoryExists(srcDir)) { - CALLING_CALL_BACK(callback, ERROR_CODE_DATA_ERROR) - return false; - } - ZipParams params(srcDir, destFile); - params.SetFilterCallback(filterCB); - return Zip(params, options, callback); -} - -bool Zip(const FilePath &srcDir, const FilePath &destFile, const OPTIONS &options, CALLBACK callback, - bool includeHiddenFiles) -{ - FilePath srctemp = srcDir; - FilePath desttemp = destFile; - HILOG_INFO("%{public}s called, srcDir=%{public}s, destFile=%{public}s", - __func__, - srctemp.Value().c_str(), - desttemp.Value().c_str()); - - FilePath srcdir = srcDir; - - std::shared_ptr innerTask = - std::make_shared([srcDir, destFile, includeHiddenFiles, callback]() { - OPTIONS options; - if (includeHiddenFiles) { - ZipWithFilterCallback(srcDir, destFile, options, callback, ExcludeNoFilesFilter); - } else { - ZipWithFilterCallback(srcDir, destFile, options, callback, ExcludeHiddenFilesFilter); - } - }); - PostTask(innerTask); - - return true; -} -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS diff --git a/tools/zip/src/zip_internal.cpp b/tools/zip/src/zip_internal.cpp deleted file mode 100644 index a88c8c3bf1bb49143d1105dd4b29cdd3291153b6..0000000000000000000000000000000000000000 --- a/tools/zip/src/zip_internal.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "zip_internal.h" - -#include -#include -#include - -#include "hilog_wrapper.h" -#include "securec.h" -#include "zip_utils.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -struct tm GetTmDataFromTickts(int64_t sec) -{ - time_t second = (time_t)sec; - struct tm now { - .tm_year = 0, - .tm_mon = 0, - .tm_mday = 0, - .tm_hour = 0, - .tm_min = 0, - .tm_sec = 0, - }; - struct tm *tmNow = localtime(&second); - if (tmNow == nullptr) { - return now; - } - int baseYeaar = 1900; - now = *tmNow; - now.tm_year += baseYeaar; - now.tm_mon += 1; - return now; -} - -// Callback function for zlib that opens a file stream from a file descriptor. -// Since we do not own the file descriptor, dup it so that we can fdopen/fclose -// a file stream. -void *FdOpenFileFunc(void *opaque, const char *filename, int mode) -{ - FILE *file = NULL; - const char *mode_fopen = NULL; - uint32_t modeInner = static_cast(mode); - if ((modeInner & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) - mode_fopen = "rb"; - else if (modeInner & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else if (modeInner & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; - - if ((filename != NULL) && (mode_fopen != NULL)) { - int fd = dup(*static_cast(opaque)); - if (fd != -1) - file = fdopen(fd, mode_fopen); - } - - return file; -} - -int FdCloseFileFunc(void *opaque, void *stream) -{ - fclose(static_cast(stream)); - free(opaque); // malloc'ed in FillFdOpenFileFunc() - return 0; -} - -// Fills |pzlib_filecunc_def| appropriately to handle the zip file -// referred to by |fd|. -void FillFdOpenFileFunc(zlib_filefunc_def *pzlibFilefuncDef, PlatformFile fd) -{ - fill_fopen_filefunc(pzlibFilefuncDef); - pzlibFilefuncDef->zopen_file = FdOpenFileFunc; - pzlibFilefuncDef->zclose_file = FdCloseFileFunc; - int *ptrFd = static_cast(malloc(sizeof(fd))); - if (ptrFd == nullptr) { - return; - } - *ptrFd = fd; - pzlibFilefuncDef->opaque = ptrFd; -} - -// A struct that contains data required for zlib functions to extract files from -// a zip archive stored in memory directly. The following I/O API functions -// expect their opaque parameters refer to this struct. -struct ZipBuffer { - const char *data; - size_t length; - size_t offset; -}; - -// Opens the specified file. When this function returns a non-NULL pointer, zlib -// uses this pointer as a stream parameter while compressing or uncompressing -// data. (Returning NULL represents an error.) This function initializes the -// given opaque parameter and returns it because this parameter stores all -// information needed for uncompressing data. (This function does not support -// writing compressed data and it returns NULL for this case.) -void *OpenZipBuffer(void *opaque, const char *, int mode) -{ - uint32_t modeInner = static_cast(mode); - if ((modeInner & ZLIB_FILEFUNC_MODE_READWRITEFILTER) != ZLIB_FILEFUNC_MODE_READ) { - HILOG_INFO("%{public}s called, mode is not ZLIB_FILEFUNC_MODE_READ.", __func__); - return NULL; - } - ZipBuffer *buffer = static_cast(opaque); - if (!buffer || !buffer->data || !buffer->length) { - return NULL; - } - buffer->offset = 0; - return opaque; -} - -// Reads compressed data from the specified stream. This function copies data -// refered by the opaque parameter and returns the size actually copied. -uLong ReadZipBuffer(void *opaque, void *, void *buf, uLong size) -{ - ZipBuffer *buffer = static_cast(opaque); - if (buffer == nullptr) { - HILOG_INFO("%{public}s called, buffer = nullptr.", __func__); - return 0; - } - if (buffer->offset > buffer->length) { - HILOG_INFO("%{public}s called, buffer->offset > buffer->length.", __func__); - return 0; - } - - size_t remaining_bytes = buffer->length - buffer->offset; - if (!buffer || !buffer->data || !remaining_bytes) { - return 0; - } - size = std::min(size, static_cast(remaining_bytes)); - if (memcpy_s(buf, size, &buffer->data[buffer->offset], size) != EOK) { - return 0; - } - buffer->offset += size; - return size; -} - -// Writes compressed data to the stream. This function always returns zero -// because this implementation is only for reading compressed data. -uLong WriteZipBuffer(void *opaque, void *stream, const void *buf, uLong) -{ - HILOG_INFO("%{public}s called. opaque=%p, stream=%p, buf=%p", __func__, opaque, stream, buf); - return 0; -} - -// Returns the offset from the beginning of the data. -long GetOffsetOfZipBuffer(void *opaque, void *) -{ - ZipBuffer *buffer = static_cast(opaque); - if (!buffer) { - return -1; - } - return static_cast(buffer->offset); -} - -// Moves the current offset to the specified position. -long SeekZipBuffer(void *opaque, void *, uLong offset, int origin) -{ - ZipBuffer *buffer = static_cast(opaque); - if (!buffer) { - return -1; - } - if (origin == ZLIB_FILEFUNC_SEEK_CUR) { - buffer->offset = std::min(buffer->offset + static_cast(offset), buffer->length); - return 0; - } - if (origin == ZLIB_FILEFUNC_SEEK_END) { - buffer->offset = (buffer->length > offset) ? buffer->length - offset : 0; - return 0; - } - if (origin == ZLIB_FILEFUNC_SEEK_SET) { - buffer->offset = std::min(buffer->length, static_cast(offset)); - return 0; - } - HILOG_INFO("%{public}s called. origin is not supported.", __func__); - return -1; -} - -// Closes the input offset and deletes all resources used for compressing or -// uncompressing data. This function deletes the ZipBuffer object referred by -// the opaque parameter since zlib deletes the unzFile object and it does not -// use this object any longer. -int CloseZipBuffer(void *opaque, void *) -{ - if (opaque) { - free(opaque); - } - return 0; -} - -// Returns the last error happened when reading or writing data. This function -// always returns zero, which means there are not any errors. -int GetErrorOfZipBuffer(void *, void *) -{ - return 0; -} - -bool TimeToZipFileInfo(const struct tm *fileTime, zip_fileinfo &zipInfo) -{ - if (fileTime == nullptr) { - return false; - } - - zipInfo.tmz_date.tm_year = (int)fileTime->tm_year + 1900; - zipInfo.tmz_date.tm_mon = (int)fileTime->tm_mon + 1; - zipInfo.tmz_date.tm_mday = (int)fileTime->tm_mday; - zipInfo.tmz_date.tm_hour = (int)fileTime->tm_hour; - zipInfo.tmz_date.tm_min = (int)fileTime->tm_min; - zipInfo.tmz_date.tm_sec = (int)fileTime->tm_sec; - return true; -} - -unzFile OpenForUnzipping(std::string &fileNameUtf8) -{ - zlib_filefunc_def *zipFuncPtrs = nullptr; - return unzOpen2(fileNameUtf8.c_str(), zipFuncPtrs); -} - -unzFile OpenFdForUnzipping(int zipFD) -{ - zlib_filefunc_def zipFuncs; - FillFdOpenFileFunc(&zipFuncs, zipFD); - return unzOpen2("fd", &zipFuncs); -} - -// static -unzFile PrepareMemoryForUnzipping(const std::string &data) -{ - if (data.empty()) { - return NULL; - } - ZipBuffer *buffer = static_cast(malloc(sizeof(ZipBuffer))); - if (!buffer) { - return NULL; - } - buffer->data = data.data(); - buffer->length = data.length(); - buffer->offset = 0; - - zlib_filefunc_def zipFunctions; - zipFunctions.zopen_file = OpenZipBuffer; - zipFunctions.zread_file = ReadZipBuffer; - zipFunctions.zwrite_file = WriteZipBuffer; - zipFunctions.ztell_file = GetOffsetOfZipBuffer; - zipFunctions.zseek_file = SeekZipBuffer; - zipFunctions.zclose_file = CloseZipBuffer; - zipFunctions.zerror_file = GetErrorOfZipBuffer; - zipFunctions.opaque = static_cast(buffer); - return unzOpen2(NULL, &zipFunctions); -} - -zipFile OpenForZipping(const std::string &fileNameUtf8, int appendFlag) -{ - zlib_filefunc_def *zipFuncPtrs = NULL; - return zipOpen2(fileNameUtf8.c_str(), - appendFlag, - NULL, - zipFuncPtrs); -} - -zipFile OpenFdForZipping(PlatformFile zipFd, int appendFlag) -{ - zlib_filefunc_def zipFuncs; - FillFdOpenFileFunc(&zipFuncs, zipFd); - // Passing dummy "fd" filename to zlib. - return zipOpen2("fd", appendFlag, NULL, &zipFuncs); -} - -bool ZipOpenNewFileInZip( - zipFile zipFile, const std::string &strPath, const OPTIONS &options, const struct tm *lastModifiedTime) -{ - const uLong LANGUAGE_ENCODING_FLAG = 0x1 << 11; - - zip_fileinfo fileInfo = {}; - TimeToZipFileInfo(lastModifiedTime, fileInfo); - if (ZIP_OK != zipOpenNewFileInZip4(zipFile, // file - strPath.c_str(), // filename - &fileInfo, // zip_fileinfo - NULL, // extrafield_local, - 0u, // size_extrafield_local - NULL, // extrafield_global - 0u, // size_extrafield_global - NULL, // comment - Z_DEFLATED, // method - (int)options.level, // level:default Z_DEFAULT_COMPRESSION - 0, // raw - -MAX_WBITS, // windowBits - (int)options.memLevel, // memLevel: default DEF_MEM_LEVEL - (int)options.strategy, // strategy:default Z_DEFAULT_STRATEGY - NULL, // password - 0, // crcForCrypting - 0, // versionMadeBy - LANGUAGE_ENCODING_FLAG)) { // flagBase - return false; - } - return true; -} - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS diff --git a/tools/zip/src/zip_reader.cpp b/tools/zip/src/zip_reader.cpp deleted file mode 100644 index bf49098382325e29df1badefaad0a359760f1efe..0000000000000000000000000000000000000000 --- a/tools/zip/src/zip_reader.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "zip_reader.h" - -#include -#include -#include -#include - -#include "checked_cast.h" -#include "contrib/minizip/unzip.h" -#include "hilog_wrapper.h" -#include "string_ex.h" -#include "zip_internal.h" -#include "zip_utils.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -// TODO(satorux): The implementation assumes that file names in zip files -// are encoded in UTF-8. This is true for zip files created by Zip() -// function in zip.h, but not true for user-supplied random zip files. -ZipReader::EntryInfo::EntryInfo(const std::string &fileNameInZip, const unz_file_info &rawFileInfo) - : filePath_(FilePath::FromUTF8Unsafe(fileNameInZip)), isDirectory_(false), isUnsafe_(false), isEncrypted_(false) -{ - originalSize_ = rawFileInfo.uncompressed_size; - - // Directory entries in zip files end with "/". - isDirectory_ = EndsWith(fileNameInZip, "/"); - - // Check the file name here for directory traversal issues. - isUnsafe_ = filePath_.ReferencesParent(); - - // We also consider that the file name is unsafe, if it's absolute. - // On Windows, IsAbsolute() returns false for paths starting with "/". - if (filePath_.IsAbsolute() || StartsWith(fileNameInZip, "/")) { - isUnsafe_ = false; - } - - // Whether the file is encrypted is bit 0 of the flag. - isEncrypted_ = rawFileInfo.flag & 1; - - // Construct the last modified time. The timezone info is not present in - // zip files, so we construct the time as local time. - if (GetCurrentSystemTime() != nullptr) { - lastModified_ = *GetCurrentSystemTime(); - } -} - -ZipReader::ZipReader() -{ - Reset(); -} - -ZipReader::~ZipReader() -{ - Close(); -} - -bool ZipReader::Open(FilePath &zipFilePath) -{ - if (zipFile_ != nullptr) { - return false; - } - - // Use of "Unsafe" function does not look good, but there is no way to do - // this safely on Linux. See file_util.h for details. - std::string zipfile = zipFilePath.Value(); - zipFile_ = OpenForUnzipping(zipfile); - if (zipFile_ == nullptr) { - return false; - } - - return OpenInternal(); -} - -bool ZipReader::OpenFromPlatformFile(PlatformFile zipFd) -{ - if (zipFile_ != nullptr) { - return false; - } - zipFile_ = OpenFdForUnzipping(zipFd); - if (!zipFile_) { - return false; - } - - return OpenInternal(); -} - -bool ZipReader::OpenFromString(const std::string &data) -{ - zipFile_ = PrepareMemoryForUnzipping(data); - if (!zipFile_) { - return false; - } - - return OpenInternal(); -} - -void ZipReader::Close() -{ - if (zipFile_) { - unzClose(zipFile_); - } - Reset(); -} - -bool ZipReader::HasMore() -{ - return !reachedEnd_; -} - -bool ZipReader::AdvanceToNextEntry() -{ - if (zipFile_ == nullptr) { - return false; - } - // Should not go further if we already reached the end. - if (reachedEnd_) { - return false; - } - unz_file_pos position = {}; - if (unzGetFilePos(zipFile_, &position) != UNZ_OK) { - return false; - } - - const int currentEntryIndex = position.num_of_file; - // If we are currently at the last entry, then the next position is the - // end of the zip file, so mark that we reached the end. - if (currentEntryIndex + 1 == numEntries_) { - reachedEnd_ = true; - } else { - if (unzGoToNextFile(zipFile_) != UNZ_OK) { - return false; - } - } - currentEntryInfo_.reset(); - return true; -} - -bool ZipReader::OpenCurrentEntryInZip() -{ - if (zipFile_ == nullptr) { - return false; - } - - unz_file_info raw_file_info = {}; - char raw_file_name_in_zip[kZipMaxPath] = {}; - - const int result = unzGetCurrentFileInfo(zipFile_, - &raw_file_info, - raw_file_name_in_zip, - sizeof(raw_file_name_in_zip) - 1, - NULL, // extraField. - 0, // extraFieldBufferSize. - NULL, // szComment. - 0); // commentBufferSize. - - if (result != UNZ_OK) { - return false; - } - if (raw_file_name_in_zip[0] == '\0') { - return false; - } - currentEntryInfo_.reset(new EntryInfo(std::string(raw_file_name_in_zip), raw_file_info)); - return true; -} - -bool ZipReader::ExtractCurrentEntry(WriterDelegate *delegate, uint64_t numBytesToExtract) const -{ - if (zipFile_ == nullptr) { - return false; - } - const int openResult = unzOpenCurrentFile(zipFile_); - if (openResult != UNZ_OK) { - return false; - } - if (!delegate->PrepareOutput()) { - return false; - } - std::unique_ptr buf(new char[kZipBufSize]); - uint64_t remainingCapacity = numBytesToExtract; - bool entirefileextracted = false; - - while (remainingCapacity > 0) { - const int numBytesRead = unzReadCurrentFile(zipFile_, buf.get(), kZipBufSize); - if (numBytesRead == 0) { - entirefileextracted = true; - break; - } else if (numBytesRead < 0) { - // If numBytesRead < 0, then it's a specific UNZ_* error code. - break; - } else if (numBytesRead > 0) { - uint64_t numBytesToWrite = std::min(remainingCapacity, checked_cast(numBytesRead)); - if (!delegate->WriteBytes(buf.get(), numBytesToWrite)) { - break; - } - if (remainingCapacity == checked_cast(numBytesRead)) { - // Ensures function returns true if the entire file has been read. - entirefileextracted = (unzReadCurrentFile(zipFile_, buf.get(), 1) == 0); - } - if (remainingCapacity >= numBytesToWrite) { - remainingCapacity -= numBytesToWrite; - } - } - } - - unzCloseCurrentFile(zipFile_); - // closeFile - delegate->SetTimeModified(GetCurrentSystemTime()); - - return entirefileextracted; -} - -bool ZipReader::OpenInternal() -{ - if (zipFile_ == nullptr) { - return false; - } - - unz_global_info zipInfo = {}; // Zero-clear. - if (unzGetGlobalInfo(zipFile_, &zipInfo) != UNZ_OK) { - return false; - } - numEntries_ = zipInfo.number_entry; - if (numEntries_ < 0) { - return false; - } - - // We are already at the end if the zip file is empty. - reachedEnd_ = (numEntries_ == 0); - return true; -} - -void ZipReader::Reset() -{ - zipFile_ = NULL; - numEntries_ = 0; - reachedEnd_ = false; - currentEntryInfo_.reset(); -} - -// FilePathWriterDelegate -FilePathWriterDelegate::FilePathWriterDelegate(const FilePath &outputFilePath) : outputFilePath_(outputFilePath) -{} - -FilePathWriterDelegate::~FilePathWriterDelegate() -{} - -bool FilePathWriterDelegate::PrepareOutput() -{ - if (!FilePathCheckValid(outputFilePath_.Value())) { - HILOG_ERROR("%{public}s called, outputFilePath_ invalid !!!.", __func__); - return false; - } - // We can't rely on parent directory entries being specified in the - // zip, so we make sure they are created. - if (!FilePath::CreateDirectory(outputFilePath_.DirName())) { - return false; - } - - file_ = fopen(outputFilePath_.Value().c_str(), "wb"); - return FilePath::PathIsValid(outputFilePath_); -} - -bool FilePathWriterDelegate::WriteBytes(const char *data, int numBytes) -{ - if (file_ == nullptr || numBytes <= 0) { - return false; - } - int writebytes = fwrite(data, 1, numBytes, file_); - return numBytes == writebytes; -} - -void FilePathWriterDelegate::SetTimeModified(const struct tm *time) -{ - fclose(file_); - file_ = nullptr; -} - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS \ No newline at end of file diff --git a/tools/zip/src/zip_utils.cpp b/tools/zip/src/zip_utils.cpp deleted file mode 100644 index a4a5e87dead32e30a178910e49b2547902b5efd2..0000000000000000000000000000000000000000 --- a/tools/zip/src/zip_utils.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "zip_utils.h" - -#include -#include -#include - -#include "parallel_task_dispatcher.h" -#include "runnable.h" -#include "task_dispatcher_context.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -namespace { -const std::string SEPARATOR = "/"; -const std::regex FILE_PATH_REGEX("([0-9A-Za-z/+_=\\-,.])+"); -} // namespace -using namespace OHOS::AppExecFwk; - -std::shared_ptr g_TaskDispatcher = nullptr; -void PostTask(const std::shared_ptr &runnable) -{ - static TaskDispatcherContext taskContext; - - if (g_TaskDispatcher == nullptr) { - g_TaskDispatcher = taskContext.CreateParallelDispatcher(std::string("toolszip"), TaskPriority::DEFAULT); - } - - if (g_TaskDispatcher != nullptr) { - g_TaskDispatcher->AsyncDispatch(runnable); - } -} - -struct tm *GetCurrentSystemTime(void) -{ - auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - struct tm *time = localtime(&tt); - if (time == nullptr) { - return nullptr; - } - int baseYear = 1900; - time->tm_mday = time->tm_mday + baseYear; - time->tm_mday = time->tm_mon + 1; - return time; -} - -bool StartsWith(const std::string &str, const std::string &searchFor) -{ - if (searchFor.size() > str.size()) { - return false; - } - - std::string source = str.substr(0, searchFor.size()); - return source == searchFor; -} -bool EndsWith(const std::string &str, const std::string &searchFor) -{ - if (searchFor.size() > str.size()) { - return false; - } - - std::string source = str.substr(str.size() - searchFor.size(), searchFor.size()); - return source == searchFor; -} - -bool IsPathAbsolute(const std::string &path) -{ - // Look for a separator in the first position. - return path.length() > 0 && StartsWith(path, SEPARATOR); -} - -bool IsASCIIChar(const char *pszStr) -{ - if (pszStr == NULL) { - return false; - } - - // Judge whether the first character in the string is ASCII character (0 – 127), and ASCII character occupies one - // byte - return ((unsigned char)pszStr[0] & 0x80) == 0x80 ? false : true; -} -bool FilePathCheckValid(const std::string &str) -{ - return std::regex_match(str, FILE_PATH_REGEX); -} - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS diff --git a/tools/zip/src/zip_writer.cpp b/tools/zip/src/zip_writer.cpp deleted file mode 100644 index 51bb371a7722a99cd7e66517705ce8c8ba791f94..0000000000000000000000000000000000000000 --- a/tools/zip/src/zip_writer.cpp +++ /dev/null @@ -1,236 +0,0 @@ - -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 "zip_writer.h" - -#include - -#include "contrib/minizip/zip.h" -#include "directory_ex.h" -#include "hilog_wrapper.h" -#include "zip_internal.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -namespace { -// Numbers of pending entries that trigger writting them to the ZIP file. -constexpr size_t g_MaxPendingEntriesCount = 50; -const std::string SEPARATOR = "/"; - -#define CALLING_CALL_BACK(callback, result) \ - if (callback != nullptr) { \ - callback(result); \ - } - -bool AddFileContentToZip(zipFile zip_file, FilePath &file_path) -{ - HILOG_INFO("%{public}s called", __func__); - int num_bytes; - char buf[kZipBufSize]; - if (!FilePathCheckValid(file_path.Value())) { - HILOG_INFO( - "%{public}s called, filePath is invalid!!! file_path=%{public}s", __func__, file_path.Value().c_str()); - return false; - } - - if (!FilePath::PathIsValid(file_path)) { - return false; - } - - FILE *fp = fopen(file_path.Value().c_str(), "rb"); - if (fp == nullptr) { - HILOG_INFO("%{public}s called, filePath to realPath failed! filePath:%{private}s ", - __func__, - file_path.Value().c_str()); - return false; - } - - while (!feof(fp)) { - num_bytes = fread(buf, 1, kZipBufSize, fp); - if (num_bytes > 0) { - if (zipWriteInFileInZip(zip_file, buf, num_bytes) != ZIP_OK) { - HILOG_INFO("%{public}s called, Could not write data to zip for path:%{public}s ", - __func__, - file_path.Value().c_str()); - fclose(fp); - fp = nullptr; - return false; - } - } - } - fclose(fp); - fp = nullptr; - return true; -} - -bool OpenNewFileEntry( - zipFile zip_file, FilePath &path, bool is_directory, struct tm *last_modified, const OPTIONS &options) -{ - HILOG_INFO("%{public}s called", __func__); - std::string strPath = path.Value(); - return ZipOpenNewFileInZip(zip_file, strPath, options, last_modified); -} - -bool CloseNewFileEntry(zipFile zip_file) -{ - HILOG_INFO("%{public}s called", __func__); - return zipCloseFileInZip(zip_file) == ZIP_OK; -} - -bool AddFileEntryToZip(zipFile zip_file, FilePath &relativePath, FilePath &absolutePath, const OPTIONS &options) -{ - HILOG_INFO("%{public}s called", __func__); - - struct tm *lastModified = GetCurrentSystemTime(); - if (lastModified == nullptr) { - return false; - } - if (!OpenNewFileEntry(zip_file, relativePath, false, lastModified, options)) { - return false; - } - bool success = AddFileContentToZip(zip_file, absolutePath); - if (!CloseNewFileEntry(zip_file)) { - return false; - } - - return success; -} - -bool AddDirectoryEntryToZip(zipFile zip_file, FilePath &path, struct tm *lastModified, const OPTIONS &options) -{ - HILOG_INFO("%{public}s called", __func__); - return OpenNewFileEntry(zip_file, path, true, lastModified, options) && CloseNewFileEntry(zip_file); -} - -} // namespace - -std::unique_ptr ZipWriter::CreateWithFd(PlatformFile zipFilefd, const FilePath &rootDir) -{ - HILOG_INFO("%{public}s called", __func__); - if (zipFilefd == kInvalidPlatformFile) { - return nullptr; - } - - zipFile zip_file = OpenFdForZipping(zipFilefd, APPEND_STATUS_CREATE); - if (!zip_file) { - HILOG_INFO("%{public}s called, Couldn't create ZIP file for FD", __func__); - return nullptr; - } - return std::unique_ptr(new ZipWriter(zip_file, rootDir)); -} - -// static -std::unique_ptr ZipWriter::Create(const FilePath &zip_file_path, const FilePath &rootDir) -{ - FilePath zipFilePath = zip_file_path; - HILOG_INFO("%{public}s called", __func__); - if (zipFilePath.Value().empty()) { - HILOG_INFO("%{public}s called, Path is empty", __func__); - return nullptr; - } - - zipFile zip_file = OpenForZipping(zipFilePath.Value(), APPEND_STATUS_CREATE); - if (!zip_file) { - HILOG_INFO("%{public}s called, Couldn't create ZIP file at path", __func__); - return nullptr; - } - return std::unique_ptr(new (std::nothrow) ZipWriter(zip_file, rootDir)); -} - -ZipWriter::ZipWriter(zipFile zip_file, const FilePath &rootDir) : zipFile_(zip_file), rootDir_(rootDir) -{} - -ZipWriter::~ZipWriter() -{ - pendingEntries_.clear(); -} - -bool ZipWriter::WriteEntries(const std::vector &paths, const OPTIONS &options, CALLBACK callback) -{ - HILOG_INFO("%{public}s called", __func__); - return AddEntries(paths, options, callback) && Close(options, callback); -} - -bool ZipWriter::AddEntries(const std::vector &paths, const OPTIONS &options, CALLBACK callback) -{ - if (!zipFile_) { - return false; - } - pendingEntries_.insert(pendingEntries_.end(), paths.begin(), paths.end()); - return FlushEntriesIfNeeded(false, options, callback); -} - -bool ZipWriter::Close(const OPTIONS &options, CALLBACK callback) -{ - bool success = FlushEntriesIfNeeded(true, options, callback) && zipClose(zipFile_, nullptr) == ZIP_OK; - zipFile_ = nullptr; - return success; -} - -bool ZipWriter::FlushEntriesIfNeeded(bool force, const OPTIONS &options, CALLBACK callback) -{ - if (pendingEntries_.size() < g_MaxPendingEntriesCount && !force) { - return true; - } - - std::string rootDir = rootDir_.Value(); - if (EndsWith(rootDir_.Value(), SEPARATOR)) { - rootDir = rootDir.substr(0, rootDir.size() - 1); - } - while (pendingEntries_.size() >= g_MaxPendingEntriesCount || (force && !pendingEntries_.empty())) { - - size_t entry_count = std::min(pendingEntries_.size(), g_MaxPendingEntriesCount); - std::vector relativePaths; - std::vector absolutePaths; - - relativePaths.insert(relativePaths.begin(), pendingEntries_.begin(), pendingEntries_.begin() + entry_count); - for (auto iter = pendingEntries_.begin(); iter != pendingEntries_.begin() + entry_count; ++iter) { - // The FileAccessor requires absolute paths. - absolutePaths.push_back(FilePath(rootDir_.Value() + iter->Value())); - } - pendingEntries_.erase(pendingEntries_.begin(), pendingEntries_.begin() + entry_count); - - // We don't know which paths are files and which ones are directories, and - // we want to avoid making a call to file_accessor_ for each entry. Open the - // files instead, invalid files are returned for directories. - - for (size_t i = 0; i < absolutePaths.size(); i++) { - FilePath &relativePath = relativePaths[i]; - FilePath &absolutePath = absolutePaths[i]; - if (FilePath::PathIsValid(absolutePath)) { - if (!AddFileEntryToZip(zipFile_, relativePath, absolutePath, options)) { - CALLING_CALL_BACK(callback, ERROR_CODE_ERRNO) - HILOG_INFO("%{public}s called, Failed to write file", __func__); - return false; - } - } else { - // Missing file or directory case. - struct tm *last_modified = GetCurrentSystemTime(); - if (!AddDirectoryEntryToZip(zipFile_, relativePath, last_modified, options)) { - CALLING_CALL_BACK(callback, ERROR_CODE_ERRNO) - HILOG_INFO("%{public}s called, Failed to write directory", __func__); - return false; - } - } - } - } - CALLING_CALL_BACK(callback, ERROR_CODE_OK) - return true; -} - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS diff --git a/zidl/bundle.json b/zidl/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..5152547cc088f0c6bd4885e60a8aef3c9ba33613 --- /dev/null +++ b/zidl/bundle.json @@ -0,0 +1,40 @@ +{ + "name": "@ohos/zidl", + "description": "提供自动生成Extension Js服务端及客户端接口文件的能力", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "foundation/aafwk/standard/zidl" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "zidl", + "subsystem": "aafwk", + "syscap": [], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "", + "ram": "", + "deps": { + "components": [ + "hiviewdfx_hilog_native", + "ipc", + "samgr_standard", + "utils_base" + ], + "third_party": [] + }, + "build": { + "sub_component": [ + "//foundation/aafwk/standard/zidl/test/native:zidl_client_test", + "//foundation/aafwk/standard/zidl/test/native:zidl_server_test" + ], + "inner_kits": [], + "test": [] + } + } +} \ No newline at end of file diff --git a/zidl/test/native/BUILD.gn b/zidl/test/native/BUILD.gn index eb3f2ce06cad826f8b9843953f7f0f7c4da8ff1c..8dc9839a534d3031f43865f20e9d586abb410ba7 100644 --- a/zidl/test/native/BUILD.gn +++ b/zidl/test/native/BUILD.gn @@ -44,7 +44,7 @@ ohos_executable("zidl_server_test") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "zidl" } ohos_executable("zidl_client_test") { @@ -65,5 +65,5 @@ ohos_executable("zidl_client_test") { ] subsystem_name = "aafwk" - part_name = "aafwk_standard" + part_name = "zidl" }